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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_incfact_setjoinuri</obj_name>
  <obj_hashval>02aa6599d9ef66bfc16c1dc3c40d1365</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_incfact_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 03.09.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_INCFACT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_incfact_setparams</obj_name>
  <obj_hashval>0e33605f7802271043f90d5daeef0b13</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_incfact_setparams(pdatas character varying, pdataf character varying, panual numeric DEFAULT 0, popt1 numeric DEFAULT 0, popt2 numeric DEFAULT 0, popt3 numeric DEFAULT 0, popt4 numeric DEFAULT 0, v_codjob1 numeric DEFAULT 0, pdataref character varying DEFAULT NULL::character varying, pallag numeric DEFAULT 1, pallpart numeric DEFAULT 1, pcriteriu numeric DEFAULT 0, psumarincfact numeric DEFAULT 0, ptotfact numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;

  gDataS     VARCHAR(10);
  gDataF     VARCHAR(10);

  dDataS     date;
  dDataF     date;
begin
  --Bogdan 03.09.2020
  gDataS     := pDataS;
  gDataF     := pDataF;

  xLunaAnIni := Extract(Year from to_date(gDataS,'dd.mm.yyyy'))*12 + 1;
  xLunaAnFin := Extract(Year from to_date(gDataF,'dd.mm.yyyy'))*12;



  dDataS := to_Date(gDataS,'dd.mm.yyyy');
  dDataF := to_Date(gDataF,'dd.mm.yyyy');

  IF  V_CODJOB1 &gt; 0 THEN
    select PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.adataini , PKG_ORA_LISTS_SET_INTERVAL_DINAMIC. adatafin
    from PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, dDataS, dDataF, xLunaAnIni, xLunaAnFin) into dDataS,dDataF;
  END IF;

  PERFORM PKG_ORA_LISTS_SET_INTERVAL_LISTARE(dDataS, dDataF);

  gDatas := to_char(dDataS, 'dd.mm.yyyy');
  gDataF := to_char(dDataF, 'dd.mm.yyyy');

  perform set_config('PKG_LIST_BASE_INCFACT.gDataS',gDatas,false);
  perform set_config('PKG_LIST_BASE_INCFACT.gDataF',gDataF,false);

  perform set_config('PKG_LIST_BASE_INCFACT.gAnual'       ,pAnual::varchar       ,false);
  perform set_config('PKG_LIST_BASE_INCFACT.gOpt1'        ,pOpt1::varchar        ,false);
  perform set_config('PKG_LIST_BASE_INCFACT.gOpt2'        ,pOpt2::varchar        ,false);
  perform set_config('PKG_LIST_BASE_INCFACT.gOpt3'        ,pOpt3::varchar        ,false);
  perform set_config('PKG_LIST_BASE_INCFACT.gOpt4'        ,pOpt4::varchar        ,false);
  perform set_config('PKG_LIST_BASE_INCFACT.gDataRef'     ,pDataRef              ,false);
  perform set_config('PKG_LIST_BASE_INCFACT.gAllAg'       ,pAllAg::varchar       ,false);
  perform set_config('PKG_LIST_BASE_INCFACT.gAllPart'     ,pAllPart::varchar     ,false);
  perform set_config('PKG_LIST_BASE_INCFACT.gCriteriu'    ,pCriteriu::varchar    ,false);
  perform set_config('PKG_LIST_BASE_INCFACT.gSumarIncFact',pSumarIncFact::varchar,false);
  perform set_config('PKG_LIST_BASE_INCFACT.gTotFact'     ,pTotFact::varchar     ,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_inlocuireagent_processlist</obj_name>
  <obj_hashval>3c4283b54a6ca2fa2cb97519f68fcdc9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_inlocuireagent_processlist(tmp_name character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'npers oa, npers na';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 01.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_INLOCUIREAGENT.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMP_NAME || '(OldAgent, NewAgent' || gUserFields || ')
  SELECT oa.nume||'' ''||oa.prenume, na.nume||'' ''||na.prenume ' || gUserAlias || '
  FROM   TMP_InlocuireAgent t
        LEFT JOIN npers oa ON oa.codpers  = t.oldcodagent
        LEFT JOIN npers na ON na.codpers  = t.newcodagent' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_inlocuireagent_setjoinuri</obj_name>
  <obj_hashval>49bd32299d7bb6183b3d37078c9eb8c6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_inlocuireagent_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_INLOCUIREAGENT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_intrari_processlist</obj_name>
  <obj_hashval>d4a9e2db8856b651ee19a05031bce3c4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_intrari_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gSuplCols   varchar:= 'TMP_LST_INTRARI I1, INTRARI I, NARTOBJ NAO, NART NA, NCLASEA NCA, NUM UM1, NUM UM2, NPART NP, NAGENDA SSOC, NLOCALIT LOCSOC, NJUDET JUDSOC, NZONE ZONASOC,' || 'NPARTCODFISC FISC, NCLASEP NCP, NGEST NG, NGEST NGSERV, NSUBUNIT NS, NSUBUNIT NSUB, NMONEDE MON, NPART PROD, NARTOBJ1 NAO1, NART1 NA1,' || 'NTVA1 NT1, NCONT NC, CONTRACT CONTR, COMANDA C, OFERTA O, IOART IOA, IOPART IOP';
  gUserFields varchar:= '';
  gUserAlias  varchar:= '';
  gNullAlias  varchar:= '';
  gSuplJoins  varchar:= '';
BEGIN
  --Florin 11.08.2020
  call pkg_list_struct_startsuplcols();

  call pkg_list_struct_addsupltabs(gSuplCols, 'TMP_UTILIZATOR', 'UTILIZATOR', 'UTILIZATOR.CODUTILIZATOR = I.USERID',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTCODFISC'  , 'CFF'       , 'CFF.COD_CODFISCAL = I.CODFISCAL'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'      , 'PD'        , 'PD.CODPART = NP.CODPART'            ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTTR'       , 'NPTR'      , 'NPTR.CODPARTTR = I1.DELEGAT'        ,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, 'NARTCLI'       , 'ACLI'      , 'ACLI.CODARTCLI = PKG_LIST_BASE_UTILS_GETCODARTCLI(I1.CODOBIECT, I.PARTENER, NP.CODCLASA)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTAMB'       , 'AA'        , 'AA.CODOBIECT = I1.CODOBIECT AND AA.UMSEC = I1.UMSEC',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CONTRACT1'     , 'CONTR1'    , 'CONTR1.CODCONTRACT1 = I1.CODCONTRACT1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'OFERTA1'       , 'O1'        , 'O1.CODOFERTA1 = I1.CODOFERTA1'        ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA1'      , 'C1'        , 'C1.CODCOMANDA1 = I1.CODCOMANDA1'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTRECOST'    , 'CC'        , 'CC.CODCENTRU = I1.CODCENTRU'          ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARI1'      , 'INTR1'     , 'INTR1.CODINTR1 = I1.CODINTR1'         ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARIF'      , 'INTRF'     , 'INTRF.CODINTR = I1.CODINTR'           ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARIF1'     , 'INTRF1'    , 'INTRF1.CODINTR1 = I1.CODINTR1'        ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDF'       , 'CFEXT'     , 'CFEXT.CODCOMANDA = C.CODCOMANDA'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDF1'      , 'CF1EXT'    , 'CF1EXT.CODCOMANDA1 = I1.CODCOMANDA1'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'ANALIZANOD'    , 'ANOD'      , 'ANOD.CODANALIZANOD = I1.CODANALIZANOD',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'ANALIZA'       , 'ANALIZ'    , 'ANALIZA.CODANALIZ = 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, 'NTARI'         , 'TARASOC'   , 'TARASOC.CODTARA = LOCSOC.CODTARA'           ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA'       , 'SPROD'     , 'SPROD.CODPART = NAO.CODPRODUCATOR AND SPROD.SEDIUSOCIAL BETWEEN 4 AND 7 AND Coalesce(SSOC.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, 'NARTOBJTRAD'   , 'TRAD'      , 'TRAD.CODOBIECT = NAO.CODOBIECT AND TRAD.CODLIMBA = ' || COALESCE(fnc_getvalconstantalucru('LimbaDenArt'), ''));
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_INTRARI.gSuplCols', gSuplCols,false);

  PERFORM PKG_LIST_BASE_INTRARI_setVar(aLISTID, aLISTVER);
  PERFORM PKG_LIST_BASE_INTRARI_InsertIntrari(tmpName, gUserFields, gUserAlias, gNullAlias, gSuplJoins);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_intrari_setvar</obj_name>
  <obj_hashval>4eb065037bcd1d8f4c1adf1582fe8c79</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_intrari_setvar(alistid numeric, alistver numeric)
 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;
  wmeRes    boolean;
BEGIN
  --Florin 02.05.2024 - fixat 61862
  --Adina 18.02.2021 - tichet 43506
  --Florin 10.08.2020
  PERFORM set_config('PKG_LIST_BASE_INTRARI.CT_UM_ART' , 1 ::varchar      ,false);
  PERFORM set_config('PKG_LIST_BASE_INTRARI.pLISTID'   , alistid ::varchar,false);
  PERFORM set_config('PKG_LIST_BASE_INTRARI.pLISTVER'  , alistver::varchar,false);
  PERFORM set_config('PKG_LIST_BASE_INTRARI.vUm'       , pUm     ::varchar,false);
  PERFORM set_config('PKG_LIST_BASE_INTRARI.vLista'    , pLista  ::varchar,false);
  vFiltru  := ' WHERE Coalesce(i1.cant,0) &lt;&gt; 0 AND i.anulat = 0';
  IF pInclNeop = 0 THEN
    vFiltru := COALESCE(vFiltru, '') ||' AND i.operat = 1 ';
  END IF;
  vFiltru := COALESCE(vFiltru, '') || '
    AND NOT (i1.tiplinie IN (''G'',''T'') AND Coalesce(i1.contdiscount,0) = 0) ';
  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
    vFiltru := COALESCE(vFiltru, '') ||' AND i.datadoc ' || sData ||' ';
  ELSE
    vFiltru := COALESCE(vFiltru, '') ||' 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'') ';
  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_INTRARI.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(i.datadoc,''dd.mm.yyyy'') )';
  ELSE
    sCursRef := ', 1 ';
  END IF;
  PERFORM set_config('PKG_LIST_BASE_INTRARI.sCursRef', sCursRef, false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_intrarisint_processlist</obj_name>
  <obj_hashval>e565d0452eb4afe8823c72acb8bc5cab</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_intrarisint_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gUserFields varchar;
  gUserAlias  varchar;
  gNullAlias  varchar;
  gSuplCols   varchar := 'INTRARI I, NPART NP, NAGENDA SSOC, NLOCALIT LOCSOC, NJUDET JUDSOC, NZONE ZONASOC, NPARTCODFISC FISC, NCLASEP NCP, NGEST NG, NSUBUNIT NS,' || 'NSUBUNIT NSUB, NMONEDE MON, TMP_UTILIZATOR UTILIZATOR, NTARI TARASOC, NPARTTR NPTR, CONTRACT CONTR';
  gSuplJoins  varchar;
BEGIN
  --Florin 10.08.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTCODFISC', 'CFF'  , 'CFF.COD_CODFISCAL = I.CODFISCAL',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'    , 'PD'   , 'PD.CODPART = NP.CODPART'        ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARIF'    , 'INTRF', 'INTRF.CODINTR = I.CODINTR'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRFAST'    , 'IFAST', 'IFAST.CODINTR = I.CODINTR'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRAST'     , 'IAST' , 'IAST.CODINTR = I.CODINTR'       ,NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_INTRARISINT.gSuplCols',gSuplCols,false);

  PERFORM pkg_list_base_intrari_setVar(aLISTID, aLISTVER);
  PERFORM pkg_list_base_intrari_InsertSinteza(tmpName, gUserFields, gUserAlias, gNullAlias, gSuplJoins);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_inventar_rest_processlist</obj_name>
  <obj_hashval>e13e92f04105f198ec1ec86d6a345521</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_inventar_rest_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  S               varchar := '';
  vCodRestaurant  varchar := current_setting('PKG_LIST_BASE_INVENTAR_REST.vCodRestaurant', true);
BEGIN
  --Adina 25 septembrie 2020
  S :=
  'INSERT INTO ' || TMPNAME ||
  '(DENUMIRE, DENUM, STOCINITIAL, INTRARI, IESIRI, PRET, DIMINUATE, TRANSFERATE, VANDUTE, CONSUMATE, DISCOUNT, NEPRELUATE)
   SELECT
     O.DENUMIRE,
     U1.DEN_UM1,
     coalesce(BS.STOCINITIAL, 0),
     coalesce(BS.INTRARI, 0),
     coalesce(BS.IESIRI, 0),
     BS.PRET,
     coalesce(BS.DIMINUATE, 0),
     coalesce(BS.TRANSFERATE, 0),
     coalesce(BS.VANDUTE, 0),
     coalesce(BS.CONSUMATE, 0),
     coalesce(BS.DISCOUNT, 0),
     coalesce(BS.NEPRELUATE, 0)
   FROM
     TMP_BALANTA_STOC BS,
     NARTOBJ O,
     NART A,
     NUM1 U1
  WHERE
     O.CODOBIECT = BS.CODOBIECT
     AND A.CODARTICOL = O.CODARTICOL
     AND U1.CODUM = A.UM
     AND NOT EXISTS (SELECT RA.COD FROM restartinactive RA WHERE RA.CODOBIECT = BS.CODOBIECT AND RA.CODRESTAURANT = ' || coalesce(vCodRestaurant,'') || ')
     AND U1.SECUNDARA = 0';
  PERFORM LIST_EXECUTE_IMMEDIATE(s, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_inventar_setparams</obj_name>
  <obj_hashval>399e61911d83f0da473cd042a657c06e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_inventar_setparams(acodinventar numeric, pid 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 25 septembrie 2020
  perform set_config('PKG_LIST_BASE_INVENTAR.vDataS',sDataS,false);
  perform set_config('PKG_LIST_BASE_INVENTAR.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_INVENTAR.p_CodInventar',(aCodInventar)::varchar,false);
  perform set_config('PKG_LIST_BASE_INVENTAR.vID'          ,(pID)::varchar         ,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ioart_processlist</obj_name>
  <obj_hashval>3b943569f6b58d629dbf542e774d242c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ioart_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

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

sInsert := 'INSERT INTO ' || tmpName || '(
      DENUMIRE,REPREZ,DIFERENTE,CHELTUIELI,VENITURI,PLUSINVENTAR, MINUSINVENTAR,CHELTTVACOLECTAT,PROVIZION,CHELTPROVIZION,CONTROTUNJIRI,DIVERSE,
      ACCIZELATRANSFER,DESCARCAREG,CONTABGEST,BAZA,DIFPRET,ARETVANEEX,TVANEEX,MG,DELA,PANALA' || gUserFields || ')
    WITH IO1 AS (
      SELECT
        CODIOART,
        CONT, DIFERENTE, CHELTUIELI, VENITURI, PLUSINVENTAR, MINUSINVENTAR, CHELTTVACOLECTAT,PROVIZION,CHELTPROVIZION, CONTROTUNJIRI, DIVERSE,
        ACCIZELATRANSFER, DESCARCAREG, CONTABGEST, BAZA, DIFPRET, ARETVANEEX, TVANEEX, MG,
        ANSTART * 12 + LUNASTART AnLunaStart, ANSTART, LUNASTART,
        Coalesce(Lead(ANSTART *12 +LUNASTART) OVER (PARTITION BY CODIOART ORDER BY ANSTART, LUNASTART) - 1,current_setting(''PKG_LIST_SELECTLUNAAN.vLunaStop'', False)::numeric) AnLunaStop
      FROM IOART1
      WHERE (ANSTART *12 +LUNASTART) &lt;= current_setting(''PKG_LIST_SELECTLUNAAN.vLunaStop'', False)::numeric AND
            (ANSTART *12 +LUNASTART) &gt;= current_setting(''PKG_LIST_SELECTLUNAAN.vLunaStart'', False)::numeric
      ORDER BY CODIOART)

    SELECT
      IO.DEN_IOART,
      Coalesce(NCCONT.SIMBOL,''--''), Coalesce(NCDIF.SIMBOL,''--''), Coalesce(NCCHELT.SIMBOL,''--''), Coalesce(NCVENIT.SIMBOL,''--''),
      Coalesce(NCPLINV.SIMBOL,''--''), Coalesce(NCMIINV.SIMBOL,''--''), Coalesce(NCTVAC.SIMBOL,''--''), Coalesce(NCPROV.SIMBOL,''--''), Coalesce(NCPROVK.SIMBOL,''--''), Coalesce(NCROT.SIMBOL,''--''), Coalesce(NCDIV.SIMBOL,''--''),
      Coalesce((Case  When io1.accizelatransfer=0 then ''NU'' else ''DA'' end),''--''), Coalesce((Case  When io1.descarcareg=0 then ''NU'' else ''DA'' end),''--''),
      Coalesce((Case  When io1.contabgest=0 then ''NU'' else ''DA'' end),''--''), Coalesce((Case  When io1.baza=0 then ''NU'' else ''DA'' end),''--''),
      Coalesce((Case  When io1.difpret=0 then ''NU'' else ''DA'' end),''--''), Coalesce((Case  When io1.aretvaneex=0 then ''NU'' else ''DA'' end),''--''), Coalesce(IO1.TVANEEX,''--''),
      (Case  When Coalesce(io1.mg,0)= 1 then ''FIFO'' When Coalesce(io1.mg,0)= 2 then ''LIFO'' When Coalesce(io1.mg,0)= 3 then ''PMP'' When Coalesce(io1.mg,0)= 4 then ''IDS'' When Coalesce(io1.mg,0)= 5 then ''VAL'' else ''nedef.'' end),
      to_char(IO1.AnStart,''fm0000'')||''.''||to_char(IO1.LunaStart,''fm00'')||''.''||pkg_list_base_utils_decode_luna(IO1.LunaStart),
             (Case when MOD(IO1.AnLunaStop,12) = 0 then to_char(Trunc(IO1.AnLunaStop/12-1),''fm0000'')||''.12.''||pkg_list_base_utils_decode_luna(12)
                   else to_char(Trunc(IO1.AnLunaStop/12),''fm0000'')||''.''||to_char(MOD(IO1.AnLunaStop,12),''fm00'')||''.''||pkg_list_base_utils_decode_luna(MOD(IO1.AnLunaStop,12)) end)
      ' || gUserAlias || '
    FROM IO1
      INNER JOIN IOART IO      ON IO.CODIOART     = IO1.CODIOART
      LEFT  JOIN NCONT NCCONT  ON NCCONT.CODCONT  = IO1.CONT
      LEFT  JOIN NCONT NCDIF   ON NCDIF.CODCONT   = IO1.DIFERENTE
      LEFT  JOIN NCONT NCCHELT ON NCCHELT.CODCONT = IO1.CHELTUIELI
      LEFT  JOIN NCONT NCVENIT ON NCVENIT.CODCONT = IO1.VENITURI
      LEFT  JOIN NCONT NCPLINV ON NCPLINV.CODCONT = IO1.PLUSINVENTAR
      LEFT  JOIN NCONT NCMIINV ON NCMIINV.CODCONT = IO1.MINUSINVENTAR
      LEFT  JOIN NCONT NCTVAC  ON NCTVAC.CODCONT  = IO1.CHELTTVACOLECTAT
      LEFT  JOIN NCONT NCPROV  ON NCPROV.CODCONT  = IO1.PROVIZION
      LEFT  JOIN NCONT NCPROVK ON NCPROVK.CODCONT = IO1.CHELTPROVIZION
      LEFT  JOIN NCONT NCROT   ON NCROT.CODCONT   = IO1.CONTROTUNJIRI
      LEFT  JOIN NCONT NCDIV   ON NCDIV.CODCONT   = IO1.DIVERSE ' || gSuplJoins;
--  insert into X(view_name, test) values('2 ioart_processlist', sInsert);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iobank_processlist</obj_name>
  <obj_hashval>0f79d673e3a6f11b8efcfe59a0cae20d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iobank_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
  --Florin 11.01.2023 - fixat 56769
  --Florin 28.12.2022 - coloane suplimentare
  GSuplCols := 'IOBANK IO';

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

  sInsert := 'INSERT INTO ' || coalesce(tmpName, '') || '(DENUMIRE, CONT, CONTDOBANDA, CONTCOMISION, CONTCHELTUIELI, CONTVENITURI, DELA, PANALA' || gUserFields || ')
        WITH IO1 AS (
        SELECT
          CODIOBANK, CONT, DOBANDA, COMISION, CHELTUIELICV, VENITURICV,
          ANSTART * 12 + LUNASTART AnLunaStart, ANSTART, LUNASTART,
          COALESCE(Lead(ANSTART *12 +LUNASTART) OVER (PARTITION BY CODIOBANK ORDER BY ANSTART, LUNASTART) - 1,current_setting(''PKG_LIST_SELECTLUNAAN.vLunaStop'', False)::numeric) AnLunaStop
        FROM IOBANK1
        WHERE (ANSTART *12 +LUNASTART) &lt;= current_setting(''PKG_LIST_SELECTLUNAAN.vLunaStop'', False)::numeric
        ORDER BY CODIOBANK
      )
    SELECT
      IO.DEN_IOBANK, COALESCE(NC.SIMBOL,''-''), COALESCE(NCDob.SIMBOL,''-''), COALESCE(NCCom.SIMBOL,''-''), COALESCE(NCChe.SIMBOL,''-''), COALESCE(NCVen.SIMBOL,''-''),
      to_char(IO1.AnStart,''fm0000'')||''.''||to_char(IO1.LunaStart,''fm00'')||''.''||pkg_list_base_utils_decode_luna(IO1.LunaStart),
      (CASE WHEN MOD(IO1.AnLunaStop,12)=0 THEN
        to_char(Trunc(IO1.AnLunaStop/12-1),''fm0000'')||''.12.''||pkg_list_base_utils_decode_luna(12)
        ELSE to_char(Trunc(IO1.AnLunaStop/12),''fm0000'')||''.''||to_char(MOD(IO1.AnLunaStop,12),''fm00'')||''.''||pkg_list_base_utils_decode_luna(MOD(IO1.AnLunaStop,12)) END )
        ' || coalesce(gUserAlias, '') || '
    FROM IO1
      INNER JOIN IOBANK IO    ON IO.CODIOBANK  = IO1.CODIOBANK
      LEFT  JOIN NCONT  NC    ON NC.CODCONT    = IO1.CONT
      LEFT  JOIN NCONT  NCDob ON NCDob.CODCONT = IO1.DOBANDA
      LEFT  JOIN NCONT  NCCom ON NCCom.CODCONT = IO1.COMISION
      LEFT  JOIN NCONT  NCChe ON NCChe.CODCONT = IO1.CHELTUIELICV
      LEFT  JOIN NCONT  NCVen ON NCVen.CODCONT = IO1.VENITURICV' || gSuplJoins || '
      WHERE ((IO1.AnLunaStart &lt;= current_setting(''PKG_LIST_SELECTLUNAAN.vLunaStop'', False)::numeric) AND (IO1.AnLunaStop  &gt;= current_setting(''PKG_LIST_SELECTLUNAAN.vLunaStart'', False)::numeric))';

  perform LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iopart_processlist</obj_name>
  <obj_hashval>9595a0476a447b19e6b49b6337487a79</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iopart_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
  --05.05.2021- sincronizare Oracle
  gSuplCols := '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_IOPART.gSuplCols', 'IOPART IO', false);


  sInsert := 'INSERT INTO ' || coalesce(tmpName, '') || '(
      DENUMIRE,CONTFURNIZOR,CONTCLIENT,CONTFURNAVANS,CONTCLIENTAVANS,CONTFURNAVIZ, CONTCLIENTAVIZ,CONTFURNMF,CONTCREDITD,
      CONTDEBITD,CONTLITIGII,CONTFURNAVS,CONTFURNAVIC,CONTFURNAVIN,CONTTERTI,TVANEEXF,TVANEEXC,TIP,DELA,
      PANALA' || gUserFields || ')
    WITH IO1 AS (
          SELECT
            CODIOPART, CONTFURNIZOR, CONTCLIENT, CONTFURNAVANS, CONTCLIENTAVANS, CONTFURNAVIZ, CONTCLIENTAVIZ, CONTFURNMF, CONTCREDITD,
            CONTDEBITD, CONTLITIGII, CONTFURNAVS, CONTFURNAVIC, CONTFURNAVIN, CONTTERTI, TVANEEXF, TVANEEXC, TIP,
            ANSTART * 12 + LUNASTART AnLunaStart, ANSTART, LUNASTART,
            Coalesce(Lead(ANSTART *12 +LUNASTART) OVER (PARTITION BY CODIOPART ORDER BY ANSTART, LUNASTART) - 1,current_setting(''PKG_LIST_SELECTLUNAAN.vLunaStop'', False)::numeric) AnLunaStop
          FROM IOPART1
        WHERE (ANSTART *12 +LUNASTART) &lt;= current_setting(''PKG_LIST_SELECTLUNAAN.vLunaStop'', False)::numeric AND
              (ANSTART *12 +LUNASTART) &gt;= current_setting(''PKG_LIST_SELECTLUNAAN.vLunaStart'', False)::numeric
    ORDER BY CODIOPART)
    SELECT
      IO.DEN_IOPART, Coalesce(NCFURN.SIMBOL,''--''), Coalesce(NCCL.SIMBOL,''--''), Coalesce(NCFAV.SIMBOL,''--''), Coalesce(NCCLAV.SIMBOL,''--''),
      Coalesce(NCFAVIZ.SIMBOL,''--''), Coalesce(NCCLAVIZ.SIMBOL,''--''), Coalesce(NCFMF.SIMBOL,''--''), Coalesce(NCCRD.SIMBOL,''--''),
      Coalesce(NCDEBD.SIMBOL,''--''), Coalesce(NCLIT.SIMBOL,''--''), Coalesce(NCFAVS.SIMBOL,''--''), Coalesce(NCFAVC.SIMBOL,''--''),
      Coalesce(NCFAVIN.SIMBOL,''--''), Coalesce(NCTERTI.SIMBOL,''--''), Coalesce(IO1.TVANEEXF,''--''), Coalesce(IO1.TVANEEXC,''--''),
      (Case  When Coalesce(IO1.TIP,0)= 0 then  ''--'' When Coalesce(IO1.TIP,0)= 1 then  ''Clasic'' When Coalesce(IO1.TIP,0)= 2 then  ''Leasing'' else ''nedef.'' end),
      to_char(IO1.AnStart,''fm0000'')||''.''||to_char(IO1.LunaStart,''fm00'')||''.''||pkg_list_base_utils_decode_luna(IO1.LunaStart),
      ( CASE WHEN MOD(IO1.AnLunaStop,12) = 0
              THEN to_char(Trunc(IO1.AnLunaStop/12-1),''fm0000'')||''.12.''||pkg_list_base_utils_decode_luna(12)
              ELSE to_char(Trunc(IO1.AnLunaStop/12),''fm0000'')||''.''||to_char(MOD(IO1.AnLunaStop,12),''fm00'')||''.''||pkg_list_base_utils_decode_luna(MOD(IO1.AnLunaStop,12)) END)
      ' || gUserAlias || '
    FROM IO1
      INNER JOIN IOPART IO      ON IO.CODIOPART     = IO1.CODIOPART
      LEFT  JOIN NCONT NCFURN   ON NCFURN.CODCONT   = IO1.CONTFURNIZOR
      LEFT  JOIN NCONT NCCL     ON NCCL.CODCONT     = IO1.CONTCLIENT
      LEFT  JOIN NCONT NCFAV    ON NCFAV.CODCONT    = IO1.CONTFURNAVANS
      LEFT  JOIN NCONT NCCLAV   ON NCCLAV.CODCONT   = IO1.CONTCLIENTAVANS
      LEFT  JOIN NCONT NCFAVIZ  ON NCFAVIZ.CODCONT  = IO1.CONTFURNAVIZ
      LEFT  JOIN NCONT NCCLAVIZ ON NCCLAVIZ.CODCONT = IO1.CONTCLIENTAVIZ
      LEFT  JOIN NCONT NCFMF    ON NCFMF.CODCONT    = IO1.Contfurnmf
      LEFT  JOIN NCONT NCCRD    ON NCCRD.CODCONT    = IO1.CONTCREDITD
      LEFT  JOIN NCONT NCDEBD   ON NCDEBD.CODCONT   = IO1.CONTDEBITD
      LEFT  JOIN NCONT NCLIT    ON NCLIT.CODCONT    = IO1.CONTLITIGII
      LEFT  JOIN NCONT NCFAVS   ON NCFAVS.CODCONT   = IO1.CONTFURNAVS
      LEFT  JOIN NCONT NCFAVC   ON NCFAVC.CODCONT   = IO1.CONTFURNAVIC
      LEFT  JOIN NCONT NCFAVIN  ON NCFAVIN.CODCONT  = IO1.CONTFURNAVIN
      LEFT  JOIN NCONT NCTERTI  ON NCTERTI.CODCONT  = IO1.CONTTERTI' || gSuplJoins;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iopers_processlist</obj_name>
  <obj_hashval>85842e6299ea4f0b1cc77638e47aa1b3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iopers_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
  --Florin 28.12.2022 - coloane suplimentare
  gSuplCols := 'IOPERS IO';

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

  sInsert := 'INSERT INTO ' || coalesce(tmpName, '') || '(
        DENUMIRE,CONTAVANSDECONT,CONTIMPUTATII,CONTGARANTII,CONTALTERETINERI,CONTAVANS,CONTLIKI,CONTNERIDICATE,CONTBOALA,
            CONTPARTSAL,CONTNATURA,CONTECHIPAMENT,CONTIMPOZIT,DELA,PANALA' || coalesce(gUserFields, '') || ')
      WITH IO1 AS (
        SELECT
          CODIOPERS, CONTAVANSDECONT, CONTIMPUTATII, CONTGARANTII, CONTALTERETINERI, CONTAVANS, CONTLIKI, CONTNERIDICATE, CONTBOALA,
          CONTPARTSAL, CONTNATURA, CONTECHIPAMENT, CONTIMPOZIT,
          ANSTART * 12 + LUNASTART AnLunaStart, ANSTART, LUNASTART,
          COALESCE(Lead(ANSTART *12 +LUNASTART) OVER (PARTITION BY CODIOPERS ORDER BY ANSTART, LUNASTART) - 1,current_setting(''PKG_LIST_SELECTLUNAAN.vLunaStop'', False)::numeric) AnLunaStop
        FROM IOPERS1
        WHERE (ANSTART *12 +LUNASTART) &lt;= current_setting(''PKG_LIST_SELECTLUNAAN.vLunaStop'', False)::numeric
                  ORDER BY CODIOPERS)
      SELECT
        IO.DEN_IOPERS, COALESCE(NCDEC.SIMBOL,''--''), COALESCE(NCIMPUT.SIMBOL,''--''), COALESCE(NCGAR.SIMBOL,''--''), COALESCE(NCRET.SIMBOL,''--''),
        COALESCE(NCAV.SIMBOL,''--''), COALESCE(NCLIK.SIMBOL,''--''), COALESCE(NCNERID.SIMBOL,''--''), COALESCE(NCBO.SIMBOL,''--''), COALESCE(NCPSAL.SIMBOL,''--''),
        COALESCE(NCNAT.SIMBOL,''--''), COALESCE(NCEKIP.SIMBOL,''--''), COALESCE(NCIMP.SIMBOL,''--''),
        to_char(IO1.AnStart,''fm0000'')||''.''||to_char(IO1.LunaStart,''fm00'')||''.''||pkg_list_base_utils_decode_luna(IO1.LunaStart),
        (case when MOD(IO1.AnLunaStop,12) = 0 THEN
          to_char(Trunc(IO1.AnLunaStop/12-1),''fm0000'')||''.12.''||pkg_list_base_utils_decode_luna(12)
          ELSE to_char(Trunc(IO1.AnLunaStop/12),''fm0000'')||''.''||to_char(MOD(IO1.AnLunaStop,12),''fm00'')||''.''||pkg_list_base_utils_decode_luna(MOD(IO1.AnLunaStop,12)) END )
          ' || gUserAlias || '
      FROM IO1
        INNER JOIN IOPERS IO     ON IO.CODIOPERS    = IO1.CODIOPERS
        LEFT  JOIN NCONT NCDEC   ON NCDEC.CODCONT   = IO1.CONTAVANSDECONT
        LEFT  JOIN NCONT NCIMPUT ON NCIMPUT.CODCONT = IO1.CONTIMPUTATII
        LEFT  JOIN NCONT NCGAR   ON NCGAR.CODCONT   = IO1.CONTGARANTII
        LEFT  JOIN NCONT NCRET   ON NCRET.CODCONT   = IO1.CONTALTERETINERI
        LEFT  JOIN NCONT NCAV    ON NCAV.CODCONT    = IO1.CONTAVANS
        LEFT  JOIN NCONT NCLIK   ON NCLIK.CODCONT   = IO1.CONTLIKI
        LEFT  JOIN NCONT NCNERID ON NCNERID.CODCONT = IO1.CONTNERIDICATE
        LEFT  JOIN NCONT NCBO    ON NCBO.CODCONT    = IO1.CONTBOALA
        LEFT  JOIN NCONT NCPSAL  ON NCPSAL.CODCONT  = IO1.CONTPARTSAL
        LEFT  JOIN NCONT NCNAT   ON NCNAT.CODCONT   = IO1.CONTNATURA
        LEFT  JOIN NCONT NCEKIP  ON NCEKIP.CODCONT  = IO1.CONTECHIPAMENT
        LEFT  JOIN NCONT NCIMP   ON NCIMP.CODCONT   = IO1.CONTIMPOZIT' ||gSuplJoins;

  perform LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
end;

$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ipoasig_processlist</obj_name>
  <obj_hashval>433f7c85e70211209322f4298824f11b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ipoasig_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 17.06.2022 - sinc. Oracle
  --Florin 09.07.2021 - sinc. Oracle (40182)
  --Adina 02.04.2021 - alstart, alstop
  --Bogdan 22.09.2020
  gSuplCols := 'nartobj obj, nart art';

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

  sInsert := 'INSERT INTO '|| TMPNAME|| '(
            NrInventar,
            Articol,
            Gestiune,
            ValIn,
            ValRest,
            DataAchiz,
            DataPunere,
            Cont,
            Ipoteca1,
            Ipoteca2,
            Ipoteca3,
            NrAsig,
            DataAsig,
            ScadentaAsig,
            Clasa,
            Asigurator,
            ValAsig'
            || coalesce (gUserFields ,'')
            || ')
          ';
  sSelect := '
        select mfix.NrInventar,
          obj.denumire Articol,
          g.den_gest   Gestiune,
          ns.pret      ValIn,
          NS.Pret -
          case
            when MFIX1.TIPREEVAL = 1 THEN 0
            else
              case
                when coalesce (MFIX1.DURATAF,0) &lt;&gt; 0
                  and MFIX.ANINTRARE * 12 + MFIX.LUNAINTRARE &lt;= getAnLunaLucru()
                  and MFIX1.STARE = 1 then MFIX1.AMO + (NS.PRET - MFIX1.AMO) / MFIX1.DURATAF
                else MFIX1.AMO
              end
          end ValRest,
          NS.DataAchiz,
          ev.datastart                        DataPunere,
          C.Simbol                            Cont,
          p1.den_part                         Ipoteca1,
          p2.den_part                         Ipoteca2,
          p3.den_part                         Ipoteca3,
          coalesce (asg.nrdoc,''...nedefinit...'') NrAsig,
          asg.datastart                       DataAsig,
          asg.termen                          ScadentaAsig,
          cls.den_clasemf                     Clasa,
          pasg.den_part                       Asigurator,
          asg1.valasig ValAsig '
            || coalesce (gUserAlias ,'')|| '
        from mifix             mfix
          left join mifix1     mfix1 on mfix.codmifix    = mfix1.codmifix
          left join nirstoc    ns    on mfix1.codnirstoc = ns.codnirstoc
          left join nartobj    obj   on obj.codobiect    = ns.codobiect
          left join nart       art   on obj.codarticol   = art.codarticol
          left join nir              on nir.codnir       = ns.codnir
          left join ngest      g     on g.codgest        = nir.gest
          LEFT JOIN IOART1     IOA1  ON NS.CODIOART      = IOA1.CODIOART
          LEFT JOIN NCONT      C     ON C.CODCONT        = IOA1.CONT
          left join evidentamf ev    on ev.codmifix      = mfix.codmifix
          left join npart      p1    on p1.codpart       = ev.codpart1
          left join npart      p2    on p2.codpart       = ev.codpart2
          left join npart      p3    on p3.codpart       = ev.codpart3
          left join asigurari1 asg1  on asg1.codmifix    = mfix.codmifix
          left join asigurari  asg   on asg.codasigurare = asg1.codasigurare
          left join nclasemf   cls   on cls.codclasemf   = asg.codclasemf
          left join npart      pasg  on pasg.codpart     = asg.codpart
        where
              (mfix1.anstart * 12 + mfix1.lunastart) = (select max (mfix2.anstart * 12 + mfix2.lunastart) from mifix1 mfix2 where mfix2.codmifix = mfix.codmifix)
          and (mfix1.anstart * 12 + mfix1.lunastart) BETWEEN IOA1.ALStart and IOA1.ALStop '
            || coalesce ( (PKG_LIST_BASE_UTILS_COND_SUBUNIT ('G', 'CODSUBUNIT',NULL,NULL)) ::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_ipoasig_setjoinuri</obj_name>
  <obj_hashval>5f50b33e23b882b563b96ef408531d56</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ipoasig_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 21.09.2020
  PERFORM pkg_list_struct_SetTableSpec (current_setting ('PKG_LIST_BASE_IPOASIG.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_istoricpreties_processlist</obj_name>
  <obj_hashval>2f540a9198b4347223be8fefe5ac3901</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_istoricpreties_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSelect         varchar := '';
  sUserJoin       varchar := '';
  pNrPretIntr     numeric;
  sArticol        varchar := '';
  gSuplCols        VARCHAR := '';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodObiect      NUMERIC := current_setting('PKG_LIST_BASE_ISTORICPRETIES.vCodObiect', true)::numeric;
BEGIN
  --Adina 13.10.2020
  pNrPretIntr := (fnc_GetValConstanta('NrPretIntr', getANLUCRU(), getlunalucru()))::numeric;

  IF  COALESCE(pNrPretIntr, 0) = 0 THEN
    pNrPretIntr := 10;
  END IF;

  sArticol := (SELECT PKG_NOM_ARTICOL_SET_CODOBIECT_ANALIZAT.WME_RESULT FROM PKG_NOM_ARTICOL_SET_CODOBIECT_ANALIZAT(NULL, vCodObiect));

  sInsert := 'INSERT INTO ' || TMPNAME || '(PREFIXDOC, NRDOC, DATADOC, CLIENT, PU_DOC, CANT, DEN_UM1, PACHIZ_RON, DEN_MONEDA, CURS, PACHIZ_VAL, MONTRANSF, CURSTRANSF, PUTRANSF, DATANIR, DEN_SUBUNIT, DEN_GEST' || gUserFields || ')';

  sSelect := '
  SELECT PREFIXDOC, NRDOC, DATADOC, CLIENT, PU_DOC, CANT, DEN_UM1, PACHIZ_RON, DEN_MONEDA, CURS, PACHIZ_VAL, MONTRANSF, CURSTRANSF, PUTRANSF, DATANIR, DEN_SUBUNIT, DEN_GEST' || gUserFields || '
  FROM (' || V_URMARIRE_PRETURI_VANZARE() || ') A_PG
  LIMIT $1 ';

  PERFORM pkg_globals_CheckDebugMode(sInsert || sSelect, aListID, aListVer);
  EXECUTE sInsert || sSelect USING pNrPretIntr;
  PERFORM pkg_list_Struct_GOLESTE_PARAM();
  PERFORM pkg_list_Struct_ADAUGA_PARAM('ARTICOL', sArticol);
  PERFORM pkg_list_Struct_ADAUGA_PARAM_EXT('NARTOBJEXT', 'CODOBIECT', vCodObiect);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_istoricpreties_setjoinuri</obj_name>
  <obj_hashval>c9c5cf1876dcfd2589005cad6a3f32fe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_istoricpreties_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 13.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_ISTORICPRETIES.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_istoricpreties_setparams</obj_name>
  <obj_hashval>7c3b2350e24388003eb5c5823adca25b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_istoricpreties_setparams(pcodobiect numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 13.10.2020
  perform set_config('PKG_LIST_BASE_ISTORICPRETIES.vCodObiect',(pCodObiect)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_istoricpretintr_processlist</obj_name>
  <obj_hashval>538eadeebacd7d01030c52819e19a165</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_istoricpretintr_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSelect1        varchar := '';
  sSelect2        varchar := '';
  sUserJoin       varchar := '';
  pNrPretIntr     numeric;
  sArticol        varchar := '';
  gSuplCols        VARCHAR := '';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodObiect      NUMERIC := current_setting('PKG_LIST_BASE_ISTORICPRETINTR.vCodObiect', true)::numeric;
BEGIN
  --Adina 13.10.2020
  pNrPretIntr := (fnc_GetValConstanta('NrPretIntr', getANLUCRU(), getlunalucru()))::numeric;

  IF  COALESCE(pNrPretIntr, 0) = 0 THEN
    pNrPretIntr := 10;
  END IF;

  sArticol := (SELECT PKG_NOM_ARTICOL_SET_CODOBIECT_ANALIZAT.WME_RESULT FROM PKG_NOM_ARTICOL_SET_CODOBIECT_ANALIZAT(NULL,vCodObiect));

  sInsert := 'INSERT INTO ' || TMPNAME || '(PREFIXDOC, NRDOC, DATADOC, FURNIZOR, CANT, DEN_UM1, PACHIZ_RON, DEN_MONEDA, CURS, PACHIZ_VAL, PVAL_DOC, PACHIZ_RON_FS, DATANIR, DEN_SUBUNIT, DEN_GEST' || gUserFields || ')';

  sSelect1 := '
  SELECT PREFIXDOC, NRDOC, DATADOC, FURNIZOR, CANT, DEN_UM1, PACHIZ_RON, DEN_MONEDA, CURS, PACHIZ_VAL, PVAL_DOC, PACHIZ_RON_FS, DATANIR, DEN_SUBUNIT, DEN_GEST' || gUserFields || '
  FROM ( '||V_URMARIRE_PRETURI()||' ) A_PG
  LIMIT $1 ';

  sSelect2 := '
  SELECT PREFIXDOC, NRDOC, DATADOC, FURNIZOR, CANT, DEN_UM1, PACHIZ_RON, DEN_MONEDA, CURS, PACHIZ_VAL, PVAL_DOC, PACHIZ_RON_FS, DATANIR, DEN_SUBUNIT, DEN_GEST' || gUserFields || '
  FROM ( '||V_URMARIRE_PRETURI_TRANSFVAL()||' ) B_PG
  LIMIT $1 ';

  PERFORM pkg_globals_CheckDebugMode(sInsert || sSelect1, aListID, aListVer);

  EXECUTE sInsert || sSelect1 USING pNrPretIntr;

  EXECUTE 'SELECT ' || coalesce(pNrPretIntr::varchar ,'0') || ' - COUNT(*) FROM ' || TMPNAME INTO pNrPretIntr;

  IF  pNrPretIntr &gt; 0 THEN
    PERFORM pkg_globals_CheckDebugMode(sInsert || sSelect2, aListID, aListVer);
    EXECUTE sInsert || sSelect2 USING pNrPretIntr;
  END IF;

  PERFORM pkg_list_Struct_GOLESTE_PARAM();
  PERFORM pkg_list_Struct_ADAUGA_PARAM('ARTICOL', sArticol);
  PERFORM pkg_list_Struct_ADAUGA_PARAM_EXT('NARTOBJEXT', 'CODOBIECT', vCodObiect);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_istoricpretintr_setjoinuri</obj_name>
  <obj_hashval>bd1673de7114e29a51bad83c9a3aefc6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_istoricpretintr_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 13.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_ISTORICPRETINTR.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_istoricpretintr_setparams</obj_name>
  <obj_hashval>0a29da028a9b91478c82a75d6081c7e1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_istoricpretintr_setparams(pcodobiect numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 13.10.2020
  perform set_config('PKG_LIST_BASE_ISTORICPRETINTR.vCodObiect',(pCodObiect)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_jobcorelrez_processlist</obj_name>
  <obj_hashval>341c033bc8f149b8c6a16f437a55c940</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_jobcorelrez_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'JOBCORELREZ JCZ, JOBCOREL JC, JOBLISTE1 JL1, JOBLISTE1 JL2';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 14 septembrie 2020
  --perform set_config('PKG_LIST_BASE_JOBCORELREZ.gSuplCols',('JOBCORELREZ JCZ, JOBCOREL JC, JOBLISTE1 JL1, JOBLISTE1 JL2')::varchar,false);
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_JOBCORELREZ.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    IDENTIFICATOR,
    VALOARE1,
    VALOARE2,
    TABLA1,
    LOOKUPFIELD1,
    VALDESCRIP1,
    LISTA1,
    TABLA2,
    LOOKUPFIELD2,
    VALDESCRIP2,
    LISTA2
  ' || gUserFields || ')
  SELECT
    JCZ.IDENTIFICATOR,
    JCZ.VALOARE1,
    JCZ.VALOARE2,
    JC.TABLA1,
    JC.LOOKUPFIELD1||'' + ''||JC.LOOKUPFIELD11,
    JC.VALDESCRIP1,
    L1.NAME LISTA1,
    JC.TABLA2,
    JC.LOOKUPFIELD2||'' + ''||JC.LOOKUPFIELD21,
    JC.VALDESCRIP2,
    L2.NAME LISTA2 ' || gUserAlias || '
  FROM JOBCORELREZ JCZ
    INNER JOIN JOBCOREL        JC  ON JCZ.CODCOREL = JC.CODCOREL
    INNER JOIN JOBLISTE1       JL1 ON JL1.CODJOB1  = JC.CODJOB1_1
    INNER JOIN JOBLISTE1       JL2 ON JL2.CODJOB1  = JC.CODJOB1_2
    INNER JOIN WINMADMIN.LISTS L1  ON JL1.LISTAID  = L1.LISTID AND JL1.LISTAVER = L1.LISTVER
    INNER JOIN WINMADMIN.LISTS L2  ON JL2.LISTAID  = L2.LISTID AND JL2.LISTAVER = L2.LISTVER' || gSuplJoins || '
  WHERE JC.CODJOB = ' || coalesce(current_setting('PKG_LIST_BASE_JOBCORELREZ.vCodJob', true),'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_jobcorelrez_setparams</obj_name>
  <obj_hashval>0c7324a703b230fbce8bf2339ebde2dd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_jobcorelrez_setparams(pcodjob 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_JOBCORELREZ.vDataS',sDataS,false);
  perform set_config('PKG_LIST_BASE_JOBCORELREZ.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_JOBCORELREZ.vCodJob',(pCodJob)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_jurncump_setjoinuri</obj_name>
  <obj_hashval>91bb559ba02b7d0d0bc63679279c73c7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_jurncump_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 28.07.2020

  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_JURNCUMP.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_jurncump_setperioada</obj_name>
  <obj_hashval>fc3f30359289118de54f5efd3e484260</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_jurncump_setperioada(pan numeric, pluna numeric, ptip numeric, psubunit numeric, pexclnoeconomicactiv numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnLunaIni NUMERIC;
  vAnLunaFin NUMERIC := pAn*12+pLuna;
  vSubunit   NUMERIC := Coalesce(pSubunit, getsubunitate());
BEGIN
  --Florin 04.08.2020
  IF    pTip = 3/*anual      */ THEN vAnLunaIni := pAn*12+ 1;
  ELSIF pTip = 2/*semestrial */ THEN vAnLunaIni := pAn*12+ CASE WHEN pLuna &gt; 6 THEN 7 ELSE 1 END;
  ELSIF pTip = 1/*trimestrial*/ THEN vAnLunaIni := pAn*12+ CASE WHEN pLuna &gt; 9 THEN 10 WHEN pLuna &gt; 6 THEN 7 WHEN pLuna &gt; 3 THEN 4 ELSE 1 END;
  ELSIF pTip = 0/*lunar      */ THEN vAnLunaIni := pAn*12+ pLuna;
  END IF;

  perform set_config('PKG_LIST_BASE_JURNCUMP.vAnLista'  , pAn                 ::varchar, false);
  perform set_config('PKG_LIST_BASE_JURNCUMP.vLunaLista', pLuna               ::varchar, false);
  perform set_config('PKG_LIST_BASE_JURNCUMP.vAnLunaFin', vAnLunaFin          ::varchar, false);
  perform set_config('PKG_LIST_BASE_JURNCUMP.vTip'      , pTip                ::varchar, false);
  perform set_config('PKG_LIST_BASE_JURNCUMP.vAnLunaIni', vAnLunaIni          ::varchar, false);
  perform set_config('PKG_LIST_BASE_JURNCUMP.vSubunit'  , vSubunit            ::varchar, false);
  perform set_config('PKG_LIST_BASE_JURNCUMP.bExclNEA'  , pExclNoEconomicActiv::varchar, false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_jurncump_sjcintr</obj_name>
  <obj_hashval>c560cc0ab9e15ed1525148ac9d8aa43e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_jurncump_sjcintr()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 11.12.2025 - fixat 67550
  --Florin 03.08.2020
return  '
    SELECT
      CODINTR,
      MAX(TVAINC) TVAINC, MAX(TIPTVA) TIPTVA,
      SUM(CASE WHEN xMATCH_TVA &lt;&gt; 3 THEN 0 WHEN TVAINC = 1 THEN Round(BAZA*COEFNEDED,7) WHEN CAZ = ''NTVA'' THEN BAZA ELSE 0 END) BMAX,
      SUM(CASE WHEN xMATCH_TVA &lt;&gt; 3 THEN 0 WHEN TVAINC = 1 THEN Round(TVA* COEFNEDED,7) WHEN CAZ = ''NTVA'' THEN TVA  ELSE 0 END) TMAX,
      SUM(CASE WHEN xMATCH_TVA &lt;&gt; 2 THEN 0 WHEN TVAINC = 1 THEN Round(BAZA*COEFNEDED,7) WHEN CAZ = ''NTVA'' THEN BAZA ELSE 0 END) BMIN,
      SUM(CASE WHEN xMATCH_TVA &lt;&gt; 2 THEN 0 WHEN TVAINC = 1 THEN Round(TVA* COEFNEDED,7) WHEN CAZ = ''NTVA'' THEN TVA  ELSE 0 END) TMIN,
      SUM(CASE WHEN xMATCH_TVA &lt;&gt; 1 THEN 0 WHEN TVAINC = 1 THEN Round(BAZA*COEFNEDED,7) WHEN CAZ = ''NTVA'' THEN BAZA ELSE 0 END) BMED,
      SUM(CASE WHEN xMATCH_TVA &lt;&gt; 1 THEN 0 WHEN TVAINC = 1 THEN Round(TVA* COEFNEDED,7) WHEN CAZ = ''NTVA'' THEN TVA  ELSE 0 END) TMED,
      SUM(CASE WHEN xMATCH_TVA &lt;&gt; 4 THEN 0 WHEN TVAINC = 1 THEN Round(BAZA*COEFNEDED,7) WHEN CAZ = ''NTVA'' THEN BAZA ELSE 0 END) BREG,
      SUM(CASE WHEN xMATCH_TVA &lt;&gt; 4 THEN 0 WHEN TVAINC = 1 THEN Round(TVA* COEFNEDED,7) WHEN CAZ = ''NTVA'' THEN TVA  ELSE 0 END) TREG,
      SUM(CASE WHEN xMATCH_TVA &lt;&gt; 5 THEN 0 WHEN TVAINC = 1 THEN Round(BAZA*COEFNEDED,7) WHEN CAZ = ''NTVA'' THEN BAZA ELSE 0 END) BREG2,
      SUM(CASE WHEN xMATCH_TVA &lt;&gt; 5 THEN 0 WHEN TVAINC = 1 THEN Round(TVA* COEFNEDED,7) WHEN CAZ = ''NTVA'' THEN TVA  ELSE 0 END) TREG2,
      SUM(CASE WHEN xMATCH_TVA &lt;&gt; 6 THEN 0 WHEN TVAINC = 1 THEN Round(BAZA*COEFNEDED,7) WHEN CAZ = ''NTVA'' THEN BAZA ELSE 0 END) BREG3,
      SUM(CASE WHEN xMATCH_TVA &lt;&gt; 6 THEN 0 WHEN TVAINC = 1 THEN Round(TVA* COEFNEDED,7) WHEN CAZ = ''NTVA'' THEN TVA  ELSE 0 END) TREG3,
      SUM(CASE WHEN xMATCH_TVA &lt;&gt; 7 THEN 0 WHEN TVAINC = 1 THEN Round(BAZA*COEFNEDED,7) WHEN CAZ = ''NTVA'' THEN BAZA ELSE 0 END) BREG4,
      SUM(CASE WHEN xMATCH_TVA &lt;&gt; 7 THEN 0 WHEN TVAINC = 1 THEN Round(TVA* COEFNEDED,7) WHEN CAZ = ''NTVA'' THEN TVA  ELSE 0 END) TREG4,
      SUM(CASE WHEN xMATCH_TVA &lt;&gt; 8 THEN 0 WHEN TVAINC = 1 THEN Round(BAZA*COEFNEDED,7) WHEN CAZ = ''NTVA'' THEN BAZA ELSE 0 END) BREG5,
      SUM(CASE WHEN xMATCH_TVA &lt;&gt; 8 THEN 0 WHEN TVAINC = 1 THEN Round(TVA* COEFNEDED,7) WHEN CAZ = ''NTVA'' THEN TVA  ELSE 0 END) TREG5,
      SUM(CASE WHEN CAZ = ''N0'' OR (CAZ = ''NTVA'' AND xMATCH_TVA = 0) THEN BAZA ELSE 0 END) T0,
      SUM(CASE WHEN CAZ = ''AICB''  THEN BAZA ELSE 0 END) AICB_BAZA,  SUM(CASE WHEN CAZ = ''AICB''  THEN TVA  ELSE 0 END) AICB_TVA,
      SUM(CASE WHEN CAZ = ''AICBS'' THEN BAZA ELSE 0 END) AICB_SCUT,  SUM(CASE WHEN CAZ = ''AICBN'' THEN BAZA ELSE 0 END) AICB_NEIMP,
      SUM(CASE WHEN CAZ = ''AICBS'' AND TIPLINIE = ''S'' THEN BAZA ELSE 0 END) AICS_SCUT, SUM(CASE WHEN CAZ = ''AICBN'' AND TIPLINIE = ''S'' THEN BAZA ELSE 0 END) AICS_NEIMP,
      SUM(CASE WHEN CAZ = ''RS315'' THEN BAZA ELSE 0 END) RS315_BAZA, SUM(CASE WHEN CAZ = ''RS315'' THEN TVA  ELSE 0 END) RS315_TVA,
      SUM(CASE WHEN CAZ = ''BS150'' THEN BAZA ELSE 0 END) BS150_BAZA, SUM(CASE WHEN CAZ = ''BS150'' THEN TVA  ELSE 0 END) BS150_TVA,
      SUM(CASE WHEN CAZ = ''BS160'' THEN BAZA ELSE 0 END) BS160_BAZA, SUM(CASE WHEN CAZ = ''BS160'' THEN TVA  ELSE 0 END) BS160_TVA,
      SUM(CASE WHEN CAZ = ''BS160'' AND xMATCH_TVA = 3 THEN BAZA ELSE 0 END) BS160_BMAX,  SUM(CASE WHEN CAZ = ''BS160'' AND xMATCH_TVA = 3 THEN TVA  ELSE 0 END) BS160_TMAX,
      SUM(CASE WHEN CAZ = ''BS160'' AND xMATCH_TVA = 2 THEN BAZA ELSE 0 END) BS160_BMIN,  SUM(CASE WHEN CAZ = ''BS160'' AND xMATCH_TVA = 2 THEN TVA  ELSE 0 END) BS160_TMIN,
      SUM(CASE WHEN CAZ = ''BS160'' AND xMATCH_TVA = 1 THEN BAZA ELSE 0 END) BS160_BMED,  SUM(CASE WHEN CAZ = ''BS160'' AND xMATCH_TVA = 1 THEN TVA  ELSE 0 END) BS160_TMED,
      SUM(CASE WHEN CAZ = ''BS160'' AND xMATCH_TVA = 4 THEN BAZA ELSE 0 END) BS160_BREG,  SUM(CASE WHEN CAZ = ''BS160'' AND xMATCH_TVA = 4 THEN TVA  ELSE 0 END) BS160_TREG,
      SUM(CASE WHEN CAZ = ''BS160'' AND xMATCH_TVA = 5 THEN BAZA ELSE 0 END) BS160_BREG2, SUM(CASE WHEN CAZ = ''BS160'' AND xMATCH_TVA = 5 THEN TVA  ELSE 0 END) BS160_TREG2,
      SUM(CASE WHEN CAZ = ''BS160'' AND xMATCH_TVA = 6 THEN BAZA ELSE 0 END) BS160_BREG3, SUM(CASE WHEN CAZ = ''BS160'' AND xMATCH_TVA = 6 THEN TVA  ELSE 0 END) BS160_TREG3,
      SUM(CASE WHEN CAZ = ''BS160'' AND xMATCH_TVA = 7 THEN BAZA ELSE 0 END) BS160_BREG4, SUM(CASE WHEN CAZ = ''BS160'' AND xMATCH_TVA = 7 THEN TVA  ELSE 0 END) BS160_TREG4,
      SUM(CASE WHEN CAZ = ''BS160'' AND xMATCH_TVA = 8 THEN BAZA ELSE 0 END) BS160_BREG5, SUM(CASE WHEN CAZ = ''BS160'' AND xMATCH_TVA = 8 THEN TVA  ELSE 0 END) BS160_TREG5,
      MAX(PRORATA) PRORATA, SUM(TVA*COEFNPRORATA) TNPRORATA, SUM(TVA*COEFMPRORATA) TMPRORATA,
      SUM(CASE WHEN xMATCH_TVA = 3 THEN Round(BAZA*(COEFNEDED - COEFNPRORATA),7) ELSE 0 END) BNMAX,  SUM(CASE WHEN xMATCH_TVA = 3 THEN BAZA*(1-COEFNEDED) ELSE 0 END) BXMAX,
      SUM(CASE WHEN xMATCH_TVA = 3 THEN Round(TVA *(COEFNEDED - COEFNPRORATA),7) ELSE 0 END) TNMAX,  SUM(CASE WHEN xMATCH_TVA = 3 THEN TVA *(1-COEFNEDED) ELSE 0 END) TXMAX,
      SUM(CASE WHEN xMATCH_TVA = 2 THEN Round(BAZA*(COEFNEDED - COEFNPRORATA),7) ELSE 0 END) BNMIN,  SUM(CASE WHEN xMATCH_TVA = 2 THEN BAZA*(1-COEFNEDED) ELSE 0 END) BXMIN,
      SUM(CASE WHEN xMATCH_TVA = 2 THEN Round(TVA *(COEFNEDED - COEFNPRORATA),7) ELSE 0 END) TNMIN,  SUM(CASE WHEN xMATCH_TVA = 2 THEN TVA *(1-COEFNEDED) ELSE 0 END) TXMIN,
      SUM(CASE WHEN xMATCH_TVA = 1 THEN Round(BAZA*(COEFNEDED - COEFNPRORATA),7) ELSE 0 END) BNMED,  SUM(CASE WHEN xMATCH_TVA = 1 THEN BAZA*(1-COEFNEDED) ELSE 0 END) BXMED,
      SUM(CASE WHEN xMATCH_TVA = 1 THEN Round(TVA *(COEFNEDED - COEFNPRORATA),7) ELSE 0 END) TNMED,  SUM(CASE WHEN xMATCH_TVA = 1 THEN TVA *(1-COEFNEDED) ELSE 0 END) TXMED,
      SUM(CASE WHEN xMATCH_TVA = 4 THEN Round(BAZA*(COEFNEDED - COEFNPRORATA),7) ELSE 0 END) BNREG,  SUM(CASE WHEN xMATCH_TVA = 4 THEN BAZA*(1-COEFNEDED) ELSE 0 END) BXREG,
      SUM(CASE WHEN xMATCH_TVA = 4 THEN Round(TVA *(COEFNEDED - COEFNPRORATA),7) ELSE 0 END) TNREG,  SUM(CASE WHEN xMATCH_TVA = 4 THEN TVA *(1-COEFNEDED) ELSE 0 END) TXREG,
      SUM(CASE WHEN xMATCH_TVA = 5 THEN Round(BAZA*(COEFNEDED - COEFNPRORATA),7) ELSE 0 END) BNREG2, SUM(CASE WHEN xMATCH_TVA = 5 THEN BAZA*(1-COEFNEDED) ELSE 0 END) BXREG2,
      SUM(CASE WHEN xMATCH_TVA = 5 THEN Round(TVA *(COEFNEDED - COEFNPRORATA),7) ELSE 0 END) TNREG2, SUM(CASE WHEN xMATCH_TVA = 5 THEN TVA *(1-COEFNEDED) ELSE 0 END) TXREG2,
      SUM(CASE WHEN xMATCH_TVA = 6 THEN Round(BAZA*(COEFNEDED - COEFNPRORATA),7) ELSE 0 END) BNREG3, SUM(CASE WHEN xMATCH_TVA = 6 THEN BAZA*(1-COEFNEDED) ELSE 0 END) BXREG3,
      SUM(CASE WHEN xMATCH_TVA = 6 THEN Round(TVA *(COEFNEDED - COEFNPRORATA),7) ELSE 0 END) TNREG3, SUM(CASE WHEN xMATCH_TVA = 6 THEN TVA *(1-COEFNEDED) ELSE 0 END) TXREG3,
      SUM(CASE WHEN xMATCH_TVA = 7 THEN Round(BAZA*(COEFNEDED - COEFNPRORATA),7) ELSE 0 END) BNREG4, SUM(CASE WHEN xMATCH_TVA = 7 THEN BAZA*(1-COEFNEDED) ELSE 0 END) BXREG4,
      SUM(CASE WHEN xMATCH_TVA = 7 THEN Round(TVA *(COEFNEDED - COEFNPRORATA),7) ELSE 0 END) TNREG4, SUM(CASE WHEN xMATCH_TVA = 7 THEN TVA *(1-COEFNEDED) ELSE 0 END) TXREG4,
      SUM(CASE WHEN xMATCH_TVA = 8 THEN Round(BAZA*(COEFNEDED - COEFNPRORATA),7) ELSE 0 END) BNREG5, SUM(CASE WHEN xMATCH_TVA = 8 THEN BAZA*(1-COEFNEDED) ELSE 0 END) BXREG5,
      SUM(CASE WHEN xMATCH_TVA = 8 THEN Round(TVA *(COEFNEDED - COEFNPRORATA),7) ELSE 0 END) TNREG5, SUM(CASE WHEN xMATCH_TVA = 8 THEN TVA *(1-COEFNEDED) ELSE 0 END) TXREG5,
      MAX(CASE WHEN TVA = 0 THEN 0 WHEN BAZA*(1-COEFNEDED) = 0 THEN 1 ELSE 1 END) AUX_X,
      SUM(CASE WHEN TVA = 0 THEN 0 ELSE BAZA*(1-COEFNEDED) END) BAZAX, SUM(TVA*(1-COEFNEDED)) TVAX, SUM(Round(TVA * (COEFNEDED - COEFNPRORATA) ,7)) TNEDED,
      CASE WHEN Max(SPLITTVA) = 0 THEN 1 WHEN Sum(BAZA)     = 0 THEN 0 ELSE Sum(CASE WHEN TVA = 0 THEN 0 ELSE BAZA     END)/Sum(BAZA    ) END COEF_B,
      CASE WHEN Max(SPLITTVA) = 0 THEN 1 WHEN Sum(BAZA+TVA) = 0 THEN 0 ELSE Sum(CASE WHEN TVA = 0 THEN 0 ELSE BAZA+TVA END)/Sum(BAZA+TVA) END COEF_D,
      MAX(TVANEDED) TVANEDED, MAX(DOC_REG) DOC_REG
    FROM X
    GROUP BY CODINTR';
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_jurnvanz_getstinsdoc</obj_name>
  <obj_hashval>a977d7622654081673e8f98d4f2fb27d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_jurnvanz_getstinsdoc(pcodobligpif numeric, pal numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  LREC     RECORD;
  vTrezor  NUMERIC;
  vCEC     NUMERIC;
  vCompens NUMERIC;
  vLitig   NUMERIC;
begin
  --Stef 14.01.2022

  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;

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

  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;

  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
  ) LOOP
    vLitig := vLitig + lREC.VALOARE;
    vLitig := vLitig - PKG_LIST_BASE_JURNVANZ_getStinsDoc(lREC.CodObligPif, pAL);
  END LOOP;

  RETURN vTrezor + vCEC + vCompens - vLitig;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_lansetichete_codatrib</obj_name>
  <obj_hashval>9ba95e598a7c17b8b39d39486091b211</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_lansetichete_codatrib(pcodobiect numeric, pidx numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sAux varchar;
BEGIN
  --Adina 13.10.2020
  SELECT a1.CODEXTERN
  INTO sAux
  FROM   natrobj oa
        INNER JOIN natrib1 a1 ON  a1.codvalatr = oa.codvalatr
  WHERE oa.codobiect = pCodObiect AND  oa.indexlocal = pIDX;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_lansetichete_denatrib</obj_name>
  <obj_hashval>dc7baf99cf822a38a6c17a972eb8ed68</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_lansetichete_denatrib(pcodobiect numeric, pidx numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sAux varchar;
BEGIN
  --Adina 13.10.2020
  SELECT a.Denumire
  INTO sAux
  FROM   natrobj oa
        INNER JOIN natrib1 a1 ON  a1.codvalatr = oa.codvalatr
        INNER JOIN natrib a   ON  a.codatribut = a1.codatribut
  WHERE oa.codobiect = pCodObiect AND  oa.indexlocal = pIDX;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_lansetichete_setjoinuri</obj_name>
  <obj_hashval>3a289e84f561ca33f4193397fdf63ae0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_lansetichete_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 13.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_LANSETICHETE.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_lansetichete_setparams</obj_name>
  <obj_hashval>02f9ab8668f52fddc0ecc0d2206447b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_lansetichete_setparams(pcoddoc 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;
  vNrAtrib    numeric;
BEGIN
  --Adina 13.10.2020
  perform set_config('PKG_LIST_BASE_LANSETICHETE.vDataS',sDataS,false);
  perform set_config('PKG_LIST_BASE_LANSETICHETE.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_LANSETICHETE.vCodDoc',(pCodDoc)::varchar,false);

  SELECT COALESCE(Max(OA.IndexLocal), 0)
  INTO vNrAtrib
  FROM   LANSARE L
        INNER JOIN PROIECT PR    ON  L.CODPROIECT     = PR.CODPROIECT
        INNER JOIN PROIECTNOD PN ON  PR.CODPROIECT    = PN.CODPROIECT AND  PN.NODORIGINAL = 0
        INNER JOIN LANSARE1 L1   ON  L1.CODPROIECTNOD = PN.CODPROIECTNOD
        INNER JOIN comanda1 c1   ON  L1.CODCMD1   = c1.CODCOMANDA1
        INNER JOIN nartobj o     ON  o.codobiect  = c1.codobiect
        INNER JOIN natrobj oa    ON  oa.codobiect = o.codobiect
  WHERE L.CodLansare = current_setting('PKG_LIST_BASE_LANSETICHETE.vCodDoc', true)::numeric;

  perform set_config('PKG_LIST_BASE_LANSETICHETE.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_lansetichete_valatrib</obj_name>
  <obj_hashval>fb43b7077469f416e3ba73743049540e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_lansetichete_valatrib(pcodobiect numeric, pidx numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sAux varchar;
BEGIN
  --Adina 13.10.2020
  SELECT a1.Valoare
  INTO sAux
  FROM   natrobj oa
        INNER JOIN natrib1 a1 ON  a1.codvalatr = oa.codvalatr
  WHERE oa.codobiect = pCodObiect AND  oa.indexlocal = pIDX;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_lansz_setparams</obj_name>
  <obj_hashval>314a54eba1e7f4f9ec00889b9a63c2b2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_lansz_setparams(psetimanaini numeric, psetimanafin numeric, pan numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  Aux numeric;
BEGIN
  --Adina 14 septembrie 2020
  perform set_config('PKG_LIST_BASE_LANSZ.vSetimanaIni',(pSetimanaIni)::varchar,false);
  perform set_config('PKG_LIST_BASE_LANSZ.vSetimanaFin',(pSetimanaFin)::varchar,false);
  perform set_config('PKG_LIST_BASE_LANSZ.vAn'         ,(pAn)::varchar         ,false);

  IF  current_setting('PKG_LIST_BASE_LANSZ.vSetimanaIni', true)::numeric &gt; current_setting('PKG_LIST_BASE_LANSZ.vSetimanaFin', true)::NUMERIC THEN
    Aux := current_setting('PKG_LIST_BASE_LANSZ.vSetimanaIni', true)::numeric;
    perform set_config('PKG_LIST_BASE_LANSZ.vSetimanaIni',current_setting('PKG_LIST_BASE_LANSZ.vSetimanaFin', true),false);
    perform set_config('PKG_LIST_BASE_LANSZ.vSetimanaFin',(Aux)::varchar,false);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_leads_processlist</obj_name>
  <obj_hashval>62c1d3f678661c27807ff43aee5548db</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_leads_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;
  sZi     varchar;
  sLuna   varchar;
  sAn     varchar;
  sData   varchar;
begin
  --Adina 23.12.2020 tichet 41862
  --Bogdan 15.09.2020
  gSuplCols := 'NPART P, NCATPRET CAT, NPARTCODFISC F, NAGENDA A, NLOCALIT L, NTARI T, NJUDET J, DOMENIIACT DA, NPARTTR RESP, CAMPANII CAMP, NPART1CRM CRM';

  call pkg_list_struct_startsuplcols();

  call pkg_list_struct_addsupltabs (gSuplCols , 'NPARTDET'    , 'PD'  , 'PD.CODPART = P.CODPART'      ,NULL);
  call pkg_list_struct_addsupltabs (gSuplCols , 'OPORTUNITATI', 'OPOR', 'OPOR.CODPARTENER = P.CODPART',NULL);

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

  SELECT (extract (day FROM CURRENT_TIMESTAMP)) ::varchar INTO sZi;
  sLuna := getLunaLucru() ::varchar;
  sAn   := getAnLucru()   ::varchar;

  BEGIN
    sData := to_char(to_date (coalesce (lpad (sZi, 2, '0') ,'')|| '.'|| coalesce (lpad (sLuna, 2, '0') ,'')|| '.'|| coalesce (sAn,'')),'dd.mm.yyyy');
  EXCEPTION WHEN others THEN
    sData := to_char(last_day (to_date ('01.'|| coalesce (lpad (sLuna, 2, '0') ,'')|| '.'|| coalesce (sAn,'') , 'dd.mm.yyyy')),'dd.mm.yyyy');
  END;

  sInsert := 'INSERT INTO '|| TMPNAME
          || '(
              DEN_PART, CODEXTERN, CODINTERN, DEN_LOCALIT, CODFISCAL,
              BLOCAT, AUTORIZATIE, STRATEGIC, SIMBAUTO, CifraAfaceri,
              DenDomeniuAct, Responsabil, DENCAMPANIE, CONCURENTI'
          || coalesce (gUserFields ,'')
          || ') ';
  sSelect := '
         SELECT P.DEN_PART,
          P.CODEXTERN,
          P.CODINTERN,
          L.DEN_LOCALIT,
          F.CODFISCAL,
          (case when P.BLOCAT = 1 then ''DA'' else ''NU'' end ) Blocat,
          P.AUTORIZATIE,
          (case when P.STRATEGIC = 1 then ''DA'' else ''NU'' end) STRATEGIC,
          J.SIMBAUTO,
          P.CifraAfaceri,
          DA.DenDomeniuAct,
          RESP.Delegat,
          CAMP.DENCAMPANIE,
          vCP.Concurenti' || coalesce (gUserAlias ,'')|| '
         FROM NPART              P
              INNER JOIN NPART1CRM   CRM  ON CRM.CODPART    = P.CODPART
              LEFT JOIN NCATPRET     CAT  ON CAT.CODCATPRET = P.CODCATEGPRET
              LEFT JOIN NPARTCODFISC F    ON F.CODPART      = P.CODPART AND F.PRINCIPAL = 1
              LEFT JOIN NAGENDA      A    ON A.CODPART      = P.CODPART AND coalesce (a.Inactiv,0) = 0 AND (BITAND (A.SEDIUSOCIAL, 4) &lt;&gt; 0)
              LEFT JOIN NLOCALIT     L    ON L.CODLOCALIT   = A.CODLOCALIT
              LEFT JOIN NTARI        T    ON T.CODTARA      = L.CODTARA
              LEFT JOIN NJUDET       J    ON J.CODJUDET     = L.CODJUDET
              LEFT JOIN DOMENIIACT   DA   ON DA.CodDomeniuAct = P.CodDomeniuAct
              LEFT JOIN NPARTTR      RESP ON RESP.CodPartTr   = P.CodResponsabil
              LEFT JOIN CAMPANII     CAMP ON CAMP.CodCampanie = P.SursaLead
              LEFT JOIN (SELECT pc.CodPart, fnc_array_to_vc3200 (ARRAY_AGG (C.DENCONCURENT) ) Concurenti
                         FROM NPARTCONCURENTI       PC
                              INNER JOIN CONCURENTI C ON C.CODCONCURENT = PC.CODCONCURENT
                         GROUP BY pc.CodPart
                        ) vCP ON vCP.CodPart = P.CodPart ' || coalesce (gSuplJoins ,'')|| '
         WHERE CRM.Lead = 1
               and CRM.DATASTART = (SELECT MAX (P1.DATASTART)
                                    FROM NPART1CRM P1
                                    WHERE P1.CODPART = P.CODPART
                                          AND P1.DATASTART &lt;= TO_DATE ('''|| coalesce (sData ,'')|| ''',''dd.mm.yyyy'')) ';
  PERFORM LIST_EXECUTE_IMMEDIATE (coalesce (sInsert,'') || coalesce (sSelect,'') , aListID, aListVer);
end;
$function$
</obj_text>
</row>

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

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

  sInsert varchar;
  sSelect varchar;
  sFiltru varchar;
begin
  --Bogdan 09.09.2020
  --Florin 15.05.2021 - fixat 39799
  gSuplCols := 'comanda c, comanda1 c1, nartobj obj, nart art, num1 num1, num us, nparcaut auto, pachete pak, comanda cc, comanda1 c1c';

  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_LISTDISPLIVR.gSuplCols',gSuplCols,false);

  sFiltru := '
        AND c.tipdoc = 18 and c.displivrare = 1 ';
  sFiltru := coalesce (sFiltru,'')
          || coalesce ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'', 'c.subunitatea',NULL,NULL)) ,'');
  sFiltru := coalesce (sFiltru,'')
          || ' AND c.datadoc between pkg_list_selectper_dataini() and pkg_list_selectper_datafin() ';
  sInsert := 'INSERT INTO '|| tmpname
      || '( NAV_CodDoc,
            NAV_TipDoc,
            DOC,
            NRDOC,
            DATADOC,
            ART,
            UM,
            CANTCOM,
            CANTACC,
            CANTREST,
            PRET,
            VALCOM,
            VALACC,
            VALREST,
            TERMEN,
            OBSART,
            OBSCOM,
            CodIntern,
            CodExtern,
            DenClasaA,
            SimbClasaA,
            Masa,
            Volum,
            UMPrinc,
            UM1,
            CANTUM1,
            D1,
            D2,
            D3,
            AUTO,
            DATACREARE '
              || coalesce (gUserFields ,'')
              || ') ';
  sSelect := '
          SELECT c.codcomanda,
            c.tipdoc,
            c.prefixdoc,
            c.nrdoc,
            c.datadoc,
            obj.denumire,
            num1.den_um1,
            c1.cantcomandat / num1.paritate,
            c1.cantacceptat / num1.paritate,
            c1.restacceptat / num1.paritate,
            c1.pu           * num1.paritate,
            c1.pu           * c1.cantcomandat,
            c1.pu           * c1.cantacceptat,
            c1.pu           * c1.restacceptat,
            c1.termen,
            c1.OBS,
            c.OBS,
            obj.codintern,
            obj.codextern,
            cla.den_clasea,
            cla.simbol,
            coalesce (obj.masa,0)  * c1.cantacceptat,
            coalesce (obj.volum,0) * c1.cantacceptat,
            UMP.DEN_UM,
            US.DEN_UM,
            C1.ACCEPTUM1,
            C1.D1,
            C1.D2,
            C1.D3,
            auto.nrinreg,
            c.datacreare '
              || coalesce (gUserAlias ,'')|| '
          FROM comanda          c
            INNER JOIN comanda1 c1        ON c.codcomanda       = c1.codcomanda
            INNER JOIN nartobj  obj       ON obj.codobiect      = c1.codobiect
            INNER JOIN nart     art       ON obj.codarticol     = art.codarticol
            INNER JOIN num      UMP       ON ART.UM             = UMP.CODUM
            INNER JOIN num1               ON num1.codum1        = c1.umsec
            LEFT JOIN nparcaut      auto  ON auto.CODNPARCAUT   = c.MIJLTRANSP
            LEFT JOIN PACHETEDLLINK PLINK ON PLINK.CODCOMANDA1  = C1.CODCOMANDA1
            LEFT JOIN PACHETEOBJ    POBJ  ON POBJ.CODPACHETEOBJ = PLINK.CODPACHETEOBJ
            LEFT JOIN PACHETE       PAK   ON PAK.CODPACHETE     = POBJ.CODPACHETE
            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 cmdlivrlink   l     on l.codcomanda1      = c1.codcomanda1
            left join comanda1      c1c   on l.codliniecomanda  = c1c.codcomanda1
            left join comanda       cc    on c1c.codcomanda     = cc.codcomanda '
              || 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_listdisplivr_setjoinuri</obj_name>
  <obj_hashval>48cd6870ee4955ebafd171fd252f1256</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_listdisplivr_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 09.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec (current_setting ('PKG_LIST_BASE_LISTDISPLIVR.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_livrari_processlist</obj_name>
  <obj_hashval>9c7bee1970c8dee15a0d3892f60bd623</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrari_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert      varchar;
  sSelectComun varchar;
  sSelectIes   varchar;
  sSelectT     varchar;
  sSelectInt   varchar;
  sColSerii    varchar := ', ns.tg, NULL serie';
  sGrupSerii   varchar := ', ns.tg';
  sJoinSerii   varchar;
  sCursRef     varchar := ', 1 ';
  sCondDataI   varchar;
  sCondDataT   varchar;
  vFiltru      varchar;
  sPMP         varchar := ', NULL PMP, NULL PMPVALUTA, NULL PMPDOC, NULL PMPVALUTADOC';
  sInsertDC    varchar;
  sWithDc      varchar;
  sSelectDC    varchar;
  sJoinDC      varchar;
  aSitV        numeric;
  aBancaV      numeric;
  aMonedaV     numeric;
  vMax         NUMERIC := (SELECT PKG_LIST_BASE_UTILS_NIVELE_NCLASEA.WME_RESULT FROM PKG_LIST_BASE_UTILS_NIVELE_NCLASEA(NULL,NULL));
  vInfoOferte  Boolean;
  vInfoPart    Boolean;
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplJoins   VARCHAR := '';
  gSuplCols    varchar := 'num1 u1, nartobj nao, nartobj1 nao1 ,nart na, num um1, num um2, ngest g, ngest go, nlocatii nl, nsubunit ss, nmonede mon, nclasea ca, nclaseas cs, ' || 'ncont nc, ncont ncv, nclaseg cg, npart prod, npart furn, ngest gfurn, nartamb aa, pretm pm, npers ag_doc, nparttr del, centrecost cc,' || 'npart np, nagenda slivr, nlocalit locl, njudet judl, nzone zonal, ntari taral, ntari torig, livr l';
  wmeRes       boolean;
BEGIN
  --Florin 09.04.2024 - fixat 61604
  --Florin 21.12.2022 - fixat 56626
  --Florin 28.04.2022 - sinc. Oracle (27.04.2022)
  --Florin 12.01.2022 - sinc. Oracle
  --Laura 11.10.2021 - sinc Oracle (05.10.2021)
  --Florin 31.08.2021 - sinc. Oracle (39880)
  --Florin 20.08.2021 - sinc. Oracle (39880)
  --Adina 02.04.2021 - alstart, alstop
  --Adina 09.03.2021 - prc_al_check
  --Adina 19.02.2021 - GetInfoSitValuta
  --Stef 21.12.2020 PKG_LIST_BASE_UTILS_GetCoefDiscMonetar
  --Florin 14.08.2020
  --Adina 27.11.2020 tichete 41298,41299
  vInfoPart   := current_setting('PKG_LIST_SELECTGEST.vExtra2', TRUE)::NUMERIC = 1;
  vInfoOferte := current_setting('PKG_LIST_SELECTGEST.vExtra3', TRUE)::NUMERIC = 1;

  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 = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR' , 'OATR.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONT'     , 'NCLIN', 'NCLIN.CODCONT = LG.CONTLIN'                      , 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI1'   , 'IES1' , 'IES1.CODIES1 = LG.CODDOC1 AND LG.ISIES = 1'      , 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARI1'  , 'INTR1', 'INTR1.CODINTR1 = LG.CODDOC1 AND LG.ISINTR = 1'   , 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TRANSF1'   , 'TRAN1', 'TRAN1.CODTRANSF1 = LG.CODDOC1 AND LG.ISTRANF = 1', 1);
  IF vInfoPart THEN
    call pkg_list_struct_addsupltabs(gSuplCols, 'NARTCLI', 'ACLI', 'ACLI.CODOBIECT  = LG.CODOBIECT AND ACLI.CODPART = LG.PARTENER', 1);
  END IF;

  IF vInfoOferte THEN
    call pkg_list_struct_addsupltabs(gSuplCols, 'OFERTA1', 'O1', 'O1.CODOFERTA1 = pkg_oferta.GetCodOferta1(LG.CODOBIECT, LG.DATADOC, LG.PARTENER, LG.locatielivr, LG.SUBUNITATEA, 50, LG.CANT)', 1);
    call pkg_list_struct_addsupltabs(gSuplCols, 'OFERTA' , 'O' , 'O1.CODOFERTA = O.CODOFERTA',NULL);
  END IF;

  call pkg_list_struct_addsupltabs(gSuplCols, 'NIRSTOC', 'NSMAX', 'NSMAX.CODNIRSTOC = LG.MAXCODNIRSTOC', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPART'  , 'COMIS', 'LG.PARTCUSTODIE = COMIS.CODPART'    , 1);

  IF Coalesce(fnc_getvalconstantalucru('CUMULEZBCAR'), '') = '2' THEN
    call pkg_list_struct_addsupltabs(gSuplCols, 'BCAR'   , 'BCAR'   , 'BCAR.CODDOC1 = LG.CODDOC1 AND BCAR.TIPDOC = LG.TIPDOC', 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_LIVRARI.gSuplCols', gSuplCols, FALSE);

  CALL PRC_AL_CHECK('NART1');
  CALL PRC_AL_CHECK('NTVA1');

  SELECT sInsertUMA, sSelectUMA, sJoinUMA FROM PKG_LIST_BASE_UTILS_UMA_UTILS('lg.cant', 'lg.codobiect', sInsertDC, sSelectDC, sJoinDC, NULL)
    INTO sInsertDC, sSelectDC, sJoinDC;

  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(LG.DATADOC, ''dd.mm.yyyy'')))';
  END IF;

  IF current_setting('PKG_LIST_SELECTGEST.vDupaData', TRUE)::NUMERIC = 1 THEN
    sCondDataI := '
          AND   l.datalivr BETWEEN to_date(''' || COALESCE(To_Char(fnc_current_setting_date('PKG_LIST_SELECTGEST.vDataIni'),'dd.mm.yyyy'),'')  || ''',''dd.mm.yyyy'')
          AND to_date(''' || COALESCE(To_Char(fnc_current_setting_date('PKG_LIST_SELECTGEST.vDataFin'),'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')' ;
    sCondDataT := sCondDataI;
  ELSIF current_setting('PKG_LIST_SELECTGEST.vLunaAnIni', TRUE) = current_setting('PKG_LIST_SELECTGEST.vLunaAnFin', TRUE) THEN
    sCondDataI := '
          AND   (i.luna + i.an * 12) = ' || COALESCE(current_setting('PKG_LIST_SELECTGEST.vLunaAnIni', TRUE),'') || ' ';
    sCondDataT := '
          AND   (t.luna + t.an * 12) = ' || COALESCE(current_setting('PKG_LIST_SELECTGEST.vLunaAnIni', TRUE),'') || ' ';
  ELSE
    sCondDataI := '
          AND   (i.luna + i.an * 12) BETWEEN ' || COALESCE(current_setting('PKG_LIST_SELECTGEST.vLunaAnIni', TRUE),'') || ' AND ' || COALESCE(current_setting('PKG_LIST_SELECTGEST.vLunaAnFin', TRUE),'') || ' ';
    sCondDataT := '
          AND   (t.luna + t.an * 12) BETWEEN ' || COALESCE(current_setting('PKG_LIST_SELECTGEST.vLunaAnIni', TRUE),'') || ' AND ' || COALESCE(current_setting('PKG_LIST_SELECTGEST.vLunaAnFin', TRUE),'') || ' ';
  END IF;

  IF current_setting('PKG_LIST_SELECTGEST.bAduSerii', TRUE)::NUMERIC = 1 THEN
    sColSerii := ',Coalesce(nser.tg, ns.tg) tg, s.serie ';
    sJoinSerii := '
            LEFT JOIN nirser nser ON nser.codnirser = l1.codnirser
            LEFT JOIN nserii s on s.codserie = nser.codserie';
    sGrupSerii := ',Coalesce(nser.tg, ns.tg), s.serie';
  END IF;

  IF current_setting('PKG_LIST_SELECTGEST.vAllGest', TRUE)::NUMERIC = 0 THEN
    vFiltru := '
        AND COALESCE(l1.codgestorig, lv.gest, n.gest)::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' ) ';
  END IF;

  sPMP := ', lg.pmp, lg.pmpvaluta, lg.pmpdoc, lg.pmpvalutadoc ';

  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 := coalesce(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 := coalesce(sWithDC,'') || '
          FROM TMP_PROFIT_NCLASEA
          GROUP BY codclasea),';
    sJoinDC := coalesce(sJoinDC,'') || '
        LEFT JOIN clase clsc ON clsc.codclasea = na.clasa';
  END IF;
  sInsert := 'INSERT INTO '|| tmpName ||'(
    NAV_CodDoc,NAV_TipDoc,NAV_FiltruLivr,
    DenArt,DenUM,DenGest,DenGestOrig,DenLGest,DenSub,SimbolCont,ContVenituri,ContCheltuieli,Document,PrefixDoc,NrDoc,DataDoc,NumeDoc,
    DocLivr, NRLIVR,DATALIVR,DENCARNETLIVR,SIMBCARNETLIVR,SERCARNETLIVR,
    TIPTVA,TIPTRANZ,
    CantIes,CantLivr,PMInreg,ValLivr,ValTVALivr,
    ProcAdaos,AdaosUnit,ValAdaos,
    PretRef, ProcAdaosRef,
    PretAch,ValAch, PUAchVal,
    PUMAX,
    PU,PU_Lei,ProcDisc,
    PIes,PIesLei,ValIes,ValIesLei,
    ProcTVA,ValTVA,ValTVALei,
    ValDisc,ValDiscLei,TVADisc,TVADiscLei,
    MonDoc,CURS,Destinatie,Serii,DataExp,
    DENIOART,CODEXTERNA,CODINTERNA,CODVAMAL,FURNIZOR,PRODUCATOR,OBSART,UM1,UM2,CANTUM1,CANTUM2,GARIES,GARART,MASA,VOLUM,
    SLIVR_TIP,SLIVR_DEN,SLIVR_ADR,SLIVR_LOC,SLIVR_JUD,SLIVR_TARA,SLIVR_ZONA,
    AGENT_DOC,GR_PRET,UPLIFT,Dim1,Dim2,Dim3,
    DENCLASEAS,DenClasaA,SimbClasaA,DenClasaP,SimbClasaP,
    DataAchiz,SerieLot,NrCertif,STipDoc,ObsDoc,Custodie,CENTRUCOST,
    ANDOC,LUNADOC,LUNA,
    IOARTINTERM, CONTINTERM, CONTVINTERM, CONTCINTERM,
    PIesDVal,
    PIesVal,MonTransf,CursTransf, CURS_REF, PMP, PMPVALUTA, PMPDOC, PMPVALUTADOC'||COALESCE(sInsertDC, '')|| COALESCE(gUserFields, '')||')';
  sSelectComun := '
      WITH ' || coalesce(sWithDC,'');
  sSelectIes := '
       LG AS (
      SELECT
        1 isies, 0 istranf, 0 isintr,
        l.codlivr, i.codies coddoc, i.tipdoc, i.prefixdoc, Coalesce(i.curs,1) curs, (CASE WHEN i.cursdoc IS NULL THEN 1 WHEN I.CURSDOC = 0 THEN 1 ELSE i.cursdoc END) cursdoc, i.nrdoc, i.datadoc, i.partener, i.an, i.luna,
        i.codgestprod, i.codsubunit, i.moneda, Coalesce(i1.codagentemulare,i.agent,0) agent, i.codlocatie locatielivr, i.subunitatea, Coalesce(i.monedatransf,0) monedatransf, i.tiptva, i.tiptranzactie,
        CASE WHEN Coalesce(l1.contintermed, 0) = 0 THEN Coalesce(i.contintermed,0) ELSE l1.contintermed END contintermed,
        Coalesce(dvi1.coddvi1,i1.codies1) codlinie,  i1.codies1 coddoc1, i1.indexlocal, i1.codobiect, Coalesce(lv.gest, n.gest, 0) gest, Coalesce(l1.codgestorig, lv.gest, n.gest, 0) gestorig,
        Coalesce(ns.codlocatie,0) codlocatie, l1.umsec, i1.obs obsart, i.delegat, i.obs obsdoc, i.custodie,
        CASE WHEN i.tipdoc IN (16,21) THEN (i1.pu - i1.tva / (CASE WHEN i1.cant = 0 THEN 1 ELSE i1.cant END) ) ELSE i1.pu END pu,
        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, i1.contserv, Coalesce(lv.codioart, ns.codioart), 1, i1.pu * i1.cant, i1.TVA)
          END pies,
        CASE
          WHEN i1.tva = 0 THEN 0
          WHEN i.tipdoc IN (16,21) AND i1.pu * i1.cant = i1.tva THEN 0
          WHEN i.tipdoc IN (16,21) THEN i1.tva / (i1.pu * (CASE WHEN i1.cant = 0 THEN 1 ELSE i1.cant END)-i1.tva)
          WHEN i1.pu * i1.cant = 0 THEN 0
          ELSE i1.tva / (i1.pu * (CASE WHEN i1.cant = 0 THEN 1 ELSE i1.cant END))
        END 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, i1.contserv, Coalesce(lv.codioart, ns.codioart), 2, i1.pu * i1.cant, i1.TVA)
        END * Coalesce(i1.tva,0) tvalin, Coalesce(i1.tva,0) tvau,
        l.carnetlivr, l.nrlivr, l.datalivr, i1.garantie, i1.codcentru, i1.contserv contlin,
        SUM(CASE WHEN IESVAL.CODLIVR1 &gt; 0 THEN IESVAL.VAL ELSE (CASE WHEN lv.codlivrval IS NULL THEN ns.pret ELSE lv.pretinreg END) * l1.cant END) * (CASE WHEN i.tipdoc = 15 THEN -1 ELSE 1 END) valinreg,
        SUM((CASE WHEN Coalesce(ns.tva,0) = 0 THEN 0 ELSE ns.pret*l1.cant*ns.tva/(1+ns.tva)END)) tvaneex,
        SUM(CASE WHEN IESVAL.CODLIVR1 &gt; 0 THEN IESVAL.VAL ELSE Coalesce((CASE WHEN lv.codlivrval IS NULL THEN ns.pret - ns.adaos ELSE lv.pretachiz END)*l1.cant,0) END) * (CASE WHEN i.tipdoc = 15 THEN -1 ELSE 1 END) valachiz,
        SUM(Coalesce(ns.puval,0)*l1.cant) * (CASE WHEN i.tipdoc = 15 THEN -1 ELSE 1 END) valachizval,
        Coalesce(lv.codioart,ns.codioart) codioart, Coalesce(i1.pumaximal,MAX(ns.pumaximal)) pumaximal,
        i1.cant * (CASE WHEN i.tipdoc = 15 THEN -1 ELSE 1 END) canti, sum(l1.cant) * (CASE WHEN i.tipdoc = 15 THEN -1 ELSE 1 END) cant, sum(l1.cantum1) * (CASE WHEN i.tipdoc = 15 THEN -1 ELSE 1 END) cantum1, sum(l1.cantum2) * (CASE WHEN i.tipdoc = 15 THEN -1 ELSE 1 END) cantum2,
        ns.d1, ns.d2, ns.d3, ns.tipserie, Coalesce(ns.furn,0) furn, Coalesce(ns.codgestprod,0) gestfurn,
        STRING_AGG(int1.nrcertif::VARCHAR, '''') nrcertif,
        ns.DataAchiz, ns.SerieLot, max(l1.pmpvaluta) pmpvaluta, max(l1.pmpdoc) pmpdoc, max(l1.pmpvalutadoc) pmpvalutadoc, max(l1.pmp) pmp, max(l1.codnirstoc) maxcodnirstoc,
        SUM(CASE WHEN IESVAL.CODLIVR1 &gt; 0 THEN IESVAL.VAL ELSE 0 END) viesdval, SUM(CASE WHEN IESVAL.CODLIVR1 &gt; 0 THEN l1.cant ELSE 0 END) ciesdval, i.partcustodie '||sColSerii||'
      FROM iesiri1 i1
        INNER JOIN iesiri i ON i.codies   = i1.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 (
          SELECT SUM(L1.CANT * (CASE WHEN LV.CODLIVR1 IS NULL THEN NS.PRET - Coalesce(NS.ADAOS,0) ELSE Coalesce(LV.PRETACHIZ,0) END)) VAL, IVL.CODLIVR1
          FROM IESVALLINK IVL
            INNER JOIN IESIRI1 I1 ON IVL.CODIES1   = I1.CODIES1
            INNER JOIN LIVR L     ON L.CODIES      = I1.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
          GROUP BY IVL.CODLIVR1
        ) IESVAL                ON IESVAL.CODLIVR1 = L1.CODLIVR1
        LEFT JOIN livrval lv    ON lv.codlivr1     = l1.codlivr1
        LEFT JOIN nirstoc ns    ON ns.codnirstoc   = l1.codnirstoc
        LEFT JOIN nirstoc1 ns1  ON ns1.codnirstoc  = l1.codnirstoc
        LEFT JOIN nirstoc nsin  ON nsin.codnirstoc = ns1.codnirstocorig
        LEFT JOIN dvi1          ON dvi1.coddvi1    = nsin.coddvi1
        LEFT JOIN intrari1 int1 ON int1.codintr1   = Coalesce(dvi1.codintr1, nsin.codintr1)
        LEFT JOIN nir n         ON n.codnir        = ns.codnir'||
        COALESCE(sJoinSerii, '') ||'
      WHERE (l.codies IS NOT NULL) AND (l.operat = 1) AND (l.anulat = 0) '||
        COALESCE(sCondDataI, '') ||
        COALESCE(vFiltru, '') ||
        COALESCE(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', NULL, NULL, NULL), '') ||
        COALESCE((SELECT PKG_LIST_BASE_UTILS_COND_USERID.wme_result FROM PKG_LIST_BASE_UTILS_COND_USERID (NULL, 'I', NULL, NULL)), '') ||'
      GROUP BY
        i.codies, i.tipdoc, i.prefixdoc, i.curs, i.cursdoc, i.nrdoc, i.datadoc, i.partener, i.an, i.luna, i.obs, i.custodie, i.tiptva, i.tiptranzactie, i.valdoc, i.valdiscount,
        i.tvadoc, i.tvadiscount, i.codgestprod, i.codsubunit, i.moneda, i.agent, i.delegat, i.codlocatie, i.subunitatea, i.monedatransf, i.contintermed, i.partcustodie, dvi1.coddvi1,
        i1.codies1, i1.indexlocal, i1.tiplinie, i1.codobiect, i1.tva, i1.pretorig, i1.pu, i1.cant, i1.tva, i1.addim, i1.coefdiscmaj, i1.valdiscpret, i1.garantie, i1.obs, i1.pumaximal, i1.addim, i1.codcentru, i1.contserv, i1.codagentemulare,
        l.codlivr, l.carnetlivr, l.nrlivr, l.datalivr, l1.umsec, SIGN(l1.cant), i.contintermed, l1.contintermed, Coalesce(lv.codioart, ns.codioart),
        COALESCE(l1.codgestorig, lv.gest, n.gest, 0), COALESCE(lv.gest, n.gest, 0),
        Coalesce(ns.codlocatie,0), Coalesce(ns.furn,0), Coalesce(ns.codgestprod,0), ns.tipserie, ns.d1, ns.d2, ns.d3, ns.DataAchiz, ns.SerieLot, lv.codioart, ns.codioart '||COALESCE(sGrupSerii, '')||'
    )
  SELECT
    lg.coddoc, lg.tipdoc,
    (SELECT PKG_LIST_BASE_SERII_FILTRU_LIVR.wme_result from PKG_LIST_BASE_SERII_FILTRU_LIVR(NULL, lg.tipdoc,lg.coddoc,lg.codlinie,lg.tipserie,lg.umsec,lg.codioart,lg.gest,lg.codlocatie,lg.gestfurn,lg.furn,Coalesce(lg.d1,0),Coalesce(lg.d2,0),Coalesce(lg.d3,0),Coalesce(lg.dataachiz::varchar,''0''))),
     nao.denumire, u1.den_um1, g.den_gest, go.den_gest, nl.denumire, ss.den_subunit, nc.simbol, ncv.simbol, ncc.simbol,
    coalesce(lg.prefixdoc, '''')||''.''||coalesce(lg.nrdoc::varchar, '''')||'' / ''||to_char(lg.datadoc,''dd.mm.yyyy'')||'' - ''||coalesce((CASE WHEN lg.tipdoc = 15 THEN ''-'' WHEN LG.TIPDOC = 16 THEN ''-'' WHEN lg.tipdoc = 23 THEN sd.den_subunit WHEN lg.tipdoc = 24 THEN gd.den_gest ELSE np.den_part END), ''''),
    lg.prefixdoc, lg.nrdoc, lg.datadoc, PKG_LIST_BASE_UTILS_decode_tipdoc(lg.tipdoc),
    ''LIVR ''||lg.nrlivr||'' / ''||to_char(lg.datalivr,''dd.mm.yyyy''), lg.nrlivr, lg.datalivr, dc.denumire, dc.simbol, dc.serie,
    (CASE WHEN lg.tiptva = 1 THEN ''Taxare Normala'' WHEN lg.tiptva = 2 THEN''Taxare Inversa'' WHEN lg.tiptva = 3 THEN ''Taxare Triunghiulara'' WHEN lg.tiptva = 4 THEN ''Prestari in afara Romaniei''
          WHEN lg.tiptva = 5 THEN ''intracom.,scutit, cu drept de ded.(lit.a/d)''  WHEN lg.tiptva = 6 THEN ''intracom.,scutit, cu drept de ded.(lit.b/c)'' WHEN lg.tiptva = 7 THEN ''regim special de scutire art 311 CF''
          WHEN lg.tiptva = 8 THEN ''regim special de scutire art 312 CF'' END),
    CASE
      WHEN LG.TIPDOC = 24 THEN ''Tranzactie interna''
      ELSE (CASE WHEN lg.tiptranzactie = 1 THEN ''Tranzactie interna''WHEN lg.tiptranzactie = 2 THEN ''Livrare intracomunitara'' WHEN lg.tiptranzactie = 3 THEN ''Export'' END)
    END,
    lg.cant / u1.paritate, lg.cant / u1.paritate, lg.valinreg * u1.paritate / (CASE WHEN lg.cant = 0 THEN 1 ELSE lg.cant END), lg.valinreg, lg.tvaneex,
    round((case when lg.valachiz = 0 then 100 else (lg.pies*lg.cant*lg.curs-lg.valachiz)*100/lg.valachiz end),2), (lg.pies*lg.curs-lg.valachiz/(case when lg.cant = 0 then 1 else lg.cant end))*u1.paritate, lg.pies*lg.cant*lg.curs-lg.valachiz, nao1.pretreferinta, round((case when nao1.pretreferinta is NULL then NULL when nao1.pretreferinta = 0 then 100 else (lg.pies*lg.curs-nao1.pretreferinta)*100/nao1.pretreferinta end),2) ProcAdaosRef,
    lg.valachiz * u1.paritate / (CASE WHEN lg.cant = 0 THEN 1 ELSE lg.cant END), lg.valachiz, lg.valachizval * u1.paritate / (CASE WHEN lg.cant = 0 THEN 1 ELSE lg.cant END),
    CASE
      WHEN Coalesce(nao1.tippretmax,0) IN (1,2,3) THEN lg.pumaximal
      WHEN Coalesce(nao1.tippretmax,0) IN (4,5,6) THEN nao1.pretmaximal
      ELSE NULL
    END pumax,
    lg.pu, lg.pu * lg.curs PU_Lei, round((CASE WHEN lg.pu = 0 THEN 0 ELSE (lg.pies - lg.pu) * 100 / (CASE WHEN lg.pu = 0 THEN 1 ELSE lg.pu END)END),2) ProcDisc,
    lg.pies * u1.paritate PIes, lg.pies * u1.paritate * lg.curs PIesLei, lg.pies * lg.cant ValIes, lg.pies * lg.cant * lg.curs ValIesLei,
    lg.coef_tva * 100 ProcTVA,
    CASE
      WHEN lg.tipdoc = 15 AND lg.canti = 0 THEN 0
      WHEN lg.tipdoc = 15 THEN lg.tvalin*lg.cant/lg.canti
      ELSE lg.cant * lg.pies * lg.coef_tva
    END ValTVA,
    CASE
      WHEN lg.tipdoc = 15 AND lg.canti = 0 THEN 0
      WHEN lg.tipdoc = 15 THEN lg.tvalin*lg.cant/lg.canti
      ELSE lg.cant * lg.pies * lg.coef_tva
    END * lg.curs ValTVALei,
    lg.cant * (lg.pies - lg.pu) ValDisc, lg.curs * lg.cant * (lg.pies - lg.pu) ValDiscLei,
    CASE
      WHEN lg.tipdoc = 15 AND lg.canti = 0 THEN 0
      WHEN lg.tipdoc = 15 THEN (lg.tvalin-lg.tvau)*lg.cant/lg.canti
      ELSE lg.coef_tva * lg.cant * (lg.pies - lg.pu)
    END TVADisc,
    CASE
      WHEN lg.tipdoc = 15 AND lg.canti = 0 THEN 0
      WHEN lg.tipdoc = 15 THEN (lg.tvalin-lg.tvau)*lg.cant/lg.canti
      ELSE lg.coef_tva * lg.cant * (lg.pies - lg.pu)
    END * lg.curs TVADiscLei,
    mon.simbol, lg.curs, (CASE WHEN lg.tipdoc = 15 THEN ''-''WHEN lg.tipdoc = 16 THEN ''-''WHEN lg.tipdoc = 23 THEN sd.den_subunit WHEN lg.tipdoc =24 THEN gd.den_gest ELSE np.den_part END), lg.serie, lg.tg,
    io.den_ioart, nao.codextern, nao.codintern, nao.codvamal, (CASE WHEN lg.furn = 0 THEN gfurn.den_gest ELSE furn.den_part END), prod.den_part, lg.obsart, um1.den_um, um2.den_um, lg.cantum1, lg.cantum2, lg.garantie, nao.lunigarantie, nao.masa, nao.volum,
    tsl.denumire, slivr.obs, fnc_getadresa(slivr.sector, slivr.strada, slivr.nr1, slivr.nr2, slivr.bloc, slivr.scara, slivr.etaj, slivr.apart, slivr.codpostal), locl.den_localit, judl.den_judet, taral.den_tara, zonal.den_zona,
    CASE WHEN ag_doc.codpers = 0 THEN ag_doc.nume ELSE ag_doc.nume||'' ''||ag_doc.prenume END, nao1.grupa, nao1.uplift,lg.d1,lg.d2,lg.d3,
    cs.den_claseas, ca.den_clasea, ca.simbol, (CASE WHEN lg.tipdoc = 24 THEN cg.den_claseg ELSE cp.den_clasep END), (CASE WHEN lg.tipdoc = 24 THEN cg.simbol ELSE cp.simbol END),
    lg.DataAchiz,lg.SerieLot,lg.NrCertif, pkg_list_base_utils_decode_tipdoc_scurt(lg.tipdoc), lg.obsdoc,(CASE WHEN lg.custodie = 1 THEN ''Da'' ELSE ''Nu'' END), cc.denumire,
    lg.an andoc, lg.luna lunadoc, to_char(lg.an,''fm0000'')||''.''||to_char(lg.luna,''fm00'')||''.''||pkg_list_base_utils_decode_luna(lg.Luna) luna,
    ioi.den_ioart, nci.simbol, ncvi.simbol, ncci.simbol,
    CASE WHEN Coalesce(lg.ciesdval,0) = 0 THEN NULL ELSE lg.viesdval/lg.ciesdval*u1.paritate END PIesDVal,
    (CASE WHEN lg.monedatransf = 0 THEN 0 ELSE lg.pies * u1.paritate/lg.cursdoc END), (CASE WHEN lg.monedatransf = 0 THEN NULL ELSE mt.simbol END), lg.cursdoc'
        || COALESCE(sCursRef, '') || COALESCE(sPMP, '') || COALESCE(sSelectDC, '') || gUserAlias ||
  ' FROM lg
    INNER JOIN num1 u1       ON u1.codum1       = lg.umsec
    INNER JOIN nartobj nao   ON nao.codobiect   = lg.codobiect
    INNER JOIN nart na       ON na.codarticol   = nao.codarticol
    LEFT  JOIN livr l        ON l.codlivr       = lg.codlivr
    LEFT  JOIN NUM UM1       ON um1.codum       = na.um1
    LEFT  JOIN NUM UM2       ON um2.codum       = na.um2
    LEFT  JOIN ngest g       ON g.codgest       = lg.gest
    LEFT  JOIN ngest go      ON go.codgest      = lg.gestorig
    LEFT  JOIN nlocatii nl   ON nl.codlocatie   = lg.codlocatie
    LEFT  JOIN nsubunit ss   ON ss.codsubunit   = lg.subunitatea
    LEFT  JOIN doccarnete dc ON dc.codcarnet    = lg.carnetlivr
    LEFT  JOIN nmonede mon   ON mon.codmoneda   = lg.moneda
    LEFT  JOIN nmonede mt    ON mt.codmoneda    = lg.monedatransf
    LEFT  JOIN nclasea ca    ON ca.codclasea    = na.clasa
    LEFT  JOIN nclaseas cs   ON cs.codclaseas   = na.clasastatist
    LEFT  JOIN ioart io      ON io.codioart     = lg.codioart
    LEFT  JOIN ioart1 io1    ON io1.codioart    = lg.codioart  AND (lg.an*12+lg.luna) BETWEEN  io1.ALStart and  io1.ALStop
    LEFT  JOIN ncont nc      ON nc.codcont      = io1.cont
    LEFT  JOIN centrecost cc ON cc.codcentru    = lg.codcentru
    LEFT  JOIN ncont ncv     ON ncv.codcont     = Coalesce(io1.venituri,0)
    LEFT  JOIN ncont ncc     ON ncc.codcont     = Coalesce(io1.cheltuieli,0)
    LEFT  JOIN ioart ioi     ON ioi.codioart    = lg.contintermed
    LEFT  JOIN ioart1 ioi1   ON ioi1.codioart   = lg.contintermed AND (lg.an*12+lg.luna) BETWEEN ioi1.ALStart and ioi1.ALStop
    LEFT  JOIN ncont nci     ON nci.codcont     = ioi1.cont
    LEFT  JOIN ncont ncvi    ON ncvi.codcont    = Coalesce(ioi1.venituri,0)
    LEFT  JOIN ncont ncci    ON ncci.codcont    = Coalesce(ioi1.cheltuieli,0)
    LEFT  JOIN npart np      ON np.codpart      = lg.partener
    LEFT  JOIN nclasep cp    ON cp.codclasep    = np.codclasa
    LEFT  JOIN ngest gd      ON gd.codgest      = lg.codgestprod
    LEFT  JOIN nclaseg cg    ON cg.codclaseg    = gd.codclasa
    LEFT  JOIN nsubunit sd   ON sd.codsubunit   = lg.codsubunit
    LEFT  JOIN NAGENDA SLIVR ON slivr.codagenda = lg.locatielivr
    LEFT  JOIN NLOCALIT LOCl ON locl.codlocalit = slivr.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 NTIPSEDII tsl ON tsl.codtipsediu = slivr.codtipsediu
    LEFT  JOIN npart prod    ON prod.codpart    = nao.codproducator
    LEFT  JOIN npart furn    ON furn.codpart    = lg.furn
    LEFT  JOIN ngest gfurn   ON gfurn.codgest   = lg.gestfurn
    LEFT  JOIN NPERS AG_DOC  ON ag_doc.codpers  = lg.agent
    LEFT  JOIN nparttr del   ON lg.delegat      = del.codparttr
    LEFT  JOIN NTARI TOrig   ON TOrig.CodTara   = nao.taraorigine
    LEFT  JOIN nartobj1 nao1 ON nao1.codobiect  = lg.codobiect AND (lg.an*12+lg.luna) BETWEEN nao1.ALStart and nao1.ALStop
    LEFT  JOIN nartamb aa    ON aa.codobiect    = lg.codobiect AND aa.umsec = lg.umsec
    LEFT  JOIN pretm pm      ON pm.codobiect    = lg.codobiect AND pm.subunitatea = lg.subunitatea AND pm.implicit = 1'||
    COALESCE(sJoinDC, '') ||
    gSuplJoins||'
  WHERE lg.cant &lt;&gt; 0';
  sSelectInt := '
        LG AS (
          SELECT
          0 isies, 0 istranf, 1 isintr,
            l.codlivr, i.codintr coddoc, i.tipdoc, i.prefixdoc, Coalesce(i.curs,1) curs, i.nrdoc, i.datadoc, i.partener, i.an, i.luna,
            i.codgestprod, i.codsubunit, i.moneda, 0 agent, i.codlocatie locatielivr, i.subunitatea, i.tiptva, i.tiptranzactie,
            i1.codintr1 coddoc1, i1.indexlocal, i1.codobiect, Coalesce(lv.gest, n.gest,0) gest, Coalesce(lv.gest, n.gest,0) gestorig,
            Coalesce(ns.codlocatie,0) codlocatie, l1.umsec, i1.obs obsart, 0 delegat, i.obs obsdoc,
            CASE WHEN i.tipdoc = 3 THEN (i1.pu - i1.tva / (Case  When i1.cant=0 then 1 else i1.cant end)) ELSE i1.pu END pu,
            i1.pretorig * Coalesce(i1.coefdiscmaj,1) * (CASE WHEN i.tipdoc = 3 THEN (1 - i1.tva / (Case  When (i1.cant * i1.pu)=0 then 1 else (i1.cant * i1.pu) end)  ) ELSE 1 END)  pies,
            CASE
              WHEN i1.tva = 0 THEN 0
              WHEN i.tipdoc = 3 AND i1.pu * i1.cant = i1.tva THEN 0
              WHEN i.tipdoc = 3 THEN i1.tva / (i1.pu * (Case  When i1.cant=0 then 1 else i1.cant end)-i1.tva)
              WHEN i1.pu * i1.cant = 0 THEN 0
              ELSE i1.tva / (i1.pu * (Case  When i1.cant=0 then 1 else i1.cant end))
            END coef_tva,
            l.carnetlivr, l.nrlivr, l.datalivr, i1.codcentru, i1.contserv contlin,
            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,
            SUM(Coalesce(ns.puval,0)*l1.cant) valachizval,
            Coalesce(lv.codioart,ns.codioart) codioart, Coalesce(i1.pumaximal,MAX(ns.pumaximal)) pumaximal,
            i1.cant canti, sum(l1.cant) cant, sum(l1.cantum1) cantum1, sum(l1.cantum2) cantum2,
            ns.d1, ns.d2, ns.d3, ns.tipserie, Coalesce(ns.furn,0) furn, Coalesce(ns.codgestprod,0) gestfurn,
            string_agg(int1.nrcertif::varchar, '''') nrcertif,
            ns.DataAchiz, ns.SerieLot, max(l1.pmpvaluta) pmpvaluta, max(l1.pmpdoc) pmpdoc, max(l1.pmpvalutadoc) pmpvalutadoc, max(l1.pmp) pmp, max(l1.codnirstoc) maxcodnirstoc,
            0 PARTCUSTODIE' || coalesce(sColSerii,'') || '
          FROM intrari1 i1
            INNER JOIN intrari i    ON i.codintr       = i1.codintr
            INNER JOIN livr l       ON l.codintr       = i1.codintr
            LEFT JOIN dvi1          ON dvi1.codintr1   = i1.codintr1
            LEFT 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 nirstoc1 ns1  ON ns1.codnirstoc  = l1.codnirstoc
            LEFT JOIN nirstoc nsin  ON nsin.codnirstoc = ns1.codnirstocorig
            LEFT JOIN dvi1 d1       ON d1.coddvi1      = nsin.coddvi1
            LEFT JOIN intrari1 int1 ON int1.codintr1   = Coalesce(d1.codintr1, nsin.codintr1)
            LEFT JOIN nir n         ON n.codnir        = ns.codnir' || coalesce(sJoinSerii,'') || '
          WHERE (l.codintr IS NOT NULL) AND (l.operat = 1) AND (l.anulat = 0)
                AND (l1.codintr1 = i1.codintr1 OR l1.coddvi1 = dvi1.coddvi1) ' || coalesce(sCondDataI,'') || coalesce(vFiltru,'')
          || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'')
          || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_USERID.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_USERID(NULL,'I',NULL,NULL)),'') || '
          GROUP BY
            i.codintr, i.tipdoc, i.prefixdoc, i.curs, i.nrdoc, i.datadoc, i.partener, i.an, i.luna, i.obs,
            i.codgestprod, i.codsubunit, i.moneda, i.codlocatie, i.subunitatea, i.tiptva, i.tiptranzactie,
            i1.codintr1, i1.indexlocal, i1.codobiect, i1.tva, i1.pretorig, i1.pu, i1.cant, i1.coefdiscmaj, i1.obs, i1.pumaximal, i1.codcentru, i1.contserv,
            l.codlivr, l.carnetlivr, l.nrlivr, l.datalivr, l1.umsec, SIGN(l1.cant), Coalesce(lv.codioart,ns.codioart), Coalesce(lv.gest, n.gest,0),
            Coalesce(ns.codlocatie,0), Coalesce(ns.furn,0), Coalesce(ns.codgestprod,0), ns.tipserie, ns.d1, ns.d2, ns.d3, ns.DataAchiz, ns.SerieLot ' || coalesce(sGrupSerii,'') || '
        )
      SELECT
        lg.coddoc, lg.tipdoc,
        (SELECT PKG_LIST_BASE_SERII_FILTRU_LIVR.WME_RESULT FROM PKG_LIST_BASE_SERII_FILTRU_LIVR(NULL, lg.tipdoc,lg.coddoc,lg.coddoc1,lg.tipserie,lg.umsec,lg.codioart,lg.gest,lg.codlocatie,lg.gestfurn,lg.furn,Coalesce(lg.d1,0),Coalesce(lg.d2,0),Coalesce(lg.d3,0),Coalesce(lg.dataachiz::varchar,''0''))),
        nao.denumire, u1.den_um1, g.den_gest, go.den_gest, nl.denumire, ss.den_subunit, nc.simbol, ncv.simbol, ncc.simbol,
        coalesce(lg.prefixdoc, '''')||''.''||coalesce(lg.nrdoc::varchar, '''')||'' / ''||to_char(lg.datadoc, ''dd.mm.yyyy'')||'' - ''||coalesce((Case  When lg.tipdoc=6 then sd.den_subunit When lg.tipdoc=7 then gd.den_gest else np.den_part end), ''''),
        lg.prefixdoc, lg.nrdoc, lg.datadoc, (SELECT PKG_LIST_BASE_UTILS_decode_tipdoc.wme_result FROM PKG_LIST_BASE_UTILS_decode_tipdoc(NULL, lg.tipdoc)),
        ''LIVR ''||lg.nrlivr||'' / ''||to_char(lg.datalivr, ''dd.mm.yyyy''), lg.nrlivr, lg.datalivr, dc.denumire, dc.simbol, dc.serie,
        (CASE WHEN lg.tiptva = 1 THEN ''Taxare normala'' WHEN lg.tiptva = 2 THEN ''Taxare inversa'' WHEN lg.tiptva =3 THEN ''Tranzactie triunghiulara'' WHEN lg.tiptva = 4 THEN ''Taxare normala ProRata''
        WHEN lg.tiptva = 5 THEN ''Regim special (art. 1521, 1522)'' WHEN lg.tiptva = 6 THEN ''Regim special de scutire art 311 CF'' WHEN lg.tiptva = 7 THEN ''Regim special de scutire art 312 CF''
        WHEN lg.tiptva = 8 THEN ''Achizitii UE de bunuri cu instalare/montaj'' end),
        (CASE when lg.tipdoc = 5 THEN ''Import'' ELSE (Case  When lg.tiptranzactie=1 then ''Tranzactie interna'' When lg.tiptranzactie=2 then ''Achizitie intracomunitara'' When lg.tiptranzactie=3 THEN ''Import servicii'' END) END),
        lg.cant / u1.paritate, lg.cant / u1.paritate, lg.valinreg * u1.paritate / (Case  When lg.cant=0 then 1 else lg.cant end), lg.valinreg, lg.tvaneex,
        round((case when lg.valachiz = 0 then 100 else (lg.pies*lg.cant*lg.curs-lg.valachiz)*100/lg.valachiz end),2), (lg.pies*lg.curs-lg.valachiz/(case when lg.cant = 0 then 1 else lg.cant end))*u1.paritate, lg.pies*lg.cant*lg.curs-lg.valachiz,
        nao1.pretreferinta, round((Case  When nao1.pretreferinta is NULL then NULL When nao1.pretreferinta=0 then 100 else (lg.pies*lg.curs-nao1.pretreferinta)*100/nao1.pretreferinta end),2) ProcAdaosRef,
        lg.valachiz * u1.paritate / (Case  When lg.cant=0 then 1 else lg.cant end), lg.valachiz, lg.valachizval * u1.paritate / (Case  When lg.cant=0 then 1 else lg.cant end),
        CASE
          WHEN Coalesce(nao1.tippretmax,0) IN (1,2,3) THEN lg.pumaximal
          WHEN Coalesce(nao1.tippretmax,0) IN (4,5,6) THEN nao1.pretmaximal
          ELSE NULL
        END pumax,
        lg.pu, lg.pu * lg.curs, round((Case  When lg.pu=0 then 0 else (lg.pies - lg.pu) * 100 / (Case  When lg.pu=0 then 1 else lg.pu end)end),2),
        lg.pies * u1.paritate, lg.pies * u1.paritate * lg.curs, lg.pies * lg.cant, lg.pies * lg.cant * lg.curs,
        lg.coef_tva * 100, lg.cant * lg.pies * lg.coef_tva, lg.cant * lg.pies * lg.coef_tva * lg.curs,
        lg.cant * (lg.pies - lg.pu), lg.curs * lg.cant * (lg.pies - lg.pu), lg.coef_tva * lg.cant * (lg.pies - lg.pu), lg.coef_tva * lg.curs * lg.cant * (lg.pies - lg.pu),
        mon.simbol, lg.curs, (Case When lg.tipdoc=6 then sd.den_subunit When lg.tipdoc=7 then gd.den_gest else np.den_part end), lg.serie, lg.tg,
        io.den_ioart, nao.codextern, nao.codintern, nao.codvamal, (Case  When lg.furn=0 then gfurn.den_gest else furn.den_part end), prod.den_part, lg.obsart, um1.den_um, um2.den_um, lg.cantum1, lg.cantum2, 0, nao.lunigarantie, nao.masa, nao.volum,
        tsl.denumire, slivr.obs, fnc_getadresa(slivr.sector, slivr.strada, slivr.nr1, slivr.nr2, slivr.bloc, slivr.scara, slivr.etaj, slivr.apart, slivr.codpostal), locl.den_localit, judl.den_judet, taral.den_tara, zonal.den_zona,
        CASE WHEN ag_doc.codpers = 0 THEN ag_doc.nume ELSE ag_doc.nume||'' ''||ag_doc.prenume END, nao1.grupa, nao1.uplift,lg.d1,lg.d2,lg.d3,
        cs.den_claseas, ca.den_clasea, ca.simbol, (Case  When lg.tipdoc=7 then cg.den_claseg else cp.den_clasep end), (Case  When lg.tipdoc=7 then cg.simbol else cp.simbol end),
        lg.DataAchiz,lg.SerieLot,lg.NrCertif, pkg_list_base_utils_decode_tipdoc_scurt(lg.tipdoc), lg.obsdoc, ''Nu'' custodie, cc.denumire,
        lg.an andoc, lg.luna lunadoc, to_char(lg.an,''fm0000'')||''.''||to_char(lg.luna,''fm00'')||''.''||pkg_list_base_utils_decode_luna(lg.Luna) luna,
        NULL, NULL, NULL, NULL,
        NULL PIesDVal,
        0, NULL, NULL ' || coalesce(sCursRef,'') || coalesce(sPMP,'') || coalesce(sSelectDC,'') || gUserAlias || '
      FROM lg
        INNER JOIN num1 u1       ON u1.codum1       = lg.umsec
        INNER JOIN nartobj nao   ON nao.codobiect   = lg.codobiect
        INNER JOIN nart na       ON na.codarticol   = nao.codarticol
        LEFT  JOIN livr l        ON l.codlivr       = lg.codlivr
        LEFT  JOIN NUM UM1       ON um1.codum       = na.um1
        LEFT  JOIN NUM UM2       ON um2.codum       = na.um2
        LEFT  JOIN ngest g       ON g.codgest       = lg.gest
        LEFT  JOIN ngest go      ON go.codgest      = lg.gestorig
        LEFT  JOIN nlocatii nl   ON nl.codlocatie   = lg.codlocatie
        LEFT  JOIN nsubunit ss   ON ss.codsubunit   = lg.subunitatea
        LEFT  JOIN doccarnete dc ON dc.codcarnet    = lg.carnetlivr
        LEFT  JOIN nmonede mon   ON mon.codmoneda   = lg.moneda
        LEFT  JOIN nclasea ca    ON ca.codclasea    = na.clasa
        LEFT  JOIN nclaseas cs   ON cs.codclaseas   = na.clasastatist
        LEFT  JOIN ioart io      ON io.codioart     = lg.codioart
        LEFT  JOIN ioart1 io1    ON io1.codioart    = lg.codioart AND (lg.an*12+lg.luna) BETWEEN  io1.ALStart and  io1.ALStop
        LEFT  JOIN ncont nc      ON nc.codcont      = io1.cont
        LEFT  JOIN centrecost cc ON cc.codcentru    = lg.codcentru
        LEFT  JOIN ncont ncv     ON ncv.codcont     = Coalesce(io1.venituri,0)
        LEFT  JOIN ncont ncc     ON ncc.codcont     = Coalesce(io1.cheltuieli,0)
        LEFT  JOIN npart np      ON np.codpart      = lg.partener
        LEFT  JOIN nclasep cp    ON cp.codclasep    = np.codclasa
        LEFT  JOIN nparttr del   ON lg.delegat      = del.codparttr
        LEFT  JOIN ngest gd      ON gd.codgest      = lg.codgestprod
        LEFT  JOIN nclaseg cg    ON cg.codclaseg    = gd.codclasa
        LEFT  JOIN nsubunit sd   ON sd.codsubunit   = lg.codsubunit
        LEFT  JOIN NAGENDA SLIVR ON slivr.codagenda = lg.locatielivr
        LEFT  JOIN NLOCALIT LOCl ON locl.codlocalit = slivr.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 NTIPSEDII tsl ON tsl.codtipsediu = slivr.codtipsediu
        LEFT  JOIN npart prod    ON prod.codpart    = nao.codproducator
        LEFT  JOIN npart furn    ON furn.codpart    = lg.furn
        LEFT  JOIN ngest gfurn   ON gfurn.codgest   = lg.gestfurn
        LEFT  JOIN NPERS AG_DOC  ON ag_doc.codpers  = lg.agent
        LEFT  JOIN NTARI TOrig   ON TOrig.CodTara   = nao.taraorigine
        LEFT  JOIN nartobj1 nao1 ON nao1.codobiect  = lg.codobiect AND (lg.an*12+lg.luna) BETWEEN nao1.ALStart and nao1.ALStop
        LEFT  JOIN nartamb aa    ON aa.codobiect    = lg.codobiect AND aa.umsec = lg.umsec
        LEFT  JOIN pretm pm      ON pm.codobiect    = lg.codobiect AND pm.subunitatea = lg.subunitatea AND pm.implicit = 1' || coalesce(sJoinDC,'') || gSuplJoins || '
      WHERE lg.cant &lt;&gt; 0';
      sSelectT := '
        LG AS (
          SELECT
            0 isies, 1 istranf, 0 isintr,
            l.codlivr, t.codtransf coddoc, t.tipdoc, t.prefixdoc, t.nrdoc, t.datadoc, 0 partener, t.an, t.luna, t.subunitatea,
            nd.gest gestd, Coalesce(nsd.codlocatie,0) codlocatied, 0 moneda, 0 agent, 0 locatielivr,
            t1.codtransf1 coddoc1, t1.indexlocal, t1.codobiect, Coalesce(lv.gest, n.gest,0) gest, Coalesce(lv.gest, n.gest,0) gestorig,
            Coalesce(ns.codlocatie,0) codlocatie, t1.umsec, t1.pu, substr(t1.obs,1,300) obsart, t.obs obsdoc,
            CASE WHEN t1.tva = 0 THEN 0 WHEN t1.pu * t1.cant = 0 THEN 0 ELSE t1.tva / (Case  When  (t1.pu * t1.cant)=0 then 1 else (t1.pu * t1.cant) end)END coef_tva,
            l.carnetlivr, l.nrlivr, l.datalivr, t.delegat, t1.codcentru, t1.codcont contlin,
            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/(CASE WHEN (1+ns.tva)= 0 then 1 ELSE (1+ns.tva) END )end)) tvaneex,
            SUM(Coalesce((Case When lv.codlivrval IS NULL then ns.pret - ns.adaos else lv.pretachiz end)*l1.cant,0)) valachiz,
            SUM(Coalesce(ns.puval,0)*l1.cant) valachizval,
            Coalesce(lv.codioart,ns.codioart) codioart, Coalesce(t1.pumaximal,MAX(ns.pumaximal)) pumaximal,
            t1.cant cantt, sum(l1.cant) cant, sum(l1.cantum1) cantum1, sum(l1.cantum2) cantum2,
            ns.d1, ns.d2, ns.d3, ns.tipserie, Coalesce(ns.furn,0) furn, Coalesce(ns.codgestprod,0) gestfurn,
            string_agg(int1.nrcertif::varchar, '''') nrcertif,
            ns.DataAchiz, ns.SerieLot, max(l1.pmpvaluta) pmpvaluta, max(l1.pmpdoc) pmpdoc, max(l1.pmpvalutadoc) pmpvalutadoc,max(l1.pmp) pmp, max(l1.codnirstoc) maxcodnirstoc,
            0 PARTCUSTODIE' || coalesce(sColSerii,'') || '
          FROM transf1 t1
            INNER JOIN transf t     ON t.codtransf = t1.codtransf
            INNER JOIN livr l       ON l.codtransf = t1.codtransf
            INNER JOIN livr1 l1     ON l1.codies1  = t1.codtransf1 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 nirstoc nsd   ON nsd.codlivr1    = l1.codlivr1
            LEFT JOIN nirstoc1 ns1  ON ns1.codnirstoc  = l1.codnirstoc
            LEFT JOIN nirstoc nsin  ON nsin.codnirstoc = ns1.codnirstocorig
            LEFT JOIN dvi1          ON dvi1.coddvi1    = nsin.coddvi1
            LEFT JOIN intrari1 int1 ON int1.codintr1   = Coalesce(dvi1.codintr1, nsin.codintr1)
            LEFT JOIN nir nd        ON nd.codnir       = nsd.codnir' || coalesce(sJoinSerii,'') || '
          WHERE (l.codtransf IS NOT NULL)  AND (l.operat = 1) AND (l.anulat = 0) ' || coalesce(sCondDataT,'') || coalesce(vFiltru,'')
          || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL),'')
          || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_USERID.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_USERID(NULL,'T',NULL,NULL)),'') || '
          GROUP BY
            t.codtransf, t.tipdoc, t.prefixdoc, t.nrdoc, t.datadoc, t.an, t.luna, t.subunitatea, t.delegat, t.obs,
            t1.codtransf1, t1.indexlocal, t1.codobiect, t1.tva, t1.pu, t1.cant, t1.umsec, substr(t1.obs,1,300), t1.pumaximal, t1.codcentru, t1.codcont,
            l.codlivr, l.carnetlivr, l.nrlivr, l.datalivr, l1.umsec, SIGN(l1.cant), Coalesce(lv.codioart, ns.codioart), Coalesce(lv.gest, n.gest,0),
            Coalesce(ns.codlocatie,0), Coalesce(ns.furn,0), Coalesce(ns.codgestprod,0), nd.gest, nsd.codlocatie, ns.tipserie, ns.d1, ns.d2, ns.d3, ns.DataAchiz, ns.SerieLot ' || coalesce(sGrupSerii,'') || '
        )
      SELECT
        lg.coddoc, lg.tipdoc,
        (SELECT PKG_LIST_BASE_SERII_FILTRU_LIVR.wme_result from PKG_LIST_BASE_SERII_FILTRU_LIVR(null, lg.tipdoc,lg.coddoc,lg.coddoc1,lg.tipserie,lg.umsec,lg.codioart,lg.gest,lg.codlocatie,lg.gestfurn,lg.furn,Coalesce(lg.d1,0),Coalesce(lg.d2,0),Coalesce(lg.d3,0),Coalesce(lg.dataachiz::varchar,''0''), lg.gestd, lg.codlocatied)),
        nao.denumire, u1.den_um1, g.den_gest, go.den_gest, nl.denumire, ss.den_subunit, nc.simbol, ncv.simbol, ncc.simbol,
        coalesce(lg.prefixdoc, '''')||''.''||coalesce(lg.nrdoc::varchar, '''')||'' / ''||to_char(lg.datadoc, ''dd.mm.yyyy'')||'' - ''||coalesce((Case  When lg.codlocatied=0 then gd.den_gest else gd.den_gest ||'' (''||nld.denumire||'')'' end), ''''),
        lg.prefixdoc, lg.nrdoc, lg.datadoc, (SELECT PKG_LIST_BASE_UTILS_decode_tipdoc.wme_result from PKG_LIST_BASE_UTILS_decode_tipdoc(NULL, lg.tipdoc)),
        ''LIVR ''||lg.nrlivr||'' / ''||to_char(lg.datalivr, ''dd.mm.yyyy''), lg.nrlivr, lg.datalivr, dc.denumire, dc.simbol, dc.serie,
        NULL,
        ''Tranzactie interna'' ,
        lg.cant / u1.paritate, lg.cant / u1.paritate, lg.valinreg * u1.paritate / (Case  When lg.cant=0 then 1 else lg.cant end), lg.valinreg, lg.tvaneex,
        round((case when lg.valachiz = 0 then 100 else (lg.pu*lg.cant-lg.valachiz)*100/(case when lg.valachiz = 0 then 1 else lg.valachiz end) end) ,2), (lg.pu-lg.valachiz/(case when lg.cant = 0 then 1 else lg.cant end))*u1.paritate, lg.pu*lg.cant-lg.valachiz,
        nao1.pretreferinta, round((Case  When nao1.pretreferinta is NULL then NULL When nao1.pretreferinta=0 then 100 else (lg.pu-nao1.pretreferinta)*100/nao1.pretreferinta end),2) ProcAdaosRef,
        lg.valachiz * u1.paritate / (Case  When lg.cant=0 then 1 else lg.cant end), lg.valachiz, lg.valachizval * u1.paritate / (Case  When lg.cant=0 then 1 else lg.cant end),
        CASE
          WHEN Coalesce(nao1.tippretmax,0) IN (1,2,3) THEN lg.pumaximal
          WHEN Coalesce(nao1.tippretmax,0) IN (4,5,6) THEN nao1.pretmaximal
          ELSE NULL
        END pumax,
        lg.pu, lg.pu, 0,
        lg.pu * u1.paritate, lg.pu * u1.paritate, lg.pu * lg.cant, lg.pu * lg.cant,
        lg.coef_tva * 100, lg.cant * lg.pu * lg.coef_tva, lg.cant * lg.pu * lg.coef_tva,
        0, 0, 0, 0,
        mon.simbol, 1, (Case  When lg.codlocatied=0 then gd.den_gest else gd.den_gest ||'' (''||nld.denumire||'')'' end), lg.serie, lg.tg,
        io.den_ioart, nao.codextern, nao.codintern, nao.codvamal, (Case  When lg.furn=0 then gfurn.den_gest else furn.den_part end), prod.den_part, lg.obsart, um1.den_um, um2.den_um, lg.cantum1, lg.cantum2, 0, nao.lunigarantie, nao.masa, nao.volum,
        NULL, slivr.obs, fnc_getadresa(slivr.sector, slivr.strada, slivr.nr1, slivr.nr2, slivr.bloc, slivr.scara, slivr.etaj, slivr.apart, slivr.codpostal), locl.den_localit, judl.den_judet, taral.den_tara, zonal.den_zona,
        CASE WHEN ag_doc.codpers = 0 THEN ag_doc.nume ELSE ag_doc.nume||'' ''||ag_doc.prenume END, nao1.grupa, nao1.uplift,lg.d1,lg.d2,lg.d3,
        cs.den_claseas, ca.den_clasea, ca.simbol, cg.den_claseg, cg.simbol,
        lg.DataAchiz,lg.SerieLot,lg.NrCertif, pkg_list_base_utils_decode_tipdoc_scurt(lg.tipdoc), lg.obsdoc, ''Nu'' custodie, cc.denumire,
        lg.an andoc, lg.luna lunadoc, to_char(lg.an,''fm0000'')||''.''||to_char(lg.luna,''fm00'')||''.''||pkg_list_base_utils_decode_luna(lg.Luna) luna,
        NULL, NULL, NULL, NULL,
        NULL PIesDVal,
        0, NULL, NULL ' || coalesce(sCursRef,'') || coalesce(sPMP,'') || coalesce(sSelectDC,'') || gUserAlias || '
      FROM lg
        INNER JOIN num1 u1       ON u1.codum1       = lg.umsec
        INNER JOIN nartobj nao   ON nao.codobiect   = lg.codobiect
        INNER JOIN nart na       ON na.codarticol   = nao.codarticol
        LEFT  JOIN livr l        ON l.codlivr       = lg.codlivr
        LEFT  JOIN NUM UM1       ON um1.codum       = na.um1
        LEFT  JOIN NUM UM2       ON um2.codum       = na.um2
        LEFT  JOIN ngest g       ON g.codgest       = lg.gest
        LEFT  JOIN ngest go      ON go.codgest      = lg.gestorig
        LEFT  JOIN nlocatii nl   ON nl.codlocatie   = lg.codlocatie
        LEFT  JOIN nsubunit ss   ON ss.codsubunit   = lg.subunitatea
        LEFT  JOIN doccarnete dc ON dc.codcarnet    = lg.carnetlivr
        LEFT  JOIN nmonede mon   ON mon.codmoneda   = lg.moneda
        LEFT  JOIN nclasea ca    ON ca.codclasea    = na.clasa
        LEFT  JOIN nclaseas cs   ON cs.codclaseas   = na.clasastatist
        LEFT  JOIN ioart io      ON io.codioart     = lg.codioart
        LEFT  JOIN ioart1 io1    ON io1.codioart    = lg.codioart AND (lg.an*12+lg.luna) BETWEEN  io1.ALStart and  io1.ALStop
        LEFT  JOIN ncont nc      ON nc.codcont      = io1.cont
        LEFT  JOIN centrecost cc ON cc.codcentru    = lg.codcentru
        LEFT  JOIN ncont ncv     ON ncv.codcont     = Coalesce(io1.venituri,0)
        LEFT  JOIN ncont ncc     ON ncc.codcont     = Coalesce(io1.cheltuieli,0)
        LEFT  JOIN npart np      ON np.codpart      = lg.partener
        LEFT  JOIN ngest gd      ON gd.codgest      = lg.gestd
        LEFT  JOIN nclaseg cg    ON cg.codclaseg    = gd.codclasa
        LEFT  JOIN NAGENDA SLIVR ON slivr.codgest   = lg.gestd
        LEFT  JOIN NLOCALIT LOCl ON locl.codlocalit = slivr.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 nlocatii nld  ON nld.codlocatie  = lg.codlocatied
        LEFT  JOIN npart prod    ON prod.codpart    = nao.codproducator
        LEFT  JOIN npart furn    ON furn.codpart    = lg.furn
        LEFT  JOIN ngest gfurn   ON gfurn.codgest   = lg.gestfurn
        LEFT  JOIN npers ag_doc  ON ag_doc.codpers  = lg.agent
        LEFT  JOIN nparttr del   ON lg.delegat      = del.codparttr
        LEFT  JOIN NTARI TOrig   ON TOrig.CodTara   = nao.taraorigine
        LEFT  JOIN nartobj1 nao1 ON nao1.codobiect  = lg.codobiect AND (lg.an*12+lg.luna) BETWEEN nao1.ALStart and nao1.ALStop
        LEFT  JOIN nartamb aa    ON aa.codobiect    = lg.codobiect AND aa.umsec = lg.umsec
        LEFT  JOIN pretm pm      ON pm.codobiect    = lg.codobiect AND pm.subunitatea = lg.subunitatea AND pm.implicit = 1' || coalesce(sJoinDC,'') || gSuplJoins || '
     WHERE lg.cant &lt;&gt; 0';
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelectcomun,'') || coalesce(sselecties,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelectcomun,'') || coalesce(sselectint,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelectcomun,'') || coalesce(sselectt,''), aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_livrari_setjoinuri</obj_name>
  <obj_hashval>16f2433be80388d71adff86e3f16e3fd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrari_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 14.08.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_LIVRARI.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_livrdoc_baga_dinamic_cols</obj_name>
  <obj_hashval>568481d7fb74c34fdac7c2ab5802ae0b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrdoc_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSQL     varchar := '';
  sATRIB  varchar := current_setting('PKG_LIST_BASE_LIVRDOC.sATRIB', true);
BEGIN
  --Adina 21 septembrie 2020
  sSQL := 'INSERT INTO tmp_dinamic_cols(FIELDNAME, DISPLAY,INDEXLOCAL,COD)
  WITH x AS (
    SELECT Row_NUMBER() OVER (ORDER BY A1.CODATRIBUT, A1.VALOARE, A1.CODVALATR) Nr, A1.CODVALATR, A.DENUMIRE||'' - ''||A1.VALOARE Display
    FROM NATRIB1 A1 INNER JOIN NATRIB A ON A.CODATRIBUT = A1.CODATRIBUT
    WHERE A1.CODATRIBUT IN (' || coalesce(sATRIB,'') || ')
  )
  SELECT ''A''||NR::varchar, DISPLAY, NR, CODVALATR
  FROM x';

  DELETE FROM tmp_dinamic_cols;
  EXECUTE sSQL;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_livrdoc_setparams</obj_name>
  <obj_hashval>ad892ddf4db0015fd762239113e85b97</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrdoc_setparams(pcodies numeric DEFAULT NULL::numeric, pcodgest numeric DEFAULT NULL::numeric, pdoarinrosu boolean DEFAULT false)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodIes    NUMERIC;
  vCntFLivr NUMERIC;
BEGIN
  --Adina 21 septembrie 2020
  perform set_config('PKG_LIST_BASE_LIVRDOC.vCodIes'  ,(pCodIes)::varchar,false);
  perform set_config('PKG_LIST_BASE_LIVRDOC.vCntFLivr',(0)::varchar      ,false);

  vCodIes   := current_setting('PKG_LIST_BASE_LIVRDOC.vCodIes',   true)::NUMERIC;
  vCntFLivr := current_setting('PKG_LIST_BASE_LIVRDOC.vCntFLivr', true)::NUMERIC;

  IF  COALESCE(pCodGest, -1) &gt;= 0 THEN
    perform set_config('PKG_LIST_BASE_LIVRDOC.vCodGest',(pCodGest)::varchar,false);
  ELSE
    perform set_config('PKG_LIST_BASE_LIVRDOC.vCodGest',(-1)::varchar,false);
  END IF;


  perform set_config('PKG_LIST_BASE_LIVRDOC.vSubCur',getSUBUNITATE()::varchar,false);

  DELETE FROM iesiri1_man;

  IF  vCodIes &gt; 0 THEN
    IF pDoarInRosu THEN
      INSERT INTO IESIRI1_MAN  SELECT * FROM IESIRI1 WHERE CodIes = vCodIes AND  Cant &lt; 0;
    ELSE
      INSERT INTO IESIRI1_MAN  SELECT * FROM IESIRI1 WHERE CodIes = vCodIes;
    END IF;

    perform set_config('PKG_LIST_BASE_LIVRDOC.vAuxNSIN',('
          WHERE L.CODIES = ' || coalesce(vCodIes::varchar ,''))::varchar,false);
  ELSE
    SELECT Count(1) INTO vCntFLivr FROM TMP_MANEVRA_LISTE TMP WHERE UPPER(tmp.filtru) = 'CODLIVR';
    perform set_config('PKG_LIST_BASE_LIVRDOC.vCntFLivr',(vCntFLivr)::varchar,false);

    IF  vCntFLivr &gt; 0 THEN
      IF pDoarInRosu THEN
        INSERT INTO IESIRI1_MAN
        WITH L1G AS (  SELECT  DISTINCT L1.CODIES1
                      FROM   TMP_MANEVRA_LISTE TMP INNER JOIN LIVR1 L1 ON  L1.CODLIVR::varchar = TMP.VALOARE
                      WHERE UPPER(tmp.filtru) = 'CODLIVR'
                    )
        SELECT I1.*
        FROM   L1G INNER JOIN IESIRI1 I1 ON  I1.CODIES1 = L1G.CODIES1
        WHERE I1.CANT &lt; 0;
      ELSE
        INSERT INTO IESIRI1_MAN
        WITH L1G AS (  SELECT  DISTINCT L1.CODIES1
                      FROM   TMP_MANEVRA_LISTE TMP INNER JOIN LIVR1 L1 ON  L1.CODLIVR::varchar = TMP.VALOARE
                      WHERE UPPER(tmp.filtru) = 'CODLIVR'
                    )
        SELECT I1.*
        FROM   L1G INNER JOIN IESIRI1 I1 ON  I1.CODIES1 = L1G.CODIES1;
      END IF;

      perform set_config('PKG_LIST_BASE_LIVRDOC.vAuxNSIN',('
            INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = L.CODLIVR::varchar AND UPPER(tmp.filtru) = ''CODLIVR''')::varchar,false);
    ELSE
      IF pDoarInRosu THEN
        INSERT INTO IESIRI1_MAN
        SELECT I1.*
        FROM   TMP_MANEVRA_LISTE TMP INNER JOIN IESIRI1 I1 ON  I1.CODIES::varchar = TMP.VALOARE
        WHERE UPPER(tmp.filtru) = 'CODIES' AND  I1.CANT &lt; 0;
      ELSE
        INSERT INTO IESIRI1_MAN
        SELECT I1.*
        FROM   TMP_MANEVRA_LISTE TMP INNER JOIN IESIRI1 I1 ON  I1.CODIES::varchar = TMP.VALOARE
        WHERE UPPER(tmp.filtru) = 'CODIES';
      END IF;

      perform set_config('PKG_LIST_BASE_LIVRDOC.vAuxNSIN',('
            INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = L.CODIES::varchar AND UPPER(tmp.filtru) = ''CODIES''')::varchar,false);
    END IF;
  END IF;

  PERFORM pkg_globals_SetSeparator(',');
  perform set_config('PKG_LIST_BASE_LIVRDOC.sATRIB',COALESCE(fnc_GetValConstanta('AtribArtDinColLivr', getANLUCRU(), getLUNALUCRU()), '0')::varchar,false);
  PERFORM PKG_LIST_BASE_LIVRDOC_BAGA_DINAMIC_COLS();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_livrfromnir_processlist</obj_name>
  <obj_hashval>842d4514b7d53f3ee37ad0fa8d1df0b5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrfromnir_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert               VARCHAR := '';
  vTipAnaliza            NUMERIC := current_setting('PKG_LIST_BASE_LIVRFROMNIR.vTipAnaliza'         , true)::numeric;
  vConditieStocNegativ  varchar := current_setting('PKG_LIST_BASE_LIVRFROMNIR.vConditieStocNegativ', true);
  vCodDocAnalizat        varchar := current_setting('PKG_LIST_BASE_LIVRFROMNIR.vCodDocAnalizat'     , true);
BEGIN
  --Adina 13.10.2020
  sInsert:= 'INSERT INTO '||tmpName||
            '(DENOBIECT,
              NRNIR,
              DATAACHIZ,
              CANTNIR,
              LIVRAT,
              REST,
              PREFIXDOC,
              NRDOC,
              DATADOC
             )
              SELECT
                 ANALIZA.DENOBIECT,
                 ANALIZA.NRNIR,
                 ANALIZA.DATAACHIZ,
                 ANALIZA.CANTNIR,
                 ANALIZA.LIVRAT,
                 ANALIZA.REST,
                 ANALIZA.PREFIXDOC,
                 ANALIZA.NRDOC,
                 ANALIZA.DATADOC
                 FROM
                  (
                   SELECT
                       LIVR_DIN_NIRSTOC.DENOBIECT,
                       LIVR_DIN_NIRSTOC.CODNIRSTOC,
                       LIVR_DIN_NIRSTOC.CODLIVR1,
                       (CASE
                          WHEN  LIVR_DIN_NIRSTOC.TIPNIR BETWEEN 1   AND  9 THEN  LIVR_DIN_NIRSTOC.CODINTR
                          WHEN  LIVR_DIN_NIRSTOC.TIPNIR BETWEEN 12  AND 13 THEN  LIVR_DIN_NIRSTOC.CODTRANSF
                          WHEN  LIVR_DIN_NIRSTOC.TIPNIR IN (14, 15, 16) OR  LIVR_DIN_NIRSTOC.TIPNIR BETWEEN 19  AND 26 THEN  LIVR_DIN_NIRSTOC.CODIES
                          ELSE NULL
                        END) CODDOCRECEPTIE,
                       LIVR_DIN_NIRSTOC.CODINTR,
                       LIVR_DIN_NIRSTOC.NRNIR,
                       LIVR_DIN_NIRSTOC.TIPNIR,
                       LIVR_DIN_NIRSTOC.DATAACHIZ,
                       LIVR_DIN_NIRSTOC.CANTNIR,
                       LIVR_DIN_NIRSTOC.CANT AS LIVRAT,
                       LIVR_DIN_NIRSTOC.REST,
                       LIVR_DIN_NIRSTOC.TIPLIVR,
                       (
                        CASE
                          WHEN  LIVR_DIN_NIRSTOC.TIPLIVR BETWEEN 1   AND 9 THEN PREFIXDOCINTR
                          WHEN  LIVR_DIN_NIRSTOC.TIPLIVR BETWEEN 12 AND 13 THEN PREFIXDOCTRANSF
                          WHEN  LIVR_DIN_NIRSTOC.TIPLIVR IN (14, 15, 16) OR LIVR_DIN_NIRSTOC.TIPLIVR BETWEEN 19 AND 26 THEN PREFIXDOCIES
                          ELSE NULL
                        END
                       ) PREFIXDOC,
                       (CASE
                          WHEN  LIVR_DIN_NIRSTOC.TIPLIVR BETWEEN 1   AND 9 THEN   LIVR_DIN_NIRSTOC.CODINTRLIVR
                          WHEN  LIVR_DIN_NIRSTOC.TIPLIVR BETWEEN 12  AND 13 THEN  LIVR_DIN_NIRSTOC.CODTRANSFLIVR
                          WHEN  LIVR_DIN_NIRSTOC.TIPLIVR IN (14, 15, 16) OR LIVR_DIN_NIRSTOC.TIPLIVR BETWEEN 19  AND 26 THEN  LIVR_DIN_NIRSTOC.CODIESLIVR
                          ELSE NULL
                        END) CODDOCLIVRARE,
                      (
                        CASE
                          WHEN  LIVR_DIN_NIRSTOC.TIPLIVR BETWEEN 1   AND 9 THEN NRDOCINTR
                          WHEN  LIVR_DIN_NIRSTOC.TIPLIVR BETWEEN 12 AND 13 THEN NRDOCTRANSF
                          WHEN  LIVR_DIN_NIRSTOC.TIPLIVR IN (14, 15, 16) OR LIVR_DIN_NIRSTOC.TIPLIVR BETWEEN 19 AND 26 THEN NRDOCIES
                          ELSE NULL
                        END
                      ) NRDOC,
                      (
                         CASE
                           WHEN  LIVR_DIN_NIRSTOC.TIPLIVR BETWEEN 1   AND 9 THEN DATADOCINTR
                           WHEN  LIVR_DIN_NIRSTOC.TIPLIVR BETWEEN 12 AND 13 THEN DATADOCTRANSF
                           WHEN  LIVR_DIN_NIRSTOC.TIPLIVR IN (14, 15, 16) OR LIVR_DIN_NIRSTOC.TIPLIVR BETWEEN  19 AND 26 THEN DATADOCIES
                         ELSE NULL
                       END
                      ) DATADOC
                   FROM
                   (
                    SELECT
                      NS.CODNIRSTOC,
                      O.DENUMIRE AS DENOBIECT,
                      NS.DATAACHIZ,
                      NS.CANTNIR,
                      NS.REST,
                      N.CODINTR,
                      N.CODIES,
                      N.CODTRANSF,
                      N.TIPNIR,
                      N.NRNIR,
                      L1.CANT,
                      L1.CODLIVR1,
                      L.TIPLIVR,
                      IES.CODIES AS CODIESLIVR,
                      IES.NRDOC AS NRDOCIES,
                      IES.DATADOC AS DATADOCIES,
                      IES.PREFIXDOC AS PREFIXDOCIES,
                      INTR.CODINTR AS CODINTRLIVR ,
                      INTR.NRDOC AS NRDOCINTR ,
                      INTR.DATADOC AS DATADOCINTR,
                      INTR.PREFIXDOC AS PREFIXDOCINTR,
                      TRANSF.CODTRANSF AS CODTRANSFLIVR,
                      TRANSF.NRDOC AS NRDOCTRANSF,
                      TRANSF.DATADOC AS DATADOCTRANSF,
                      TRANSF.PREFIXDOC AS PREFIXDOCTRANSF
                   FROM
                     NIRSTOC NS,
                     NIR   N,
                     LIVR1 L1,
                     LIVR L
                     LEFT OUTER JOIN IESIRI  IES    ON IES.CODIES       = L.CODIES
                     LEFT OUTER JOIN INTRARI INTR   ON INTR.CODINTR     = L.CODINTR
                     LEFT OUTER JOIN TRANSF  TRANSF ON TRANSF.CODTRANSF = L.CODTRANSF,
                     NARTOBJ O
                   WHERE
                     N.CODNIR      = NS.CODNIR AND
                     L1.CODNIRSTOC = NS.CODNIRSTOC AND
                     L1.CODLIVR    = L.CODLIVR AND ' || vConditieStocNegativ||
                '     O.CODOBIECT   = NS.CODOBIECT
                   ) LIVR_DIN_NIRSTOC
                     ORDER BY DENOBIECT, DATADOC
                )
                  ANALIZA';

     if vTipAnaliza = 1 then
       sInsert := sInsert||
                  ' WHERE EXISTS
                     (SELECT CODNIRSTOC FROM NIRSTOC NS, NIR N WHERE NS.CODNIR = N.CODNIR AND '||vCodDocAnalizat||' AND NS.CODNIRSTOC = ANALIZA.CODNIRSTOC)
                   ORDER BY  PREFIXDOC, NRDOC, DATADOC';
     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_livrfromnir_setjoinuri</obj_name>
  <obj_hashval>3dcd7b4cb25ecf71bc05b6902780d6fe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrfromnir_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_livrfromnir_setparams</obj_name>
  <obj_hashval>0be5351c4bfb9d8bb66344c5d7a82cb1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrfromnir_setparams(pconditiestocnegativ character varying, ptipanaliza numeric, pcoddocanalizat character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 13.10.2020
  --Bogdan 28.01.2021
  perform set_config('PKG_LIST_BASE_LIVRFROMNIR.vConditieStocNegativ',pConditieStocNegativ   ,false);
  perform set_config('PKG_LIST_BASE_LIVRFROMNIR.vTipAnaliza'         ,pTipAnaliza  :: varchar,false);
  perform set_config('PKG_LIST_BASE_LIVRFROMNIR.vCodDocAnalizat'     ,pCodDocAnalizat        ,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_livrintrdoc_processparams</obj_name>
  <obj_hashval>28537d936847c13edc2e32cc4a609f90</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrintrdoc_processparams()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  vTipDoc     numeric;
  vCodLocatie numeric;
  vPartener   numeric;
  vCodGest    NUMERIC := current_setting('PKG_LIST_BASE_LIVRINTRDOC.vCodGest', true)::numeric;
  vCodIntr    NUMERIC := current_setting('PKG_LIST_BASE_LIVRINTRDOC.vCodIntr', true)::numeric;
BEGIN
  --Florin 10.04.2024 - fixat 61640
  --Florin 21.06.2022 - sinc. Oracle
  --Adina 13.10.2020
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  IF  COALESCE(getSUBUNITATE(), 0) = 0 THEN
    PERFORM pkg_globals_SetSubunitate(current_setting('PKG_LIST_BASE_LIVRINTRDOC.vSubCur', true)::numeric);
  END IF;

  FOR v_rec IN
  (
    SELECT G.DEN_GEST, NumePrenume(NP.Nume, NP.Prenume) GESTIONAR
    FROM   NGEST G LEFT JOIN NPERS NP ON  G.CODGESTIONAR = NP.CODPERS
    WHERE G.CODGEST = vCodGest
  )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('GESTIUNE',           v_rec.Den_Gest);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('GESTIUNE GESTIONAR', v_rec.Gestionar);
    EXIT ;
  END LOOP;

  FOR v_rec IN
  (
    SELECT I.TIPDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC, I.OBS, I.PARTENER, I.CODLOCATIE
    FROM INTRARI I
    WHERE I.CODINTR = vCodIntr
  )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT',       v_rec.PrefixDoc);
    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 OBS',   v_rec.Obs);
    vTipDoc     := v_rec.TipDoc;
    vPartener   := v_rec.Partener;
    vCodLocatie := v_rec.CodLocatie;
    EXIT ;
  END LOOP;

  FOR v_rec IN
  (
    SELECT STRING_AGG(NrLivr::varchar,',') NRLIVR, STRING_AGG(DataLivr,',') DATALIVR, STRING_AGG(ObsLivr,',') OBSLIVR, STRING_AGG(ZiLivr::varchar,',') ZILIVR
    FROM (
          SELECT  DISTINCT L.NRLIVR, To_Char(L.DATALIVR, 'dd.mm.yyyy') DATALIVR, L.OBS OBSLIVR, EXTRACT( DAY FROM L.DATALIVR) ZILIVR
          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
                LEFT JOIN nir n      ON  n.codnir      = ns.codnir
          WHERE L.CodIntr = vCodIntr AND (vCodGest = -1 OR  Coalesce(lv.gest, n.gest, 0) = vCodGest)
         ) A_PG
  )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOC.LIVR.NUMAR', v_rec.NrLivr);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOC.LIVR.DATA',  v_rec.DataLivr);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOC.LIVR.OBS',   v_rec.ObsLivr);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOC.LIVR.ZI',    v_rec.ZiLivr);
    EXIT ;
  END LOOP;

  FOR v_rec IN
  (
    SELECT n.nume, n.prenume, n.cnp, d.delegat, d.doc DELDOC, d.nrdoc NRDOCTRANSP, d.seriedoc, d.eliberat, d.cnp DELCNP, d.mijltransp, d.nrtransp, d.datadoc DELDATADOC
    FROM   INTRARI I
          LEFT JOIN NPERS N   ON  I.USERID  = N.LOGONNAME
          LEFT JOIN NPARTTR D ON  I.DELEGAT = D.CODPARTTR
    WHERE I.CODINTR = vCodIntr
  )
  LOOP
    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('TRANSPORT DELEGAT',        v_rec.DELEGAT);
    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.NRDOCTRANSP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT SERIE DOCUMENT', v_rec.SERIedoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DOC ELIBERAT',   v_rec.ELIBERAT);
    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.MIJLTRANSP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT NR MIJLOC',      v_rec.NRTRANSP);
    EXIT ;
  END LOOP;

  PERFORM pkg_list_Struct_ADAUGA_PARAM('MASA FACTURATA',               TO_CHAR(0, 'fm9G999G999G990D00'));
  PERFORM pkg_list_Struct_ADAUGA_PARAM('VOLUM FACTURAT',               TO_CHAR(0, 'fm9G999G999G990D00'));
  PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET SERIE',                  '');
  PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET NUMAR',                  '');
  PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET NUMAR PACHETE',          '');
  PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET DATA',                   '');
  PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET Identificator',          '');
  PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET PERSOANA COLECTARE',     '');
  PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET DATA COLECTARE',         '');
  PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET PERSOANA VERIFICATOARE', '');
  PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET DATA VERIFICARE',        '');
  PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET TRANSPORT PERSOANA',     '');
  PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET TRANSPORT DATA',         '');

  IF vTipDoc IN (1, 2, 3, 5) THEN  -- parametrii client
    FOR v_rec IN (
      SELECT
        PB.CONTBANCA, B.DENUMIRE, B.SIMBOL, I.VALDOC, I.TVADOC
      FROM INTRARI I
        LEFT JOIN NPARTB PB ON PB.CODPART = I.PARTENER AND PB.IMPLICIT = 1
        LEFT JOIN NBANK B ON B.CODBANK = PB.CODBANK
      WHERE I.CODINTR = vCodIntr
    ) LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CONT', v_rec.CONTBANCA);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT BANCA', v_rec.DENUMIRE);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT SIMBOL BANCA', v_rec.SIMBOL);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA', TO_CHAR(TRUNC(COALESCE(v_rec.TVADOC,0), 2)));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VALOARE', TO_CHAR(TRUNC(COALESCE(v_rec.VALDOC,0)-COALESCE(v_rec.TVADOC,0), 2)));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL', TO_CHAR(TRUNC(COALESCE(v_rec.VALDOC,0), 2)));
      EXIT;
    END LOOP;
    FOR v_rec IN
    (
      SELECT A.Obs, J.Den_Judet, A.TELEFON,
             fnc_GetAdresa(A.sector, A.strada, A.nr1, A.nr2, A.bloc, A.scara, A.etaj, A.apart, A.codpostal) AS ADRESA, L.DEN_LOCALIT, J.SIMBAUTO, A.CODCLIENT
      FROM   NAGENDA A
            LEFT JOIN NLOCALIT L ON  A.CODLOCALIT = L.CODLOCALIT
            LEFT JOIN NJUDET J   ON  L.CODJUDET   = J.CODJUDET
      WHERE CODAGENDA = vCodLocatie
    )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE ADRESA',        v_rec.Adresa);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE DENUMIRE',      v_rec.OBS);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE LOCALITATE',    v_rec.Den_Localit);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE JUDET',         v_rec.DEN_JUDET);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE TELEFON',       v_rec.Telefon);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE COD LA CLIENT', v_rec.CodClient);
      EXIT ;
    END LOOP;

    FOR v_rec IN
    (
      SELECT P.DEN_PART, C.CODFISCAL, P.AUTORIZATIE, A.OBS, L.DEN_LOCALIT, J.Den_Judet, CASE
       WHEN  P.PERSOANAFIZICA=1 THEN NULL ELSE  P.REGCOM END  REGCOM, coalesce(PC.NUME,'') || ' ' || coalesce(PC.PRENUME,'') PERSC
      FROM   NPART P
            LEFT JOIN NPARTCODFISC C  ON  C.CODPART = P.CODPART AND  C.PRINCIPAL = 1
            LEFT JOIN NAGENDA A       ON  A.CODPART = P.CODPART AND  COALESCE(a.Inactiv, 0) = 0 AND A.SEDIUSOCIAL IN (4, 5, 6, 7)
            LEFT JOIN NLOCALIT L      ON  A.CODLOCALIT = L.CODLOCALIT
            LEFT JOIN NJUDET J        ON  L.CODJUDET = J.CODJUDET
            LEFT JOIN NPERSCONTACT PC ON  PC.CODPART = P.CODPART
      WHERE P.CODPART = vPartener
    )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT DENUMIRE',                   v_rec.Den_Part);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT COD FISCAL',                 v_rec.CodFiscal);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT REGISTRU COMERT',            v_rec.RegCom);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT AUTORIZATIE SPECIALA',       v_rec.Autorizatie);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT SEDIU SOCIAL',               v_rec.Obs);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT LOCALITATE SEDIU SOCIAL',    v_rec.Den_Localit);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT JUDET SEDIU SOCIAL',         v_rec.Den_Judet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT PERSOANA CONTACT IMPLICITA', v_rec.PersC);
      EXIT ;
    END LOOP;
  ELSIF vTipDoc = 6 THEN -- parametrii subunitati
    FOR v_rec IN
    (
      SELECT S.Den_Subunit, L.DEN_LOCALIT, S.RegCom, BK.DENUMIRE AS BANCA, BC.nrCONT CONTBANCA, fnc_GetAdresa(A.sector, A.strada, A.nr1, A.nr2, A.bloc, A.scara, A.etaj, A.apart, A.codpostal) ADRESA, S.CIF
      FROM   INTRARI I
            INNER JOIN NSUBUNIT S  ON  I.CODSUBUNIT  = S.CODSUBUNIT
            LEFT JOIN NAGENDA A    ON  S.CODSUBUNIT  = A.CODSUBUNIT
            LEFT JOIN nbankcont BC ON  S.codbankcont = BC.codbankcont
            LEFT JOIN nbank BK     ON  BC.codbank    = BK.codbank
            LEFT JOIN NLOCALIT L   ON  A.CODLOCALIT  = L.CODLOCALIT
      WHERE I.CODINTR = vCodIntr
    )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SUBUNITATE DESTINATIE DENUMIRE',   v_rec.DEN_SUBUNIT);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SUBUNITATE DESTINATIE LOCALITATE', v_rec.DEN_LOCALIT);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SUBUNITATE DESTINATIE ADRESA',     v_rec.ADRESA);
      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 BANCA',      v_rec.banca);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Subunitate DESTINATIE CONT',       v_rec.contbanca);
      EXIT ;
    END LOOP;
  ELSIF vTipDoc = 7 THEN -- parametrii productie proprie
    FOR v_rec IN
    (
      SELECT G.DEN_GEST
      FROM INTRARI I LEFT JOIN NGEST G ON I.CODGESTPROD = G.CODGEST
      WHERE I.CODINTR  = vCodIntr
    )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('GESTIUNE PRODUCATOARE'   , v_rec.DEN_GEST);
      EXIT;
    END LOOP;
  END IF;

  PERFORM pkg_list_Struct_ADAUGA_PARAM_EXT('INTRARIF', 'CODINTR', vCodIntr);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_livrintrdoc_setjoinuri</obj_name>
  <obj_hashval>67d1e26bcda0f8f9dd14ba92f6073e78</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrintrdoc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 13.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_LIVRINTRDOC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_livrintrdoc_setparams</obj_name>
  <obj_hashval>3d5852ca384b5a6bce1e26b4711d7027</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrintrdoc_setparams(pcodintr numeric DEFAULT NULL::numeric, pcodgest numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 13.10.2020
  perform set_config('PKG_LIST_BASE_LIVRINTRDOC.vCodIntr',(pCodIntr)::varchar     ,false);
  perform set_config('PKG_LIST_BASE_LIVRINTRDOC.vSubCur' ,getSUBUNITATE()::varchar,false);

  IF  COALESCE(pCodGest, -1) &gt;= 0 THEN
    perform set_config('PKG_LIST_BASE_LIVRINTRDOC.vCodGest',(pCodGest)::varchar,false);
  ELSE
    perform set_config('PKG_LIST_BASE_LIVRINTRDOC.vCodGest',(-1)::varchar,false);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_livrnerez_processlist</obj_name>
  <obj_hashval>df538923599724c98a84dfc39b340582</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrnerez_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 := 'tmp_livr_nerezolvate tmp';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 13.10.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJ'   , 'O'   , 'O.CODOBIECT = TMP.CODOBIECT' ,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, 'NPART'     , 'P'   , 'P.CODPART = TMP.CODPART'     ,NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_LIVRNEREZ.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    SERIEFACTURA, NRFACTURA, DENOBIECT, CANT, DENUM, CLIENT, COMANDA ' || gUserFields || ')';

  sSelect := '
  SELECT
    tmp.seriefactura, tmp.nrfactura, tmp.denobiect, tmp.cant, tmp.denum, tmp.client, tmp.comanda ' || gUserAlias || '
  FROM tmp_livr_nerezolvate tmp ' || gSuplJoins;

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

  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN (SELECT tmp.seriefactura, tmp.nrfactura, tmp.client, tmp.comanda FROM tmp_livr_nerezolvate tmp) LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT DENUMIRE', v_rec.client);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('FACTURA',         v_rec.nrfactura::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COMANDA',         v_rec.comanda);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_livrpkdoc_setparams</obj_name>
  <obj_hashval>b05ed53740e0ebe682569a4c8c5aa819</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrpkdoc_setparams(pcodpachete numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTipPachet   NUMERIC;
  vTipLivrare  NUMERIC;
BEGIN
  --Adina 13.10.2020
  perform set_config('PKG_LIST_BASE_LIVRPKDOC.vCodPachete',(pCodPachete)::varchar,false);

  SELECT COALESCE(tippachet, 0), COALESCE(tiplivrare, 4)
  INTO vTipPachet, vTipLivrare
  FROM pachete
  WHERE codpachete = current_setting('PKG_LIST_BASE_LIVRPKDOC.vCodPachete', true)::numeric;

  perform set_config('PKG_LIST_BASE_LIVRPKDOC.vTipPachet' ,(vTipPachet)::varchar,false);
  perform set_config('PKG_LIST_BASE_LIVRPKDOC.vTipLivrare',(vTipLivrare)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_livrsimpl_setjoinuri</obj_name>
  <obj_hashval>47b78d0e002f21038467c08bc41544b4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrsimpl_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 14.08.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_LIVRSIMPL.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_livrtransf_setparams</obj_name>
  <obj_hashval>a1ecf7fb0cf478aeaf5757c168a3be15</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrtransf_setparams(pcodtransf numeric DEFAULT NULL::numeric, pcodgest numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 18 septembrie 2020
  perform set_config('PKG_LIST_BASE_LIVRTRANSF.vCodTransf',(pCodTransf)::varchar,false);
  IF  COALESCE(pCodGest, -1) &gt;= 0 THEN
    perform set_config('PKG_LIST_BASE_LIVRTRANSF.vCodGest',(pCodGest)::varchar,false);
  ELSE
    perform set_config('PKG_LIST_BASE_LIVRTRANSF.vCodGest',(-1)::varchar,false);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_logimportcom_processlist</obj_name>
  <obj_hashval>120eea25747470bdcbcc16c0198d8c5a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_logimportcom_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 01.09.2020
   gSuplCols := 'LOGIMPORTDOC L, NPART P, NARTOBJ O, COMANDA C';

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

  sInsert := 'INSERT INTO ' || coalesce(TMPNAME,'')
        || ' (NRDOC, DATADOC, DATAIMP, PART, ART, OPER, CANTO, CANTN'
        || coalesce(gUserFields,'') || ')';
  sSelect := '
        SELECT
          L.NRDOC, L.DATADOC, L.DATAIMPORT, P.DEN_PART, O.DENUMIRE,
          (case when L.TIPOPERATIE = ''A'' then ''Adaugare'' when L.TIPOPERATIE = ''M'' then ''Modificare'' end),
          L.CANTVECHI, L.CANTNOU ' || coalesce(gUserAlias,'') || '
        FROM LOGIMPORTDOC L
          LEFT JOIN NPART   P ON P.CODPART   = L.CODPART
          LEFT JOIN NARTOBJ O ON O.CODOBIECT = L.CODOBIECT
          LEFT JOIN COMANDA C ON C.TIPDOC    = L.TIPDOC AND C.NRDOC = L.NRDOC AND C.DATADOC = L.DATADOC AND C.PARTENER = L.CODPART'
              || coalesce(gSuplJoins,'') || '
        WHERE L.TIPDOC = 18  ';
  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_logimportcom_setjoinuri</obj_name>
  <obj_hashval>96d732a97c2b60a1173e5c07696030ee</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_logimportcom_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 01.09.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_LOGIMPORTCOM.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_loguseri_processlist</obj_name>
  <obj_hashval>85d43351ca06b23b983c2d89331dbf18</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_loguseri_processlist(tmpname character varying, listid numeric DEFAULT 0, listver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  SKEMA           varchar := '';
  gSuplCols        VARCHAR := 'LOG LG, NSUBUNIT S';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  G_DATAS          varchar := current_setting('PKG_LIST_BASE_LOGUSERI.G_DATAS', true);
  G_DATAF          varchar := current_setting('PKG_LIST_BASE_LOGUSERI.G_DATAF', true);
BEGIN
  --Florin 08.03.2021 tichet 44585
  --Adina 03.02.2021 tichet 42695
  --Stef  15.01.2021
  --Adina 16.12.2020 tichet 41637
  --Adina 14.10.2020
  skema := Upper(current_setting('PKG_GLOBALS.FIRMANAME', true));

  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(listid, listver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_LOGUSERI.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO '|| TMPNAME ||' (
    UTILIZATOR,FIRMA,SUBUNITATE,
    TIPOPER,
    DATA_ORA,DATADOC,DOCUMENT,TABELA,CODDOC,OBS'||gUserFields||')
  SELECT
    LG.UTILIZATOR,LG.FIRMA,S.DEN_SUBUNIT,
    CASE LG.OPERATIE
      WHEN ''A''     THEN ''Adaugare''
      WHEN ''M''     THEN ''Modificare''
      WHEN ''S''     THEN ''Stergere''
      WHEN ''R''     THEN ''Refacere''
      WHEN ''F''     THEN ''Fixare''
      WHEN ''C''     THEN ''Actualizare''
      WHEN ''V''     THEN ''Verificare''
      WHEN ''I''     THEN ''Inchidere luna''
      WHEN ''D''     THEN ''Deschidere luna''
      WHEN ''REGB''  THEN ''Regularizare casa/banca''
      WHEN ''REGPA'' THEN ''Regularizare parteneri''
      WHEN ''REGPE'' THEN ''Regularizare personal''
      WHEN ''LST''   THEN ''Vizualizare lista''
      ELSE ''Operatie neidentificata''
    END TIPOPER,
    To_Char(LG.DATA,''dd.mm.yyyy hh24:mi:ss'') DATA_ORA, LG.DATADOC, LG.DOCUMENT, LG.TABELA, LG.CODDOC, LG.OBS '||gUserAlias||'
  FROM WINMADMIN.LOG LG
    LEFT JOIN NSUBUNIT S ON S.CODSUBUNIT = LG.SUBUNITATEA '||
    gSuplJoins||'
  WHERE UPPER(LG.FIRMA) = '''||skema||'''
    AND LG.DATA BETWEEN to_date('''||G_DATAS||''',''dd.mm.yyyy'') AND TO_DATE('''||G_DATAF||''',''dd.mm.yyyy'')+1';

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, ListID, ListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_loguseri_setjoinuri</obj_name>
  <obj_hashval>96394a3aea8441749776da7696cd0a0a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_loguseri_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_LOGUSERI.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_loguseri_setparams</obj_name>
  <obj_hashval>d59a305ceb8b08c637653b9aa5adfb0a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_loguseri_setparams(adatas character varying, adataf character varying, v_codjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
BEGIN
  --Adina 14.10.2020
  perform set_config('PKG_LIST_BASE_LOGUSERI.G_DATAS',(ADATAS)::varchar,false);
  perform set_config('PKG_LIST_BASE_LOGUSERI.G_DATAF',(ADATAF)::varchar,false);

  IF  COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, current_setting('PKG_LIST_BASE_LOGUSERI.G_DATAS', true), current_setting('PKG_LIST_BASE_LOGUSERI.G_DATAF', true), xLunaAnIni, xLunaAnFin);
  END IF;

  PERFORM PKG_ORA_LISTS_SET_INTERVAL_LISTARE(to_date(adatas,'dd.mm.yyyy'), to_date(adataf,'dd.mm.yyyy'));
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_mail_processlist</obj_name>
  <obj_hashval>97281e9b0b76809758da51c4459efc10</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_mail_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSelect         varchar := '';
  sZIstart         varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true);
  sZIstop         varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true);
  gSuplCols        VARCHAR := 'mailuri m';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
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_MAIL.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  sInsert := 'INSERT INTO ' || tmpName || '(
          NAV_CodDoc,
          NAV_TipDoc,
          CODMAIL,
          SENDER,
          RECIPIENTS,
          SUBJECT,
          MESSAGE,
          DATA,
          STATUS,
          EROARE,
          HOST,
          DOMAIN' || gUserFields || ' )';

  sSelect := '
  SELECT
        M.CodDoc,
        M.TipDoc,
        M.CODMAIL,
        M.SENDER,
        M.RECIPIENTS,
        M.SUBJECT,
        M.MESSAGE,
        M.DATA,
        M.STATUS,
        M.EROARE,
        M.HOST,
        M.DOMAIN' || gUserAlias || '
  FROM mailuri M' || gSuplJoins || '
    WHERE M.Data between TO_DATE(''' || coalesce(sZIstart,'') || ''', ''dd/mm/yyyy'') and TO_DATE(''' || coalesce(sZIstop,'') || ''', ''dd/mm/yyyy'')';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_mail_setparams</obj_name>
  <obj_hashval>9d03b7b933b902028641846f6c23fa69</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_mail_setparams(zi1 date, zi2 date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 11 septembrie 2020
  perform set_config('PKG_LIST_BASE_MAIL.sZi1',current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true),false);
  perform set_config('PKG_LIST_BASE_MAIL.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_manconformnp_processlist</obj_name>
  <obj_hashval>6c123c92f8a34e902e37de194c87d9e3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_manconformnp_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert      varchar;
  gSuplCols    varchar := 'intrari i, intrari1 i1, comanda1 c1, cmdprodman man, prodcomp pc, nartobj prod, nart artp, prodgest pg, ngest g, noper op, locmunca lm';
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplJoins   VARCHAR := '';
  sAnLunaLucru varchar := COALESCE( (getanlucru() * 12 + getlunalucru())::varchar,'0');
BEGIN
  --Adina 11.05.2021 - alstart,alstop, sAnLunaLucru
  --Florin 15.09.2020
  CALL PRC_AL_CHECK('tarifeman1', 0);

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

  sInsert := 'INSERT INTO ' || tmpName || '(
       NAV_CodDoc, NAV_TipDoc, Doc,
       Reteta, Produs, CantPredata, SectieExec, Ordine, NrOp, Operatie, LocMunca, DenTarif,
       tarif, tu, valoare,
       dsv, bps, tpi, obs, detalii ' || gUserFields || ')
    SELECT
      i.codintr, i.tipdoc, i.prefixdoc||'' ''||i.nrdoc||''/''||i.datadoc,
      pc.obs Reteta, prod.denumire Produs, i1.cant, G.Den_Gest SectieExec, man.IndexLocal Ordine, man.NrOp, op.denumire Operatie, lm.denumire LocMunca, t.denumire DenTarif,
      t.tarif, i1.cant/man.bps * man.tu, round(i1.cant/man.bps * (man.tu * t.tarif)/60,5) valoare,
      man.dsv, man.bps, man.tpi, man.obs, man.detalii ' || gUserAlias || '
    FROM intrari i
      INNER JOIN intrari1   i1   on i1.codintr      = i.codintr
      INNER JOIN comanda1   c1   on c1.codcomanda1  = i1.codcmdint1
      INNER JOIN cmdprodman man  on i1.codcmdint1   = man.codcomanda1
      INNER JOIN prodcomp   pc   on c1.codreteta    = pc.codprodcomp
      INNER JOIN nartobj    prod on prod.codobiect  = pc.codobiect
      INNER JOIN nart       artp on prod.codarticol = artp.codarticol
      LEFT  JOIN prodgest   pg   on pc.codprodcomp  = pg.codprodcomp and man.codprodgest = pg.codprodgest
      LEFT  JOIN ngest      g    on i.codgestprod   = g.codgest
      LEFT  JOIN noper      op   on man.codop       = op.codop
      LEFT  JOIN locmunca   lm   on lm.codloc       = man.codloc
      LEFT  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 NCLASEA    CLSP ON COALESCE(ARTP.CLASA,0) = CLSP.CODCLASEA' ||
      gSuplJoins || '
    WHERE COALESCE(pc.anulat, 0) = 0 and i.an*12+i.luna = getanlucru() * 12 + getlunalucru()
      and i.operat = 1 and COALESCE(i.anulat,0) = 0 and COALESCE(i.blocat,0) = 0 and i.tipdoc = 7
      and ((getsubunitate() = 1) or (getsubunitate() = i.subunitatea))';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_manconformnp_setjoinuri</obj_name>
  <obj_hashval>d560cca206eff2aa5ada6aba166086ee</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_manconformnp_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 15.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_MANCONFORMNP.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_manprod_setallparams</obj_name>
  <obj_hashval>3f42995d3fde17a66fbfb978fd9e1a53</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_manprod_setallparams(v_flgallart numeric, v_tip numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 14.09.2020
  perform set_config ('PKG_LIST_BASE_MANPROD.p_flgAllArt',v_flgAllArt::varchar,false);
  perform set_config ('PKG_LIST_BASE_MANPROD.p_Tip'      ,v_Tip::varchar      ,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_manprod_setjoinuri</obj_name>
  <obj_hashval>954f2e0d498ee24bfa776a5aec598590</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_manprod_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 14.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec (current_setting ('PKG_LIST_BASE_MANPROD.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_mariridimin_setjoinuri</obj_name>
  <obj_hashval>c640e4e9ad0ab28f2d4d67c6de9fdbb4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_mariridimin_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_MARIRIDIMIN.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_matsa_setjoinuri</obj_name>
  <obj_hashval>16c88369a93905e6ca1c081e074ecc14</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_matsa_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 20.05.2024 - sinc. Oracle
  --Adina 14.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting ('pkg_list_base_matsa.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_miscari_getcondart</obj_name>
  <obj_hashval>bab60eac7f5ace121ac4cd55cd9a7f8b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_miscari_getcondart(pcamp character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vResult varchar;
BEGIN
  --Florin 06.08.2020
  IF current_setting('PKG_LIST_SELECTPER.vToateArt', TRUE)::NUMERIC = 0  THEN
    vResult := ' AND ' || coalesce(pCamp,'') || '::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' ) ';
  END IF;
  RETURN vResult;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_miscari_getconddata</obj_name>
  <obj_hashval>fb5ac7e5bc62334577c0a2cadc780996</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_miscari_getconddata(palias character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vResult varchar;
BEGIN
  --Florin 06.08.2020
  IF current_setting('PKG_LIST_SELECTPER.vDupaData', TRUE)::NUMERIC = 1 THEN
    vResult := ' AND DATE_TRUNC(''HOUR'',' || coalesce(pAlias,'') || '.DATADOC) BETWEEN TO_DATE(''' || COALESCE(current_setting('PKG_LIST_SELECTPER.vDataIni', TRUE),'')|| ''',''DD.MM.YYYY'')
                                                                                    AND TO_DATE(''' || COALESCE(current_setting('PKG_LIST_SELECTPER.vDataFin', TRUE),'')|| ''',''DD.MM.YYYY'') ';
  ELSIF current_setting('PKG_LIST_SELECTPER.vDataIni', TRUE) = current_setting('PKG_LIST_SELECTPER.vDataFin', TRUE) THEN
    vResult := ' AND (' || COALESCE(pAlias,'') || '.AN*12 + ' || COALESCE(pAlias,'') || '.LUNA) = ' || COALESCE(current_setting('PKG_LIST_SELECTPER.vLunaAnIni', TRUE),'');
  ELSE
    vResult := ' AND (' || coalesce(pAlias,'') || '.AN*12+ ' || coalesce(pAlias,'') || '.LUNA) BETWEEN ' || coalesce(current_setting('PKG_LIST_SELECTPER.vLunaAnIni', TRUE),'') || ' AND ' || coalesce(current_setting('PKG_LIST_SELECTPER.vLunaAnFin', TRUE),'');
  END IF;
  RETURN vResult;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_miscari_getcondgest</obj_name>
  <obj_hashval>f443ce025473f053832c6ef6605377ad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_miscari_getcondgest(pcamp character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vResult varchar;
BEGIN
  --Florin 06.08.2020
  IF current_setting('PKG_LIST_SELECTPER.vToateGest', TRUE)::NUMERIC = 0 THEN
    vResult := ' AND ' || coalesce(pCamp,'') || '::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
  END IF;
  RETURN vResult;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_miscari_getnircuserii</obj_name>
  <obj_hashval>e414ab22b8aeb517489baafd44138a87</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_miscari_getnircuserii()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar;
BEGIN
  --Florin 25.08.2020
  sInsert := 'INSERT INTO TMP_MANEVRA_LISTE(FILTRU,VALOARE)
  SELECT DISTINCT ''CODNIRSTOC'', ns.codnirstoc
  FROM (
    SELECT codtransf
    FROM transf ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('', 'subunitatea', 'WHERE',NULL),'');
  IF current_setting('PKG_LIST_SELECTPER.vDupaData', TRUE)::NUMERIC = 1 THEN
    sInsert := coalesce(sInsert,'') || '
            AND To_Date(TO_CHAR(DATADOC, ''DD.MM.YYYY''), ''DD.MM.YYYY'') BETWEEN TO_DATE(''' || coalesce(current_setting('PKG_LIST_SELECTPER.vDataIni', TRUE),'') || ''',''DD.MM.YYYY'')
                                                                              AND TO_DATE(''' || coalesce(current_setting('PKG_LIST_SELECTPER.vDataFin', TRUE),'') || ''',''DD.MM.YYYY'') ';
  ELSIF current_setting('PKG_LIST_SELECTPER.vLunaAnIni', TRUE)::NUMERIC = current_setting('PKG_LIST_SELECTPER.vLunaAnFin', TRUE)::NUMERIC THEN
    sInsert := coalesce(sInsert,'') || '
            AND (AN*12 + LUNA) = ' || coalesce(current_setting('PKG_LIST_SELECTPER.vLunaAnIni', TRUE)::NUMERIC, 0);
  ELSE
    sInsert := coalesce(sInsert,'') || '
            AND (AN*12 + LUNA) BETWEEN ' || coalesce(current_setting('PKG_LIST_SELECTPER.vLunaAnIni', TRUE)::NUMERIC, 0) || ' AND ' || coalesce(current_setting('PKG_LIST_SELECTPER.vLunaAnFin', TRUE)::NUMERIC, 0);
  END IF;
  sInsert := coalesce(sInsert,'') || '
        ) t
        INNER JOIN transf1 t1 ON t.codtransf   = t1.codtransf
        INNER JOIN nirstoc ns ON t1.codtransf1 = ns.codtransf1 AND ns.tipserie &gt; 0
        INNER JOIN NIR        ON NIR.CODNIR    = NS.CODNIR
      WHERE 1 = 1 ';
  IF current_setting('PKG_LIST_SELECTPER.vToateArt', TRUE)::NUMERIC = 0 THEN
    sInsert := coalesce(sInsert,'') || '
        AND NS.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'') ';
  END IF;
  IF current_setting('PKG_LIST_SELECTPER.vToateGest', TRUE)::NUMERIC = 0 THEN
  sInsert := coalesce(sInsert,'') || '
        AND NIR.GEST::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
  END IF;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, 0, 0);
  sInsert := 'INSERT INTO TMP_MANEVRA_LISTE(FILTRU,VALOARE)
      SELECT DISTINCT  ''CODNIRSTOC'', l1.codnirstoc
      FROM (
        SELECT codies
      FROM iesiri ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('', 'subunitatea', 'WHERE',NULL),'');
  IF current_setting('PKG_LIST_SELECTPER.vDupaData', TRUE)::NUMERIC = 1 THEN
    sInsert := coalesce(sInsert,'') || '
          AND DATADOC BETWEEN TO_DATE(''' || coalesce(current_setting('PKG_LIST_SELECTPER.vDataIni', TRUE),'') || ''',''DD.MM.YYYY'')
          AND TO_DATE(''' || coalesce(current_setting('PKG_LIST_SELECTPER.vDataFin', TRUE),'') || ''',''DD.MM.YYYY'') ';
  ELSIF current_setting('PKG_LIST_SELECTPER.vLunaAnIni', TRUE) = current_setting('PKG_LIST_SELECTPER.vLunaAnFin', TRUE) THEN
    sInsert := coalesce(sInsert,'') || '
          AND (AN*12 + LUNA) = ' || coalesce(current_setting('PKG_LIST_SELECTPER.vLunaAnIni', TRUE)::NUMERIC, 0);
  ELSE
    sInsert := coalesce(sInsert,'') || '
          AND (AN*12 + LUNA) BETWEEN ' || coalesce(current_setting('PKG_LIST_SELECTPER.vLunaAnIni', TRUE)::NUMERIC, 0) || ' AND '
            || coalesce(current_setting('PKG_LIST_SELECTPER.vLunaAnFin', TRUE)::numeric, 0);
  END IF;
  sInsert := coalesce(sInsert,'') || '
        ) ies
        INNER JOIN livr    l  ON ies.codies    = l.codies
        INNER JOIN livr1   l1 ON l.codlivr     = l1.codlivr1
        INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC AND NS.TIPSERIE &gt; 0
        INNER JOIN NIR        ON NIR.CODNIR    = NS.CODNIR
      WHERE 1 = 1 ';
  IF current_setting('PKG_LIST_SELECTPER.vToateArt', TRUE)::NUMERIC = 0 THEN
    sInsert := coalesce(sInsert,'') || '
        AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' AND VALOARE = NS.CODOBIECT::varchar) ';
  END IF;
  IF current_setting('KG_LIST_SELECTPER.vToateGest', TRUE)::NUMERIC = 0 THEN
    sInsert := coalesce(sInsert,'') || '
      AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = NIR.GEST::varchar) ';
  END IF;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, 0, 0);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_miscari_setjoinuri</obj_name>
  <obj_hashval>54acd96c15acaa8467aefa806df9a7ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_miscari_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 06.08.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_MISCARI.gSuplCols', TRUE));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_modifpretdoc_baganircuserii</obj_name>
  <obj_hashval>b01638e32ecbfd4f511cc687a0c33328</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_modifpretdoc_baganircuserii()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Stef 12.05.2022 - curatenie PKG_LIST_BASE_UTILS CT_XXX
  DELETE FROM tmp_manevra_liste WHERE filtru = 'CODLIVR1';

  INSERT INTO tmp_manevra_liste(filtru, valoare)
  SELECT 'CODLIVR1', L1.CODLIVR1::varchar
  FROM   LIVR L INNER JOIN LIVR1 L1 ON  L1.CODLIVR = L.CODLIVR
  WHERE L.CODTRANSF = current_setting('PKG_LIST_BASE_MODIFPRETDOC.vCodDoc', true)::numeric;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_modifpretdoc_setparams</obj_name>
  <obj_hashval>60e0a6b3aa103921e703eda04d628f6c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_modifpretdoc_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 22 septembrie 2020
  perform set_config('PKG_LIST_BASE_MODIFPRETDOC.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_monetare_processlist</obj_name>
  <obj_hashval>92d4af129da25e114a6854112e30efa0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_monetare_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sSelect1    varchar;
  sSelect2    varchar;
  sCursRef    varchar;
  aSitV       numeric;
  aBancaV     numeric;
  aMonedaV    numeric;
  gSuplCols   varchar := 'nartobj nao, nart na, nclasea nca, num1 um, num um1, num um2, pretm p, ngest ng, ncont nc, nsubunit nsub';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  wmeRes      boolean;
BEGIN
  --Florin 12.06.2024 - sinc. Oracle
  --Florin 13.05.2024 - sin. Oracle
  --Florin 09.09.2021 - sinc. Orcale (07.09.2021)
  --Florin 16.06.2021 - sinron Oracle (30289)
  --Adina 05.04.2021 - alstart, alstop
  --Adina 11.02.2021 - add wmeRes + corectat PKG_LIST_BASE_UTILS_GETCURSREFERINTA in loc de PKG_LIST_BASE_UTILS.GETCURSREFERINTA
  --Florin 19.08.2020

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI'    , 'IES' , 'IES.CODIES     = I1.CODIES'    , 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI1'   , 'IES1', 'IES1.CODIES1   = I1.CODIES1'   , 1);
  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_monetare.gSuplCols', gSuplCols, false);

  PERFORM PKG_LIST_BASE_MONETARE_setFiltre(
    fnc_current_setting_boolint('PKG_LIST_SELINTIES.vToateArt'),
    fnc_current_setting_boolint('PKG_LIST_SELINTIES.vDupaData'),
    current_setting('PKG_LIST_SELINTIES.vPerioada', true)
  );

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

  IF wmeRes  --(SELECT pkg_list_base_utils_GetInfoSitValuta.WME_RESULT FROM pkg_list_base_utils_GetInfoSitValuta(NULL, aSitV, aBancaV, aMonedaV))
  THEN
    sCursRef := '(select wme_result from  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,' || coalesce(aMonedaV,0)::varchar || ',' || coalesce(aBancaV,0)::varchar || ', to_char(i1.datadoc,''dd.mm.yyyy'') ))';
  ELSE
    sCursRef := ' 1 ';
  END IF;
  sInsert := '
    INSERT INTO ' || tmpName || '(
      NAV_CodDoc, NAV_TipDoc, NRDOC, DATADOC, ART, UM, CANT, PRET, VAL, PJTVA,
      VALTVA, VALFARATVA,
      ADAOSUNIT, ADAOSTOT,
      OBSART, CodIntern, CodExtern, PuAchiz, PuMAX, PretV,
      GEST, DenCONT, SimbCONT, DenClasaA, SimbClasaA,
      UM1, UM2, CANT1, CANT2, SERII, GAR, TG, SUBUNITATEA, VALDISC, COMIS, CURS_REF ' || gUserFields || ')';
  sSelect1 := '
    WITH I1 AS (
      SELECT
        i.codies, i.tipdoc, i.nrdoc, i.datadoc, i.prefixdoc, coalesce(i.curs,1) curs, i.an, i.luna,  i.obs obsdoc, i.subunitatea,
        i1.indexlocal, i1.tiplinie, i1.codobiect, i1.umsec, i1.contserv, i1.obs obsart, i1.pu, coalesce(i1.tva,0) tvalin, i1.cant cantlin,
         (CASE WHEN i1.tiplinie=''='' then coalesce(lv.gest, n.gest) ELSE i1.gestact END) Gest,
        ROUND(CASE
          WHEN coalesce(i1.tva,0) = 0 THEN 0
          WHEN i1.pu * i1.cant = coalesce(i1.tva,0) THEN 0
          ELSE coalesce(i1.tva,0) / (i1.pu * i1.cant-coalesce(i1.tva,0))
        END,2) coef_tva,
        (Case  When i1.tiplinie=''='' then  SUM(l1.cant) else i1.cant end) cant,
        SUM(coalesce((Case When lv.codlivrval IS NULL then  ns.pret - ns.adaos else lv.pretachiz end) * l1.cant, 0)) valachiz,
        MAX(coalesce(ns.pumaximal, 0)) pumaximal, i1.garantie,
        CASE
          WHEN i1.tiplinie = ''='' THEN (SELECT io1.cont FROM IOART1 IO1 WHERE IO1.CODIOART = coalesce(lv.codioart,ns.codioart) AND (I.AN*12+I.LUNA) BETWEEN IO1.ALStart and IO1.ALStop )
          ELSE i1.contserv
        END CodCont,
        CASE coalesce(ns.tipserie,0)
          WHEN 1 THEN STRING_AGG(s.serie, '''')
          WHEN 2 THEN STRING_AGG(s.serie || ''(~#'' || l1.cant || ''#~)'', '''')
          ELSE NULL
        END SERII,
        STRING_AGG(coalesce(nser.tg, ns.tg)::varchar,'''') tg,
        SUM(l1.cantum1) cantum1, SUM(l1.cantum2) cantum2, i1.codies1, i1.valdiscpret,i1.CODPARTCOMISEMUL
      FROM iesiri i
        INNER 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' || COALESCE(current_setting('PKG_LIST_BASE_MONETARE.vFiltru', TRUE),'')
          || COALESCE(current_setting('PKG_LIST_BASE_MONETARE.vFiltruArt', true),'') || '
      GROUP BY
        i.codies, i.tipdoc, i.nrdoc, i.datadoc, i.prefixdoc, i.curs, i.an, i.luna, i.subunitatea, i.obs,
        i1.indexlocal, i1.tiplinie, i1.codobiect, i1.umsec, i1.tva, i1.pu, i1.cant,
        i1.garantie, i1.gestact, i1.contserv, i1.obs,i1.codies1,
        lv.codioart, lv.gest, ns.codioart, n.gest, ns.tipserie, i1.valdiscpret,i1.CODPARTCOMISEMUL)
    SELECT
      i1.codies, i1.tipdoc, i1.nrdoc, i1.datadoc, nao.denumire, um.den_um1, i1.cant/um.paritate, i1.pu*um.paritate, i1.pu * i1.cant, i1.coef_tva * 100,
      (Case When i1.cantlin = 0 then 0 When i1.cantlin = i1.cant then i1.tvalin else i1.tvalin * i1.cant / i1.cantlin end), i1.pu * i1.cant -
      (Case When i1.cantlin= 0 then 0 When i1.cantlin = i1.cant then i1.tvalin else i1.tvalin * i1.cant/i1.cantlin end),
      (Case  When i1.cant = 0 then 0 else (i1.pu * i1.cant - i1.tvalin - i1.valachiz) / i1.cant * um.paritate end), i1.pu * i1.cant - i1.tvalin - i1.valachiz,
      i1.obsart, nao.codintern, nao.codextern, (Case When i1.cant = 0 then 0 else i1.valachiz * um.paritate / i1.cant end), i1.pumaximal, p.lei,
      ng.den_gest, nc.den_cont, nc.simbol, nca.den_clasea, nca.simbol,
    um1.den_um, um2.den_um, i1.cantum1, i1.cantum2, i1.serii, i1.garantie, i1.tg, nsub.den_subunit, i1.VALDISCPRET,coms.den_part,'||COALESCE(sCursRef, '')||COALESCE(gUserAlias, '')||'
FROM I1
      LEFT JOIN NARTOBJ  NAO  ON nao.codobiect = i1.codobiect
      LEFT JOIN NART     NA   ON na.codarticol = nao.codarticol
      LEFT JOIN NCLASEA  NCA  ON nca.codclasea = na.clasa
      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 pretm    p    ON p.codobiect   = i1.codobiect AND p.implicit = 1 AND p.subunitatea = ' || coalesce(current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, 0) || '
      LEFT JOIN NGEST    NG   ON ng.codgest    = i1.gest
      LEFT JOIN NCONT    NC   ON nc.codcont  = i1.codcont
      LEFT JOIN NSUBUNIT NSUB ON nsub.codsubunit = i1.subunitatea
      LEFT JOIN npart coms    on coms.codpart   = i1.CODPARTCOMISEMUL '|| gSuplJoins;
  sSelect2 := '
    WITH I1 AS (
      SELECT
        i.codies, i.tipdoc, i.nrdoc, i.datadoc, i.contdiscount, i.subunitatea, i.moneda,
        0 CodObiect, 0 UmSec,
        (Case  When i1.tiplinie = ''='' then coalesce(lv.gest, n.gest) else i1.gestact end) gest,
        CASE WHEN i.valdoc = i.valdiscount THEN 0 ELSE i.valdiscount * SUM(I1.PU  * coalesce(L1.CANT, I1.CANT)) / (i.valdoc - i.valdiscount) END valdiscg,
        CASE WHEN i.tvadoc = i.tvadiscount THEN 0 ELSE i.tvadiscount * SUM(I1.TVA * coalesce(L1.CANT, I1.CANT) / I1.CANT) / (i.tvadoc - i.tvadiscount) END tvadiscg,
        i1.codies1, i1.CODPARTCOMISEMUL
      FROM iesiri i
        INNER 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 ' || COALESCE(current_setting('PKG_LIST_BASE_MONETARE.vFiltru', true),'') || '
        AND coalesce(I.VALDISCOUNT,0) &lt;&gt; 0 AND I1.CANT &lt;&gt; 0
        AND (COALESCE(N.GEST,LV.GEST) IN (SELECT CODGEST FROM TMP_GESTDEDICATE) OR I1.tiplinie = ''S'')
      GROUP BY i.codies, i.tipdoc, i.nrdoc, i.datadoc, i.valdiscount, i.tvadiscount, i.valdoc, i.tvadoc, i.contdiscount, i.subunitatea, i.moneda,
        (Case When i1.tiplinie = ''='' then coalesce(lv.gest, n.gest) else i1.gestact end),
               i1.codies1
      )
    SELECT
      I1.CODIES, I1.TIPDOC, I1.NRDOC, I1.DATADOC, ''Discount/Majorare'', M.SIMBOL, 1,
      I1.VALDISCG, I1.VALDISCG,
     (Case When I1.TVADISCG = 0 then 0 else I1.TVADISCG / (I1.VALDISCG - I1.TVADISCG) * 100 end),
      I1.TVADISCG, I1.VALDISCG - I1.TVADISCG ,
      0, 0,
      NULL, NULL, NULL, 0, 0, NULL,
      NG.DEN_GEST, NC.DEN_CONT, NC.SIMBOL, NULL, NULL,
      NULL, NULL, NULL, NULL, NULL, NULL, NULL, NSUB.DEN_SUBUNIT, 0, coms.den_part,'||COALESCE(sCursRef, '')||gUserAlias||'
    FROM I1
      LEFT JOIN NARTOBJ  NAO  ON nao.codobiect = i1.codobiect
      LEFT JOIN NART     NA   ON na.codarticol = nao.codarticol
      LEFT JOIN NCLASEA  NCA  ON nca.codclasea = na.clasa
      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 PRETM    P    ON p.codobiect   = i1.codobiect AND p.implicit = 1 AND p.subunitatea = ' || COALESCE(current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, 0) || '
      LEFT JOIN NGEST    NG   ON NG.CODGEST    = I1.GEST
      LEFT JOIN NCONT    NC   ON NC.CODCONT    = I1.CONTDISCOUNT
      LEFT JOIN NSUBUNIT NSUB ON NSUB.CODSUBUNIT = I1.SUBUNITATEA
      LEFT JOIN NMONEDE  M    ON M.CODMONEDA = I1.MONEDA
      LEFT JOIN npart coms    on coms.codpart   = i1.CODPARTCOMISEMUL '|| gSuplJoins;

  PERFORM LIST_EXECUTE_IMMEDIATE(COALESCE(sInsert,'') || COALESCE(sSelect1,''), aListID, aListVer);

  IF fnc_current_setting_boolint('PKG_LIST_SELINTIES.vToateArt') = 1 THEN
  PERFORM LIST_EXECUTE_IMMEDIATE(COALESCE(sInsert,'') || COALESCE(sSelect2,''), aListID, aListVer);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_monetare_setfiltre</obj_name>
  <obj_hashval>87f28d410dda9250257ded430c86742d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_monetare_setfiltre(ptoateart numeric, pdupadata numeric, sdata character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vFiltru    VARCHAR := '';
  vFiltruArt VARCHAR := '';
BEGIN
  --Florin 17.09.2024 - sinc. Oracle
  --Florin 12.06.2024 - sinc. Oracle
  --Florin 20.05.2024 - fixat 62011
  --Florin 29.07.2020

  vFiltru := '
    WHERE i.tipdoc = 16 AND i.operat = 1 AND i.anulat = 0 ';
  vFiltru := vFiltru ||  COALESCE((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL, 'I', NULL, NULL, NULL)), '') ;
  vFiltru := vFiltru || ' AND coalesce(i.initializari,0) = 0 ';
  if pDupaData then
    vFiltru := vFiltru || ' AND i.datadoc ' || sData|| ' ';
  else
    vFiltru := vFiltru || ' AND (i.luna + i.an * 12) ' || sData || ' ';
  end if;

  vFiltru := vFiltru||' AND (COALESCE(N.GEST,LV.GEST) IN (SELECT CODGEST FROM TMP_GESTDEDICATE) OR I1.tiplinie = ''S'' OR I1.tiplinie = ''V'')';
  IF pToateArt = 0 THEN
    vFiltruArt := ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' AND VALOARE = I1.CODOBIECT::varchar) ';
  END IF;

  PERFORM set_config('PKG_LIST_BASE_MONETARE.vFiltru'   , vFiltru   , false);
  PERFORM set_config('PKG_LIST_BASE_MONETARE.vFiltruArt', vFiltruArt, false);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_monetaremp_baga_dinamic_cols</obj_name>
  <obj_hashval>e3db2d0e39a4aa252a626fdca13df77b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_monetaremp_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 14.10.2022 - fixat 5590
  --Florin 28.07.2020
  DELETE FROM tmp_dinamic_cols;
  INSERT INTO tmp_dinamic_cols(FIELDNAME, DISPLAY)
  SELECT 'D' || row_number() OVER (ORDER BY Display) FIELDNAME, Display
  FROM (
    SELECT DISTINCT Coalesce(REPLACE(mp.denmodplata, ' ', ''), '...') DISPLAY
    FROM iesiri i INNER JOIN moduriplati mp ON  mp.codies = i.codies
    WHERE i.tipdoc = 16 AND mp.tipplata &lt;&gt; 0 AND COALESCE(mp.valoare, 0) &lt;&gt; 0
      AND i.an = getanlucru()
      AND i.luna BETWEEN current_setting('PKG_LIST_SELECTLUNA.vLunaStart', true)::numeric AND current_setting('PKG_LIST_SELECTLUNA.vLunaFin', true)::numeric
  ) A_PG;

    if current_setting('PKG_LIST_SELECTLUNA.vFixed', true) then
    INSERT INTO tmp_dinamic_cols (FIELDNAME, DISPLAY)
    SELECT 'C'||CODCARD, DENUMIRE
    FROM CARDURI
    WHERE CODCARD &gt; 0;
  end if;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_monetaremp_processlist</obj_name>
  <obj_hashval>df11eaa327a4ff5058568fc2ce2dde1a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_monetaremp_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC        RECORD;
  sInsert     varchar;
  sSelect     varchar;
  gSuplCols   varchar := 'iesiri i';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  v_rec       record;
BEGIN
  --Florin 21.11.2022 - fixat 56327
  --Florin 14.10.2022 - fixat 55909
  --Florin 05.10.2022 - sinc. Oracle
  --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_MONETAREMP.gSuplCols', gSuplCols, false);

  sInsert := '
    INSERT INTO ' || tmpName || '(
      NAV_CodDoc, NAV_TipDoc, NRDOC, DATADOC, VAL, Cash ';
  sSelect := '
    SELECT i.codies, i.tipdoc, i.nrdoc, i.datadoc, i.valdoc, SUM((Case When mp.tipplata = 0 then mp.valoare else 0 end))';
--  insert into x(view_name, test) values ('monrsel', coalesce(sSelect,''));
  FOR vRec IN (SELECT FIELDNAME, DISPLAY FROM tmp_dinamic_cols ORDER BY FIELDNAME) LOOP
    IF SUBSTR(VREC.FIELDNAME,1,1) = 'D' THEN
      sInsert := coalesce(sInsert,'') || ', ' || coalesce(vRec.FieldName,'');
      sSelect := coalesce(sSelect,'') || ', SUM(CASE WHEN Coalesce(REPLACE(mp.denmodplata,'' '',''''),''...'') = ''' || coalesce(vRec.Display,'') || '''
      THEN mp.valoare ELSE 0 END)';
    END IF;
  END LOOP;

 -- insert into x(view_name, test) values ('monrsel', coalesce(sSelect,''));
  sInsert := coalesce(sInsert,'') || gUserFields || ')';
  sSelect := coalesce(sSelect,'') || gUserAlias || '
    FROM iesiri i
      INNER JOIN moduriplati mp ON mp.codies = i.codies' || gSuplJoins || '
    WHERE i.tipdoc = 16
      AND i.an = ' || getanlucru() || '
      AND i.luna BETWEEN ' || current_setting('PKG_LIST_SELECTLUNA.vLunaStart', true) || ' AND ' ||
        current_setting('PKG_LIST_SELECTLUNA.vLunaFin', true) || ' ' ||
        coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL, 'I', NULL, NULL, NULL)), '') || '
    GROUP BY i.codies, i.tipdoc, i.nrdoc, i.datadoc, i.valdoc' || gUserAlias;
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);

  IF current_setting('PKG_LIST_SELECTLUNA.vFixed', true) then
    FOR V_REC IN (SELECT CODCARD FROM CARDURI WHERE CODCARD &gt; 0) LOOP
      EXECUTE 'UPDATE '||TMPNAME||' T SET C'||V_REC.CODCARD||' = (select M.valoare from modplata2 M where codies = T.NAV_CODDOC AND M.CODCARD = '||V_REC.CODCARD||')';
    END LOOP;
  end if;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_mpcd_processlist</obj_name>
  <obj_hashval>b11367d7e120653284af10256a2a1a20</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_mpcd_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
BEGIN
  --Adina 14.10.2020
  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
  CodPretM,
  DenObj,
  Den_CatPret,
  Den_UM,
  Rot,
  Lei,
  Valuta,
  PretNou,
  PretNouV)
  Select
    CodPretM,
    DenObj,
    Den_CatPret,
    Den_UM,
    Rot,
    Lei,
    Valuta,
    PretNou,
    PretNouV
  FROM tmp_lst_293';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_mpcd_setjoinuri</obj_name>
  <obj_hashval>56c9aeddbe5ba915b664d6b8f86a6645</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_mpcd_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.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_mpcp_processlist</obj_name>
  <obj_hashval>16f66cb25a3a05fd3cf2e99faeaabd58</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_mpcp_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
BEGIN
  --Adina 14.10.2020
  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
  CodPretM,
  DenObj,
  Den_CatPret,
  Den_UM,
  Rot,
  Lei,
  Valuta,
  PretNou,
  PretNouV)
  Select
    CodPretM,
    DenObj,
    Den_CatPret,
    Den_UM,
    Rot,
    Lei,
    Valuta,
    PretNou,
    PretNouV
  FROM tmp_lst_292';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_mpcp_setjoinuri</obj_name>
  <obj_hashval>e6fe0062ba446a63b7d72d2b75a4b93e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_mpcp_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.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_mpvd_processlist</obj_name>
  <obj_hashval>ba68820960c09669ebd95a9fad3c65eb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_mpvd_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar;
begin
  sInsert := 'INSERT INTO ' || TMPNAME || '(
    CodPretM,
    DenObj,
    Den_CatPret,
    Den_UM,
    Rot,
    PretReferinta,
    Lei,
    PAdaosLei,
    Valuta,
    PretNou,
    PAdaosNou,
    PretNouV)
    select
      CodPretM,
      DenObj,
      Den_CatPret,
      Den_UM,
      Rot,
      PretReferinta,
      Lei,
      PAdaosLei,
      Valuta,
      PretNou,
      PAdaosNou,
      PretNouV
    FROM tmp_lst_291';
  PERFORM LIST_EXECUTE_IMMEDIATE( sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_mpvp_processlist</obj_name>
  <obj_hashval>acda526434815e74ec3e46af2472c60a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_mpvp_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
BEGIN
  --Adina 14.10.2020
  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
  CodPretM,
  DenObj,
  Den_CatPret,
  Den_UM,
  Rot,
  PretReferinta,
  Lei,
  PAdaosLei,
  Valuta,
  PretNou,
  PAdaosNou,
  PretNouV)
  Select
    CodPretM,
    DenObj,
    Den_CatPret,
    Den_UM,
    Rot,
    PretReferinta,
    Lei,
    PAdaosLei,
    Valuta,
    PretNou,
    PAdaosNou,
    PretNouV
  FROM tmp_lst_290';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz1_setjoinuri</obj_name>
  <obj_hashval>0d30fbb561085add36dc021deef5841c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz1_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 27 august 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_NAPROVIZ1.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz1_setparams</obj_name>
  <obj_hashval>3e3c2033b1f2d1564b2e7dc7a68552b7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz1_setparams(ptoategest integer DEFAULT 1, ptoateioart integer DEFAULT 1, pdataini character varying DEFAULT NULL::character varying, pdatascad character varying DEFAULT NULL::character varying, psubcurenta integer DEFAULT 1, pextra1 integer DEFAULT 0, pextra2 integer DEFAULT 0, pcentralizat integer DEFAULT 0, pcodjob1 numeric DEFAULT 0, pcodproiect numeric DEFAULT 0, pcant numeric DEFAULT 1)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xALS INTEGER;
  xALF INTEGER;
  vDataIni date;
  vDataScad date;
  vToateGest bool;
  vSubCurenta bool;
BEGIN
  --Florin 18.12.2025 - fixat 67614
  --Florin 31.01.2024 - fixat 64584
  --Florin 27.01.2025 - fixat 64562
  --Florin 20.01.2024 - sinc. Oracle
  --Florin 17.01.2025 - sinc. Oracle
  --Florin 26.11.2024
  vToateGest    := Coalesce(pToateGest,  1) = 1;
  vSubCurenta   := Coalesce(pSubCurenta, 1) = 1;
  IF NVL(pCodJob1,0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1,vDataIni, vDataScad, xALS,xALF);
  END IF;
  if vSubCurenta then
    if vToateGest then
      delete FROM tmp_manevra_liste where filtru = 'CODGEST';
      insert into tmp_manevra_liste(filtru, valoare)
      select 'CODGEST', G.CodGest
      from tmp_subunitdedicate t
           inner join ngest g on g.codsubunit = t.codsubunit
      where GETSUBUNITATE() = 1 or t.codsubunit = GETSUBUNITATE();
    else
      delete FROM tmp_manevra_liste t
      where filtru = 'CODGEST'
            and not exists (select ts.valoare from tmp_manevra_liste ts, ngest g where ts.valoare = g.codsubunit::varchar and tS.filtru = 'CODSUBUNIT' and t.valoare = g.codgest::varchar);
    end if;
  else
    if vToateGest then
      delete FROM tmp_manevra_liste where filtru = 'CODGEST';
      insert into tmp_manevra_liste(filtru, valoare)
      select 'CODGEST', G.CodGest
      from tmp_subunitdedicate t
           inner join ngest g on g.codsubunit = t.codsubunit
           inner join tmp_gestdedicate tg on tg.codgest = g.codgest
         where exists (select ts.valoare from tmp_manevra_liste ts where ts.valoare = g.codsubunit::varchar and tS.filtru = 'CODSUBUNIT');
    else
      delete FROM tmp_manevra_liste t
      where filtru = 'CODGEST'
            and not exists (select ts.valoare from tmp_manevra_liste ts, ngest g where ts.valoare = g.codsubunit::varchar and tS.filtru = 'CODSUBUNIT' and t.valoare = g.codgest::varchar);
    end if;
  end if;
  perform set_config('pkg_list_base_naproviz1.vToateGest'  , to_char(Coalesce(pToateGest,  1) = 1), FALSE);
  perform set_config('pkg_list_base_naproviz1.vToateIoart' , to_char(Coalesce(pToateIoart, 1) = 1), FALSE);
  perform set_config('pkg_list_base_naproviz1.vDataIni'    , pDataIni::varchar                    , FALSE);
  perform set_config('pkg_list_base_naproviz1.vDataScad'   , pDataScad::varchar                   , FALSE);
  perform set_config('pkg_list_base_naproviz1.vSubCurenta' , to_char(Coalesce(pSubCurenta, 1) = 1), FALSE);
  perform set_config('pkg_list_base_naproviz1.vExtra1'     , to_char(Coalesce(pExtra1, 1) = 1)    , FALSE);
  perform set_config('pkg_list_base_naproviz1.vExtra2'     , to_char(Coalesce(pExtra2, 1) = 1)    , FALSE);
  perform set_config('pkg_list_base_naproviz1.vCentralizat', pCentralizat::varchar                , FALSE);
  perform set_config('pkg_list_base_naproviz1.vCodProiect' , Coalesce(pCodProiect, 1)::varchar, FALSE);
  perform set_config('pkg_list_base_naproviz1.vCant'       , pCant::varchar                       , FALSE);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz2_calculeazazilestoc</obj_name>
  <obj_hashval>476d7a9ce71db19c04caddf81c223c98</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz2_calculeazazilestoc(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_OBJ      RECORD;
  aCount      numeric;
  aZi        date;
  StocP      numeric;
  Intrari    numeric;
  Iesiri      numeric;
  vSel        varchar := '';
  vAux        varchar := '';
  vCateGest  numeric;
  vCateLGest numeric;
BEGIN
  --Adina 10.12.2020 tichet 41539
  --Adina 28 august 2020
  FOR v_obj IN (SELECT o.codobiect
                FROM  nartobj o
                      INNER JOIN nart a ON  a.codarticol = o.codarticol
                WHERE a.tiparticol = '0'
               )
  LOOP
    aCount := 0;
    aZi    := to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', true)::varchar,'dd.mm.yyyy');

    WHILE  aZi &lt;= to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', true)::varchar,'dd.mm.yyyy') LOOP
      IF  aZi = to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', true)::varchar,'dd.mm.yyyy') THEN
        BEGIN
          SELECT COALESCE(cant, 0) INTO STRICT StocP
          FROM tmp_stocreal WHERE codobiect = v_obj.codobiect and  tip = 'INIT';
        EXCEPTION
          WHEN NO_DATA_FOUND THEN StocP := 0;
          WHEN others THEN
            StocP := 0;
        END;
      END IF;

      vSel :=
      'SELECT
         SUM(CASE
           WHEN coalesce(NSE.CODNIRSER, 0) = 0 THEN NS.CANTNIR
           ELSE NSE.CANTNIR
         END)
       FROM
         NIRSTOC NS
         INNER JOIN NIR    N   ON N.CODNIR      = NS.CODNIR
         INNER JOIN NGEST  G   ON G.CODGEST     = N.GEST
         LEFT  JOIN NIRSER NSE ON NS.CODNIRSTOC = NSE.CODNIRSTOC
       WHERE
         N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 12, 15) AND  N.ANULAT = 0 AND N.OPERAT = 1
         AND N.DATANIR = to_date(''' || coalesce(to_char(aZi, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')
         AND (GETSUBUNITATE() = 1 OR G.CODSUBUNIT = GETSUBUNITATE())
         AND NS.CODOBIECT = ' || coalesce(V_OBJ.CODOBIECT::varchar ,'');

      IF  NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', true)::boolean 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';
        vAux := '
          AND';

        IF  vCateLGest = 0 THEN
          vAux := vAux || ' N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
        ELSIF vCateGest = 0 THEN
          vAux := vAux || ' NS.CODLOCATIE::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'') ';
        ELSE
          vAux := vAux || ' (N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') OR NS.CODLOCATIE::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'')) ';
        END IF;

        vSel := vSel || vAux;
      END IF;

      IF  NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateIOArt', true)::boolean THEN
        vAux := '
          AND NS.CODIOART::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
        vSel := vSel || vAux;
      END IF;

      BEGIN
        EXECUTE vSel INTO Intrari;
      EXCEPTION WHEN others THEN
        Intrari := 0;
      END;

      IF Intrari IS NULL THEN
        Intrari := 0;
      END IF;

      vSel :=
      'SELECT
         sum(CASE WHEN L.TIPLIVR = 15 THEN -L1.CANT ELSE L1.CANT END)
       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 N.CODNIR      = NS.CODNIR
         INNER JOIN NGEST   G  ON G.CODGEST     = N.GEST
         LEFT  JOIN NIRSER  NE ON L1.CODNIRSER  = NE.CODNIRSER
       WHERE
         L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7, 14, 15 ,16, 19, 20, 21, 23, 24) AND L.OPERAT = 1 AND L.ANULAT = 0 AND
         L.DATALIVR = to_date(''' || coalesce(to_char(aZi, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')
         AND (GETSUBUNITATE() = 1 OR G.CODSUBUNIT = GETSUBUNITATE())
         AND NS.CODOBIECT = ' || coalesce(V_OBJ.CODOBIECT::varchar ,'');

      vSel := vSel || vAux;

      BEGIN
        EXECUTE vSel INTO Iesiri;
      EXCEPTION WHEN others THEN
        Iesiri := 0;
      END;

      IF Iesiri IS NULL THEN
        Iesiri := 0;
      END IF;

      IF  Intrari &gt; 0 THEN
        aCount := aCount + 1;
      ELSE
        IF  Iesiri &gt; 0 THEN
          aCount := aCount + 1;
        ELSE
          IF  StocP &gt; 0 THEN
            aCount := aCount + 1;
          END IF;
        END IF;
      END IF;

      StocP := StocP + Intrari - Iesiri;
      aZi := aZi + 1;
    END LOOP;
    EXECUTE 'update ' || tmpName || ' set nrzile = ' || coalesce(aCount::varchar,'') || ' where codobiect = ' || coalesce(v_obj.codobiect::varchar ,'');
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz2_getallgest</obj_name>
  <obj_hashval>4f89b5b3a91c73359e9d417b0f0ac714</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz2_getallgest()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 28 august 2020
  IF current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', true)::boolean THEN
    RETURN  1;
  ELSE
    RETURN  0;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz2_getallioart</obj_name>
  <obj_hashval>d7a65653dc740802b932c2f6eee79b42</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz2_getallioart()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 28 august 2020
  IF current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateIoart', true)::boolean THEN
    RETURN  1;
  ELSE
    RETURN  0;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz2_getcutermen</obj_name>
  <obj_hashval>1190a46294fc717cd530f3f3101e71a8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz2_getcutermen()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 28 august 2020
  IF current_setting('PKG_LIST_BASE_NAPROVIZ2.vCuTermen', true)::boolean THEN
    RETURN  1;
  ELSE
    RETURN  0;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz2_getpezile</obj_name>
  <obj_hashval>d6ea34a6796af41490a8ee2325c9c63e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz2_getpezile()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 28 august 2020
  IF current_setting('PKG_LIST_BASE_NAPROVIZ2.vPeZile', true)::boolean THEN
    RETURN  1;
  ELSE
    RETURN  0;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz2_setjoinuri</obj_name>
  <obj_hashval>ab6dae85b2e4df69b3c41d4fb3705f28</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz2_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 28 august 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_NAPROVIZ2.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz2_setparams</obj_name>
  <obj_hashval>f6d27b6440244378baeda923e5769d6a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz2_setparams(ptoategest numeric DEFAULT 1, ptoateioart numeric DEFAULT 1, pdatacini character varying DEFAULT NULL::character varying, pdatacfin character varying DEFAULT NULL::character varying, ptipvanz character varying DEFAULT NULL::character varying, ppervanz numeric DEFAULT 0, pdatavini character varying DEFAULT NULL::character varying, pdatavfin character varying DEFAULT NULL::character varying, pultachiz numeric DEFAULT 0, pcutermen numeric DEFAULT 0, ptermen character varying DEFAULT NULL::character varying, ppezile numeric DEFAULT 0, pnrzile numeric DEFAULT 0, pafectare numeric DEFAULT 0, pclasa numeric DEFAULT 0, pclasas numeric DEFAULT 0, pprod numeric DEFAULT 0, pzilestoc numeric DEFAULT 0, v_codjob1 numeric DEFAULT 0, ppeluni numeric DEFAULT 0, prestcmd numeric DEFAULT 0, pdim numeric DEFAULT 0, pvanzemul numeric DEFAULT 0, pclasaw numeric DEFAULT 0, pcucomenzi numeric DEFAULT 1, pcuartfaravanz numeric DEFAULT 1, pdefalcat numeric DEFAULT 0, pallcls numeric DEFAULT 0, pstocurigest numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
BEGIN
  --Florin 18.02.2025 - fixat 64791
  --Florin 04.02.2024 - sinc. Oracle
  --Florin 04.05.2023 - sinc. Oracle (03.05.2023)
  --Adina 28 august 2020
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vAllCls' ,( COALESCE(pAllCls,1) = 1)::varchar ,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vToateGest' ,( COALESCE(pToateGest,1) = 1)::varchar ,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vToateIoart',( COALESCE(pToateIoart,1) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vDefalcare',( COALESCE(pDefalcat,1) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vZiuaIniC'  ,COALESCE(pDataCIni,'') ,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vZiuaFinC'  ,COALESCE(pDataCFin,'') ,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vTipVanz'   ,(COALESCE(pTipVanz,'')),false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vStocuriGest',(COALESCE(pStocuriGest, 1) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vAnLucru'   ,(getANLUCRU())::varchar,false);

  IF  COALESCE(pPerVanz,0) = 1 THEN
    perform set_config('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni',COALESCE(pDataVIni,''),false);
    perform set_config('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin',COALESCE(pDataVFin,''),false);
  ELSE
    perform set_config('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni',('01.' || coalesce(to_char(extract( month FROM to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIniC', true),'dd.mm.yyyy')), '00'),'') || '.' || coalesce(current_setting('PKG_LIST_BASE_NAPROVIZ2.vAnLucru', true)::numeric,0)),false);
    perform set_config('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin',to_char(Last_Day(to_date('01.' || coalesce(to_char(extract( month FROM to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFinC', true),'dd.mm.yyyy')), '00'),'') || '.' || coalesce(current_setting('PKG_LIST_BASE_NAPROVIZ2.vAnLucru', true)::numeric,0), 'DD.MM.YYYY')),'dd.mm.yyyy'),false);
  END IF;

  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vUltAchiz',( COALESCE(pUltAchiz,0) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vCuTermen',( COALESCE(pCuTermen,0) = 1)::varchar,false);

  BEGIN
    perform set_config('PKG_LIST_BASE_NAPROVIZ2.vTermen',COALESCE(pTermen,''),false);
  EXCEPTION WHEN OTHERS THEN
    perform set_config('PKG_LIST_BASE_NAPROVIZ2.vTermen','',false);
  END;

  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vPeZile'  ,( COALESCE(pPeZile,0) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vNrZile'  ,COALESCE(pNrZile,0)::varchar       ,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vAfectare',COALESCE(pAfectare,0)::varchar     ,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vClasa'   ,COALESCE(pClasa,0)::varchar        ,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vClasaS'  ,COALESCE(pClasaS,0)::varchar       ,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vClasaW'  ,COALESCE(pClasaW,0)::varchar       ,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vProd'    ,COALESCE(pProd,0)::varchar         ,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vZileStoc',COALESCE(pZileStoc,0)::varchar     ,false);

  IF  COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni' , true), current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin' , true), xLunaAnIni, xLunaAnFin);
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIniC', true), current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFinC', true), xLunaAnIni, xLunaAnFin);
    PERFORM PKG_ORA_LISTS_SET_DATA_DINAMIC(V_CODJOB1, to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vTermen', true),'dd.mm.yyyy'));
  END IF;

  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vPeLuni'       ,(COALESCE(pPeLuni,0) = 1)::varchar  ,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vRestCmd'      ,(COALESCE(pRestCmd,0) = 1)::varchar ,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vDim'          ,(COALESCE(pDim,0) = 1)::varchar     ,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vVanzEmul'     ,(COALESCE(pVanzEmul,0) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vCuComenzi'    ,(COALESCE(pCuComenzi,1) = 1)::varchar     ,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ2.vCuArtFaraVanz',COALESCE(pCuArtFaraVanz,1)::varchar ,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz5_makecomenzi</obj_name>
  <obj_hashval>ae88a3142731d8c7a3c55c6e209f6dc8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz5_makecomenzi()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnLucru      NUMERIC := current_setting('PKG_LIST_BASE_NAPROVIZ5.vAnLucru'    , true)::NUMERIC;
  vUserID      NUMERIC := current_setting('PKG_LIST_BASE_NAPROVIZ5.vUserID'     , true)::NUMERIC;
  vSubunitatea NUMERIC := current_setting('PKG_LIST_BASE_NAPROVIZ5.vSubunitatea', true)::NUMERIC;
BEGIN
  --Adina 11.12.2020 - tuning - un singur for pt insert si fara update
  --Adina 02 septembrie 2020

--  for vLuna in 1..12 loop
--    insert into tmp_stocreal_nec5(codobiect, tip, userid)
--    select tmp.valoare::numeric, 'COM'||vLuna::varchar tip, vuserid
--    from tmp_manevra_liste tmp where tmp.filtru = 'CODOBIECT';
--  end loop;
--
--  for vLuna in 1..12 loop
--    update tmp_stocreal_nec5 tmp set
--      cant =
--            ( select coalesce(sum(c1.restacceptat),0)
--              from comanda1 c1
--                   inner join comanda c on c.codcomanda = c1.codcomanda
--              where c.tipdoc = 8 and c.anulat = 0 and c.operat = 1 and extract(year from c1.termen) * 12 + extract(month from c1.termen) = vAnLucru * 12 + vLuna
--                and c1.codobiect = tmp.codobiect and (vSubunitatea = 1 or vSubunitatea = c.subunitatea)
--            )
--    where tmp.tip = 'COM'||vLuna::varchar and userid = vuserid;
--  end loop;

  for vLuna in 1..12 loop
    insert into tmp_stocreal_nec5(codobiect, tip, userid, cant)
    select tmp.valoare::numeric, 'COM'||vLuna::varchar tip, vuserid, coalesce(b.cant,0)
    from tmp_manevra_liste tmp
         LEFT JOIN ( select c1.codobiect, coalesce(sum(c1.restacceptat),0) cant
                     from comanda1 c1
                           inner join comanda c on c.codcomanda = c1.codcomanda
                     where c.tipdoc = 8 and c.anulat = 0 and c.operat = 1 and extract(year from c1.termen) * 12 + extract(month from c1.termen) = vAnLucru * 12 + vLuna
                           and (vSubunitatea = 1 or vSubunitatea = c.subunitatea)
                     group by c1.codobiect
                   ) b ON tmp.valoare::numeric = b.codobiect
    where tmp.filtru = 'CODOBIECT';
  end loop;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz5_makeconsumuri</obj_name>
  <obj_hashval>93f69dce97b2732a0b6e7748deb2e23b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz5_makeconsumuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnLucru      NUMERIC := current_setting('PKG_LIST_BASE_NAPROVIZ5.vAnLucru'    , true)::NUMERIC;
  v_flgArt      NUMERIC := CASE WHEN current_setting('PKG_LIST_SELFISAMAG.p_flgArt',true)::boolean THEN 1 ELSE 0 END ;
  vUserID      NUMERIC := current_setting('PKG_LIST_BASE_NAPROVIZ5.vUserID'     , true)::NUMERIC;
  vSubunitatea NUMERIC := current_setting('PKG_LIST_BASE_NAPROVIZ5.vSubunitatea', true)::NUMERIC;
BEGIN
  --Adina 11.12.2020 - tuning - un singur for pt insert si fara update
  --Adina 02 septembrie 2020

--  for vLuna in 1..12 loop
--    insert into tmp_stocreal_nec5(codobiect, tip, userid)
--    select tmp.valoare::numeric, 'C'||vLuna::varchar, vuserid
--    from tmp_manevra_liste tmp where tmp.filtru = 'CODOBIECT';
--  end loop;
--
--  for vLuna in 1..12 loop
--    update tmp_stocreal_nec5 tmp set
--      cant =
--            (select coalesce(sum(cant),0)
--             from (
--                    select mat.codobiect, mat.rest cant, 'C'||vLuna::varchar tip
--                    from cmdprodmat mat
--                         inner join comanda1 c1 on c1.codcomanda1 = mat.codcomanda1
--                         inner join comanda c on c.codcomanda = c1.codcomanda
--                    where c.anulat = 0 and c.operat = 1 and extract(year from c1.termen) * 12 + extract(month from c1.termen) = vAnLucru * 12 + vLuna
--                      and (v_flgArt = 1 or exists (select valoare from tmp_manevra_liste where filtru = 'CODOBIECT' and COALESCE(valoare,'') = COALESCE(mat.CODOBIECT::varchar,'') ))
--                      and (vSubunitatea = 1 or vSubunitatea = c.subunitatea) and mat.tip = 1
--                    UNION ALL
--                    select pn.codobiect, (c1.cantacceptat-coalesce(lansari.cant,0)) / pn0.cant * pn.cant cant, 'C'||vLuna::varchar tip
--                    from proiectnod pn
--                         inner join proiectnod pn0 on pn.codproiect = pn0.codproiect and pn0.nodoriginal = 0
--                         inner join comanda1 c1 on c1.codproiect = pn.codproiect
--                         inner join comanda c on c.codcomanda = c1.codcomanda
--                         left join (select sum(cant) cant, cmdlink.codliniecomanda codcomanda1, c1.codobiect
--                                    from cmdlink
--                                         inner join comanda1 c1 on c1.codcomanda1 = cmdlink.codcomanda1
--                                    group by cmdlink.codliniecomanda, c1.codobiect
--                                    ) lansari on lansari.codcomanda1 = c1.codcomanda1 and lansari.codobiect = c1.codobiect
--                    where c.tipdoc = 18 and c.anulat = 0 and c.operat = 1 and extract(year from c1.termen) * 12 + extract(month from c1.termen) = vAnLucru * 12 + vLuna
--                      and (v_flgArt = 1 or exists (select valoare from tmp_manevra_liste where filtru = 'CODOBIECT' and COALESCE(valoare,'') = COALESCE(pn.CODOBIECT::varchar,'') ))
--                      and (vSubunitatea = 1 or vSubunitatea = c.subunitatea)
--                  ) A_PG
--             where codobiect = tmp.codobiect)
--    where tmp.tip = 'C'||vLuna::varchar and userid = vuserid;
--  end loop;

  for vLuna in 1..12 loop
    insert into tmp_stocreal_nec5(codobiect, tip, userid, cant)
    select tmp.valoare::numeric, 'C'||vLuna::varchar, vuserid, COALESCE(b.cant,0)
    from tmp_manevra_liste tmp
         LEFT JOIN ( select codobiect, coalesce(sum(cant),0) cant
                     from (
                            select mat.codobiect, mat.rest cant, 'C'||vLuna::varchar tip
                            from cmdprodmat mat
                                 inner join comanda1 c1 on c1.codcomanda1 = mat.codcomanda1
                                 inner join comanda  c  on c.codcomanda   = c1.codcomanda
                            where c.anulat = 0 and c.operat = 1 and extract(year from c1.termen) * 12 + extract(month from c1.termen) = vAnLucru * 12 + vLuna
                              and (v_flgArt = 1 or exists (select valoare from tmp_manevra_liste where filtru = 'CODOBIECT' and COALESCE(valoare,'') = COALESCE(mat.CODOBIECT::varchar,'') ))
                              and (vSubunitatea = 1 or vSubunitatea = c.subunitatea) and mat.tip = 1
                            UNION ALL
                            select pn.codobiect, (c1.cantacceptat-coalesce(lansari.cant,0)) / pn0.cant * pn.cant cant, 'C'||vLuna::varchar tip
                            from proiectnod pn
                                 inner join proiectnod pn0 on pn.codproiect = pn0.codproiect and pn0.nodoriginal = 0
                                 inner join comanda1   c1  on c1.codproiect = pn.codproiect
                                 inner join comanda    c   on c.codcomanda  = c1.codcomanda
                                 left join (select sum(cant) cant, cmdlink.codliniecomanda codcomanda1, c1.codobiect
                                            from cmdlink
                                                 inner join comanda1 c1 on c1.codcomanda1 = cmdlink.codcomanda1
                                            group by cmdlink.codliniecomanda, c1.codobiect
                                            ) lansari on lansari.codcomanda1 = c1.codcomanda1 and lansari.codobiect = c1.codobiect
                            where c.tipdoc = 18 and c.anulat = 0 and c.operat = 1 and extract(year from c1.termen) * 12 + extract(month from c1.termen) = vAnLucru * 12 + vLuna
                              and (v_flgArt = 1 or exists (select valoare from tmp_manevra_liste where filtru = 'CODOBIECT' and COALESCE(valoare,'') = COALESCE(pn.CODOBIECT::varchar,'') ))
                              and (vSubunitatea = 1 or vSubunitatea = c.subunitatea)
                          ) A_PG
                     GROUP BY codobiect
                   ) b ON tmp.valoare::numeric = b.codobiect
    where tmp.filtru = 'CODOBIECT';
  end loop;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz5_makeiesiri</obj_name>
  <obj_hashval>282fb5dcd2d3906f15949a0dc8abb95b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz5_makeiesiri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnLucru      NUMERIC := current_setting('PKG_LIST_BASE_NAPROVIZ5.vAnLucru'    , true)::NUMERIC;
  vUserID      NUMERIC := current_setting('PKG_LIST_BASE_NAPROVIZ5.vUserID'     , true)::NUMERIC;
  vSubunitatea NUMERIC := current_setting('PKG_LIST_BASE_NAPROVIZ5.vSubunitatea', true)::NUMERIC;
BEGIN
  --Adina 11.12.2020 - tuning - un singur for pt insert si fara update
  --Adina 01 septembrie 2020

--  for vLuna in 1..12 loop
--    insert into tmp_stocreal_nec5(codobiect, tip, userid)
--    select valoare::numeric, 'IES'||vLuna::varchar, vuserid
--    from tmp_manevra_liste
--    where filtru = 'CODOBIECT';
--
--    insert into tmp_stocreal_nec5(codobiect, tip, userid)
--    select valoare::numeric, 'IES'||vLuna::varchar||'P', vuserid
--    from tmp_manevra_liste
--    where filtru = 'CODOBIECT';
--  end loop;

--  for vLuna in 1..12 loop
--    update tmp_stocreal_nec5 tmp set
--      cant =
--            ( select coalesce(sum(i1.cant),0)
--              from iesiri1 i1
--                   inner join tmp_manevra_liste tmpl on tmpl.valoare = i1.codobiect::varchar and tmpl.filtru = 'CODOBIECT'
--                   inner join iesiri i on i.codies = i1.codies
--              where coalesce(i.anulat, 0) = 0 and i.operat = 1 and i.an * 12 + i.luna = vAnLucru * 12 + vLuna
--                and tmp.codobiect = i1.codobiect and (vSubunitatea = 1 or vSubunitatea = i.subunitatea)
--            )
--    where tmp.tip = 'IES'||vLuna::varchar and userid = vuserid;
--
--    update tmp_stocreal_nec5 tmp set
--      cant =
--            ( select coalesce(sum(i1.cant),0)
--              from iesiri1 i1
--                   inner join tmp_manevra_liste tmpl on tmpl.valoare = i1.codobiect::varchar and tmpl.filtru = 'CODOBIECT'
--                   inner join iesiri i on i.codies = i1.codies
--              where coalesce(i.anulat, 0) = 0 and i.operat = 1 and i.an * 12 + i.luna = (vAnLucru - 1) * 12 + vLuna
--                and tmp.codobiect = i1.codobiect  and (vSubunitatea = 1 or vSubunitatea = i.subunitatea))
--    where tmp.tip = 'IES'||vLuna::varchar||'P' and userid = vuserid;
--  end loop;

  for vLuna in 1..12 loop
    insert into tmp_stocreal_nec5(codobiect, tip, userid,cant)
    select a.valoare::numeric, c.camp, vuserid, COALESCE(b.cant,0)
    from tmp_manevra_liste a
         CROSS JOIN (SELECT 'IES'||vLuna::varchar camp UNION SELECT 'IES'||vLuna::varchar||'P' camp) c
         LEFT  JOIN (select i1.codobiect, coalesce(sum(i1.cant),0) cant
                     from iesiri1 i1
                          inner join tmp_manevra_liste tmpl on tmpl.valoare = i1.codobiect::varchar and tmpl.filtru = 'CODOBIECT'
                          inner join iesiri            i    on i.codies     = i1.codies
                     where coalesce(i.anulat, 0) = 0 and i.operat = 1 and i.an * 12 + i.luna = vAnLucru * 12 + vLuna
                           and (vSubunitatea = 1 or vSubunitatea = i.subunitatea)
                     group by i1.codobiect
                    ) b ON a.valoare::numeric = b.codobiect
    where a.filtru = 'CODOBIECT' ;
  end loop;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz5_makestocuri</obj_name>
  <obj_hashval>4531cf3a45deab0a1f2e41a59689bcf2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz5_makestocuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  anlunamax    NUMERIC;
  vAnLucru      NUMERIC := current_setting('PKG_LIST_BASE_NAPROVIZ5.vAnLucru'       , true)::NUMERIC;
  v_flggest    NUMERIC := CASE WHEN current_setting('PKG_LIST_SELFISAMAG.p_flgGest', true)::boolean THEN 1 ELSE 0 END ;
  vUserID      NUMERIC := current_setting('PKG_LIST_BASE_NAPROVIZ5.vUserID'        , true)::NUMERIC;
  vSubunitatea NUMERIC := current_setting('PKG_LIST_BASE_NAPROVIZ5.vSubunitatea'   , true)::NUMERIC;
BEGIN
  --Adina 05.04.2021 - alstart,alstop
  --Adina 11.12.2020 - tuning- un singur for pt.insert si fara update
  --Adina 01 septembrie 2020

--  for vLuna in 1..12 loop
--    insert into tmp_stocreal_nec5(codobiect, tip, userid)
--    select valoare::numeric, 'S'||vLuna::varchar, vuserid
--    from tmp_manevra_liste
--    where filtru = 'CODOBIECT';
--  end loop;

  SELECT anmaxim * 12 + lunamaxima INTO anlunamax FROM FirmaLuni;

--  for vLuna in 1..12 loop
--    if vLuna &lt; anlunamax then
--      UPDATE tmp_stocreal_nec5 tmp SET cant =
--      (  SELECT coalesce(sum(NL.REST),0)
--        FROM
--          NIRLUNA NL,
--          NIRSTOC NS,
--          NIR N,
--          NGEST G,
--          IOART1 IO1
--        WHERE
--          NS.CODNIR = N.CODNIR
--          AND N.GEST = G.CODGEST
--          AND NL.AN = vAnLucru
--          AND NL.LUNA = vLuna
--          AND coalesce(NL.REST, 0) + coalesce(NL.RESTUM1, 0) + coalesce(NL.RESTUM2, 0) &lt;&gt; 0
--          AND NL.CODNIRSTOC = NS.CODNIRSTOC
--          AND NS.CODIOART = IO1.CODIOART
--          AND IO1.MG &lt;&gt; 5
--          and (v_flggest = 1 or exists (select valoare from tmp_manevra_liste where filtru = 'CODGEST' and COALESCE(valoare,'') = COALESCE(N.GEST::varchar,'')))
--          and tmp.codobiect = ns.codobiect
--          and (vSubunitatea = 1 or vSubunitatea = G.CODSUBUNIT)
--          and IO1.ANSTART * 12 + IO1.LUNASTART =
--             (  SELECT MAX(IO2.ANSTART * 12 + IO2.LUNASTART) FROM IOART1 IO2
--              WHERE IO2.CODIOART = IO1.CODIOART AND IO2.ANSTART * 12 + IO2.LUNASTART &lt;= vAnLucru*12+vLuna
--            )
--          and tmp.codobiect = ns.codobiect
--      )
--      WHERE 'S'||vLuna::varchar = tmp.tip and userid = vuserid;
--    elsif vLuna = anlunamax  then
--      UPDATE tmp_stocreal_nec5 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) + coalesce(NS.RESTUM1, 0) + coalesce(NS.RESTUM2, 0) &lt;&gt; 0
--          AND NS.CODIOART = IO1.CODIOART
--          AND IO1.MG &lt;&gt; 5
--          and (v_flggest = 1 or exists (select valoare from tmp_manevra_liste where filtru = 'CODGEST' and COALESCE(valoare,'') = COALESCE(N.GEST::varchar,'')))
--          and tmp.codobiect = ns.codobiect
--          and (vSubunitatea = 1 or vSubunitatea = G.CODSUBUNIT)
--          and IO1.ANSTART * 12 + IO1.LUNASTART =
--             ( SELECT MAX(IO2.ANSTART * 12 + IO2.LUNASTART) FROM IOART1 IO2
--              WHERE IO2.CODIOART = IO1.CODIOART AND IO2.ANSTART * 12 + IO2.LUNASTART &lt;= vAnLucru*12+vLuna
--            )
--          and tmp.codobiect = ns.codobiect
--      )
--      WHERE 'S'||vLuna::varchar = tmp.tip and userid = vuserid;
--    end if;
--  end loop;

  for vLuna in 1..12 LOOP
    IF vLuna &lt; anlunamax THEN
      insert into tmp_stocreal_nec5(codobiect, tip, userid,cant)
      select valoare::numeric, 'S'||vLuna::varchar, vuserid, COALESCE(b.cant,0)
      from tmp_manevra_liste a
           LEFT JOIN (  SELECT ns.codobiect, coalesce(sum(NL.REST),0) cant
                        FROM
                          NIRLUNA NL,
                          NIRSTOC NS,
                          NIR N,
                          NGEST G,
                          IOART1 IO1
                        WHERE
                          NS.CODNIR = N.CODNIR
                          AND N.GEST = G.CODGEST
                          AND NL.AN = vAnLucru
                          AND NL.LUNA = vLuna
                          AND coalesce(NL.REST, 0) + coalesce(NL.RESTUM1, 0) + coalesce(NL.RESTUM2, 0) &lt;&gt; 0
                          AND NL.CODNIRSTOC = NS.CODNIRSTOC
                          AND NS.CODIOART = IO1.CODIOART
                          AND IO1.MG &lt;&gt; 5
                          and (v_flggest = 1 or exists (select valoare from tmp_manevra_liste where filtru = 'CODGEST' and COALESCE(valoare,'') = COALESCE(N.GEST::varchar,'')))
                          and (vSubunitatea = 1 or vSubunitatea = G.CODSUBUNIT)
                          AND (vAnLucru*12+vLuna) BETWEEN IO1.ALStart and IO1.ALStop
                          GROUP BY ns.codobiect
                      ) b ON a.valoare::numeric = b.codobiect
      where a.filtru = 'CODOBIECT';
    ELSIF vLuna = anlunamax  then
      insert into tmp_stocreal_nec5(codobiect, tip, userid,cant)
      select valoare::numeric, 'S'||vLuna::varchar, vuserid, COALESCE(b.cant,0)
      from tmp_manevra_liste a
           LEFT JOIN       (SELECT ns.codobiect, coalesce(sum(NS.REST),0) cant
                            FROM
                              NIRSTOC NS,
                              NIR N,
                              NGEST G,
                              IOART1 IO1
                            WHERE
                              NS.CODNIR = N.CODNIR
                              AND N.GEST = G.CODGEST
                              AND coalesce(NS.REST, 0) + coalesce(NS.RESTUM1, 0) + coalesce(NS.RESTUM2, 0) &lt;&gt; 0
                              AND NS.CODIOART = IO1.CODIOART
                              AND IO1.MG &lt;&gt; 5
                              and (v_flggest = 1 or exists (select valoare from tmp_manevra_liste where filtru = 'CODGEST' and COALESCE(valoare,'') = COALESCE(N.GEST::varchar,'')))
                              and (vSubunitatea = 1 or vSubunitatea = G.CODSUBUNIT)
                              AND (vAnLucru*12+vLuna) BETWEEN IO1.ALStart and IO1.ALStop
                              GROUP BY ns.codobiect
                           ) b ON a.valoare::numeric = b.codobiect
      where a.filtru = 'CODOBIECT';
    END IF;
  end loop;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz7_calculeazazilestoc</obj_name>
  <obj_hashval>6c70c7fbf374b799f213a3f27eda8ceb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz7_calculeazazilestoc(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount NUMERIC(5);
  aZi date;
  StocP NUMERIC(20,7);
  Intrari NUMERIC(20,7);
  Iesiri NUMERIC(20,7);
  vSel varchar(20000);
  vAux varchar(1000);
  vCateGest NUMERIC(5);
  vCateLGest NUMERIC(5);
  v_obj record;
BEGIN
  --Florin 31.05.2024 - immediate
  --Florin 19.05.2023
  for v_obj in (select o.codobiect
                from nartobj o
                     inner join nart a on a.codarticol = o.codarticol
                where a.tiparticol = '0'-- and o.codobiect = 5010
                ) loop
    aCount := 0;
    aZi := to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy');
    while aZi &lt;= to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy') loop
      if aZi = to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy') then
        begin
          select nvl(cant,0) into StocP
          from tmp_stocreal where codobiect = v_obj.codobiect and tip = 'INIT';
        exception when others then StocP := 0;
        end;
      end if;
      -- intrari in zi
      vSel :=
      'SELECT
         SUM(CASE
           WHEN NVL(NSE.CODNIRSER, 0) = 0 THEN NS.CANTNIR
           ELSE NSE.CANTNIR
         END)
       FROM
         NIRSTOC NS
         INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
         INNER JOIN NGEST G ON G.CODGEST = N.GEST
         LEFT  JOIN NIRSER NSE ON NS.CODNIRSTOC = NSE.CODNIRSTOC
       WHERE
         N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 12, 15) AND  N.ANULAT = 0 AND N.OPERAT = 1
         AND N.DATANIR = to_date('''||to_char(aZi,'dd.mm.yyyy')||''',''dd.mm.yyyy'')
         AND (GETSUBUNITATE() = 1 OR G.CODSUBUNIT = GETSUBUNITATE())
         AND NS.CODOBIECT = '||V_OBJ.CODOBIECT;
      IF current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', TRUE)::boolean 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';
        vAux := '
        AND';
        IF    vCateLGest = 0 THEN vAux := vAux||' N.GEST IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
        ELSIF vCateGest  = 0 THEN vAux := vAux||' NS.CODLOCATIE IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'') ';
        ELSE vAux := vAux||' (N.GEST IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') OR NS.CODLOCATIE IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'')) ';
        END IF;
        vSel := vSel||vAux;
      END IF;

      IF current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateIoart', TRUE)::boolean THEN
        vAux := '
        AND NS.CODIOART IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
        vSel := vSel||vAux;
      END IF;
      begin
        execute vSel into Intrari;
      exception when others then Intrari := 0;
      end;
      if Intrari is null then Intrari := 0; end if;
      -- iesiri in zi
      vSel :=
      'SELECT
         sum(CASE WHEN L.TIPLIVR = 15 THEN -L1.CANT ELSE L1.CANT END)
       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 N.CODNIR = NS.CODNIR
         INNER JOIN NGEST G ON G.CODGEST = N.GEST
         LEFT JOIN NIRSER NE ON L1.CODNIRSER = NE.CODNIRSER
       WHERE
         L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7, 14, 15 ,16, 19, 20, 21, 23, 24) AND L.OPERAT = 1 AND L.ANULAT = 0 AND
         L.DATALIVR = to_date('''||to_char(aZi,'dd.mm.yyyy')||''',''dd.mm.yyyy'')
         AND (GETSUBUNITATE() = 1 OR G.CODSUBUNIT = GETSUBUNITATE())
         AND NS.CODOBIECT = '||V_OBJ.CODOBIECT;
      vSel := vSel||vAux;
      begin
        execute vSel into Iesiri;
      exception when others then Iesiri := 0;
      end;
      if Iesiri is null then Iesiri := 0; end if;
      if Intrari &gt; 0 then aCount := aCount + 1;
      else
        if Iesiri &gt; 0 then aCount := aCount + 1;
        else if StocP &gt; 0 then aCount := aCount + 1; end if;
        end if;
      end if;
      StocP := StocP + Intrari - Iesiri;
      aZi := aZi + 1;
    end loop;
    execute 'update '||tmpName||' set nrzile = '||aCount||' where codobiect = '||v_obj.codobiect;
  end loop;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz7_setjoinuri</obj_name>
  <obj_hashval>36029c3678d56071173619fd2543f583</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz7_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 19.05.2023
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_NAPROVIZ7.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nart_getgnullalias</obj_name>
  <obj_hashval>f4cfe3d620046b6c688a91f9ced76692</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nart_getgnullalias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_NART.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_nart_getgsuplcols</obj_name>
  <obj_hashval>108fbffbcb6376290334cf629d018320</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nart_getgsuplcols(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_NART.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_nart_getgsupljoins</obj_name>
  <obj_hashval>547e521c75596c3789609334f9f9fd4f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nart_getgsupljoins(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_NART.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_nart_getguseralias</obj_name>
  <obj_hashval>a9f38d4e0f7f6e75c6422a2a547062b6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nart_getguseralias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_NART.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_nart_getguserfields</obj_name>
  <obj_hashval>cd1907aefc110075c60e0ea504c43ec1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nart_getguserfields(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_NART.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_nart_getvtoateart</obj_name>
  <obj_hashval>948fa387a19ae35da8c9e0ad38fbd7c5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nart_getvtoateart(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_NART.vToateArt', 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_nart_gnullalias</obj_name>
  <obj_hashval>b44e6d9ac4778571e2a2e15b3a33b4c3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nart_gnullalias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_NART.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_nart_gsuplcols</obj_name>
  <obj_hashval>7d3adacfbf1823734ee82dc77e479de9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nart_gsuplcols(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_NART.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_nart_gsupljoins</obj_name>
  <obj_hashval>0cf9f24dbe47b0ec2d85da6b312e2b5d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nart_gsupljoins(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_NART.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_nart_guseralias</obj_name>
  <obj_hashval>a625fdff9e7b8ee0073a6a0ffde93b46</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nart_guseralias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_NART.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_nart_setgsuplcols</obj_name>
  <obj_hashval>bb690b5d4583bce85aa2898c622fac29</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nart_setgsuplcols(agsuplcols character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_NART.gSuplCols',agSuplCols,false);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nart_setparams</obj_name>
  <obj_hashval>d8b7ab99d12a38acbcf6784994e6a17f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nart_setparams(ptoateart integer)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_NART.vToateArt',pToateArt::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nart_setvtoateart</obj_name>
  <obj_hashval>c039d7a1e79de82fffb345ce69ae3072</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nart_setvtoateart(avtoateart boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
 if avToateArt
 then perform set_config('PKG_LIST_BASE_NART.vToateArt','1',false);
 else perform set_config('PKG_LIST_BASE_NART.vToateArt','0',false);
 end if;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nart_vtoateart</obj_name>
  <obj_hashval>8ca0a54456744f8808dba9eeb8e0b995</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nart_vtoateart(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_NART.vToateArt', 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_nartofe_baga_dinamic_cols</obj_name>
  <obj_hashval>a2626e06272967e9c9383aff0dd15ba6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nartofe_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  K     NUMERIC := 0;
BEGIN
  --Adina 19 august 2020
  DELETE FROM tmp_dinamic_cols;
  IF  current_setting('PKG_LIST_BASE_NARTOFE.vPretImplicit', true)::NUMERIC = 0 AND  current_setting('PKG_LIST_BASE_NARTOFE.vCatPret', true)::numeric &lt;= 0 AND  current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric &gt; 1 THEN
    IF  COALESCE(current_setting('PKG_LIST_BASE_NARTOFE.vCatPret', true)::numeric, 0) = -1 THEN
      IF current_setting('PKG_LIST_BASE_NARTOFE.vToateArt', true)::NUMERIC = 1 THEN
        FOR v_rec IN (SELECT CODCATPRET, DEN_CATPRET
                      FROM ncatpret
                      WHERE CODCATPRET IN (SELECT  DISTINCT CODCATPRET FROM PretM p )
                      ORDER BY CODCATPRET
                     )
        LOOP
          k := k + 1;
          INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('L' || coalesce((k)::varchar,''), coalesce(v_rec.DEN_CATPRET,'') || '/Lei', v_rec.CODCATPRET);
          INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('V' || coalesce((k)::varchar,''), coalesce(v_rec.DEN_CATPRET,'') || '/Valuta', v_rec.CODCATPRET);
        END LOOP;
      ELSE
        FOR v_rec IN (SELECT CODCATPRET, DEN_CATPRET
                      FROM ncatpret
                      WHERE CODCATPRET IN (SELECT DISTINCT CODCATPRET FROM PretM p
                                           WHERE CodObiect IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODOBIECT')
                                          )
                      ORDER BY CODCATPRET
                     )
        LOOP
          k := k + 1;
          INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('L' || coalesce((k)::varchar,''), coalesce(v_rec.DEN_CATPRET,'') || '/Lei', v_rec.CODCATPRET);
          INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('V' || coalesce((k)::varchar,''), coalesce(v_rec.DEN_CATPRET,'') || '/Valuta', v_rec.CODCATPRET);
        END LOOP;
      END IF;
    ELSE
      FOR v_rec IN (SELECT CODCATPRET, DEN_CATPRET
                    FROM ncatpret
                    WHERE CODCATPRET &lt;&gt; 0
                    ORDER BY CODCATPRET
                   )
      LOOP
        k := k + 1;
        INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('L' || coalesce((k)::varchar,''), coalesce(v_rec.DEN_CATPRET,'') || '/Lei', v_rec.CODCATPRET);
        INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('V' || coalesce((k)::varchar,''), coalesce(v_rec.DEN_CATPRET,'') || '/Valuta', v_rec.CODCATPRET);
      END LOOP;
    END IF;
  END IF;

  perform set_config('PKG_LIST_BASE_NARTOFE.vNrCol',k::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nartofe_setjoinuri</obj_name>
  <obj_hashval>25d51d39737f24e45f32a256bfe65b17</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nartofe_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_NARTOFE.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nartofe_setparams</obj_name>
  <obj_hashval>a6dfeb1f0d34af0f28f9b2f78c499eff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nartofe_setparams(ptoateart numeric DEFAULT 1, ppretimplicit numeric DEFAULT 1, pcatpret numeric DEFAULT 0, pstocsubcur numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  perform set_config('PKG_LIST_BASE_NARTOFE.vToateArt'    ,ptoateart::varchar     , false);
  perform set_config('PKG_LIST_BASE_NARTOFE.vPretImplicit', ppretimplicit::varchar, false);
  perform set_config('PKG_LIST_BASE_NARTOFE.vCatPret'     , pcatpret::varchar     , false);
  perform set_config('PKG_LIST_BASE_NARTOFE.vStocSubCur'  ,pstocsubcur::varchar   , false);
  PERFORM pkg_list_base_nartofe_BAGA_DINAMIC_COLS();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nartum_processlist</obj_name>
  <obj_hashval>8a1340b1c27b582697c87c09552970e6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nartum_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar := '';
  gSuplCols   varchar := 'nartobj o, nart a, num u, num1 u1, nclasea c, nclaseas cs, npart prod, NAGENDA NAG, NLOCALIT LOC, NJUDET JUD';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';

BEGIN
  --Adina 04.03.2021 -add col. X_
  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_NARTUM.gSuplCols',gSuplCols,false);

  sInsert := 'INSERT INTO ' || tmpName ||'(
    DenArt, DenUM, DenUM1, Princ, Par, DenClasaA, SimbolClasaA, Masa, Volum
    , x_Judet, X_CodSubunit, X_CodClasaP' || gUserFields || ')
  SELECT
    o.denumire, u.den_um, u1.den_um1, (Case when u1.secundara = 1 then ''DA'' else ''NU'' end), u1.paritate, c.Den_Clasea, c.simbol, o.Masa, o.Volum
    , coalesce(JUD.SIMBAUTO,''XX''), getSubunitate(), prod.codclasa ' || gUserAlias || '
  FROM NARTOBJ o
    INNER JOIN nart     a    ON a.codarticol   = o.codarticol
    LEFT  JOIN num      u    ON u.codum        = a.um
    LEFT  JOIN num1     u1   ON u1.codum       = a.um
    LEFT  JOIN nclasea  c    ON c.codclasea    = Coalesce(a.clasa,0)
    LEFT  JOIN nclaseas cs   ON cs.codclaseas  = Coalesce(a.clasastatist,0)
    LEFT  JOIN npart    prod ON prod.codpart   = o.codproducator
    LEFT  JOIN NAGENDA  NAG  ON prod.codpart   = NAG.CODPART AND NAG.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(NAG.INACTIV, 0) = 0
    LEFT  JOIN NLOCALIT LOC  ON NAG.CODLOCALIT = LOC.CODLOCALIT
    LEFT  JOIN NJUDET   JUD  ON JUD.CODJUDET   = LOC.CODJUDET ' || gSuplJoins || '
  WHERE a.codarticol &gt; 0 ';

  IF  current_setting('PKG_LIST_BASE_NARTUM.vToateArt', true)::numeric = 0 THEN
    sInsert := coalesce(sInsert,'') || '
      AND O.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')';
  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_nartum_setparams</obj_name>
  <obj_hashval>cbb3df8d0de2c6b5d26086640e2d1c20</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nartum_setparams(ptoateart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_NARTUM.vToateArt',ptoateart::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ncdoc_setparams</obj_name>
  <obj_hashval>adaa54338441ce3863bc0a48d9e05579</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ncdoc_setparams(pcodnc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 25 septembrie 2020
  perform set_config('PKG_LIST_BASE_NCDOC.vCodNC',(pCodNC)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nclasea_processlist</obj_name>
  <obj_hashval>9bd95134c27d856ac921894bd9db66b9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nclasea_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  gSuplCols   varchar := 'nclasea nc';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 31.01.2023 - fixat 56789
  --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_NCLASEA.gSuplCols',gSuplCols,false);

  sInsert := 'INSERT INTO ' || tmpName ||
      '(
        DENUMIRE,
        SIMBOL,
        NIVEL,
        NRANALITICE ' || gUserFields ||
      ')' ||
      ' WITH recursive a AS
      (
         SELECT lpad('' '',1::integer*2,'' '')||nc.den_clasea den_cl,
                nc.simbol AS simbol1,
                1::integer AS nivel1,
                nc.nranalitice AS nranalitice1,
                codclasea AS codclasea1, codparinte AS codparinte1' || gUserAlias || '
         FROM nclasea nc ' || gSuplJoins || '
         WHERE coalesce(nc.codparinte,0)=0
         UNION all
         SELECT lpad('' '',(a.nivel1+1)*2,'' '')||nc.den_clasea den_cl,
                nc.simbol AS simbol1,
                a.nivel1+1 AS nivel1,
                nc.nranalitice AS nranalitice1,
                nc.codclasea AS codclasea1, nc.codparinte AS codparinte1' || gUserAlias || '
         FROM nclasea nc inner join a ON a.codclasea1 = nc.codparinte ' || gSuplJoins || '
      )
      select den_cl, simbol1, nivel1, nranalitice1 ' || REPLACE(upper(gUserAlias), 'NC.', 'a.') || ' from a ' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE( sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ncont_processlist</obj_name>
  <obj_hashval>8601d33e2d64f602214f6c1f1a5f0aa1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ncont_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;
  sAnLunaLucru varchar := COALESCE(getanlunalucru()::varchar,'0');
BEGIN
  --Adina 10.05.2021 - alstart,alstop, sAnLunaLucru
  CALL PRC_AL_CHECK('ncont1', 0);

  gSuplCols := 'NCont NC, NContS NCS, 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_NCONT.gSuplCols',gSuplCols, false);

  sInsert := 'INSERT INTO ' || coalesce(tmpName, '') || '(
        SIMBOL, DEN_CONT, CLASA, TIP,
        BALANTASINTETICA, BALANTAANALITICA, CODCONT,
        SIMBOLS, TIPS,
        SIMBOLT, TIPT,
        NAME_CONT, SIMB_TransfSF, SIMB_SincrRul, SIMB_TransfD, SIMB_TransfCDim, SIMB_TransfC,
        CentruCost' || gUserFields || ')
      SELECT
        LPAD('' '',((Case  When NC.NIVEL=1 then 0 else NC.NIVEL-1 end)*2)::integer)||nc.simbol simbol, nc.den_cont, nc.clasa,
        (Case  When nc.tipcont=0 then ''A'' When nc.tipcont=1 then ''P'' When nc.tipcont=2 then ''Bifunc.'' else ''nedef.'' end),
        (Case  When nc.balantasintetica=0 then ''Nu'' When nc.balantasintetica=1 then ''Da'' else ''nedef.'' end),
        (Case  When nc.vizibilbalanta=0 then ''Nu'' When nc.vizibilbalanta=1 then ''Da'' else ''nedef.'' end),
        nc.codcont,  ncs.simbol,
        (Case  When ncs.codconts is NULL then NULL else(Case  When ncs.tipcont=0 then ''A'' When ncs.tipcont=1 then ''P'' When ncs.tipcont=2 then ''Bifunc.'' else ''nedef.'' end) end),
        nct.simbol,
        (Case  When nct.codcontt is NULL then NULL else(Case  When nct.tipcont=0 then ''A'' When nct.tipcont=1 then ''P'' When nct.tipcont=2 then ''Bifunc.'' else ''nedef.'' end) end),
        nc.name, nc_t.simbol, nc_s.simbol, nc_b.simbol, nc_d.simbol, nc_c.simbol,
        cc.denumire' || gUserAlias || '
      FROM ncont nc
        INNER JOIN ncont1     nc1  ON nc1.codcont  = nc.codcont AND '||sAnLunaLucru||' BETWEEN nc1.ALSTART and nc1.ALSTOP
        LEFT  JOIN nconts     ncs  ON ncs.codconts = nc1.CONTSECUNDAR
        LEFT  JOIN ncontt     nct  ON nct.codcontt = nc1.CONTTERTIAR
        LEFT  JOIN ncont      nc_t ON nc_t.codcont = nc1.continkidsold
        LEFT  JOIN ncont      nc_s ON nc_s.codcont = nc1.sincronizare
        LEFT  JOIN ncont      nc_b ON nc_b.codcont = nc1.conttransfd
        LEFT  JOIN ncont      nc_d ON nc_d.codcont = nc1.conttransfcdim
        LEFT  JOIN ncont      nc_c ON nc_c.codcont = nc1.conttransfc
        LEFT  JOIN centrecost cc   ON cc.codcentru = nc1.codcentru' || gSuplJoins || '
      ORDER BY ltrim (nc.simbol) ';

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nconts_processlist</obj_name>
  <obj_hashval>2b69d81c4300a2ed6eab82be1665a3bd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nconts_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
  --Adina 03.02.2021
  gSuplCols := 'NContS NC';

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

  sInsert :=
  'INSERT INTO '||coalesce(tmpName,'')||'(
    SIMBOL, DEN_CONT, CLASA, TIP,
    BALANTASINTETICA, BALANTAANALITICA, CODCONTS,
    SIMBOLP, TIPP,
    NAME_CONT '||gUserFields||')
  WITH nc1 AS
  (
    SELECT
      CODCONTS,
      Max(CODCONT) CODCONT
    FROM (SELECT CODCONTS, CODCONT, dense_rank() over(Partition by CODCONTS ORDER BY ANSTART desc, LUNASTART desc) NR
          FROM nconts1
          WHERE (ANSTART * 12 + LUNASTART) &lt;= getAnLunaLucru()
         ) aa
    WHERE NR=1
    GROUP BY CODCONTS
  )
  SELECT
    LPAD('' '', ((case when NC.NIVEL=1 then 0 else NC.NIVEL-1 end)*2)::integer)||nc.simbol simbol,
    nc.den_cont, nc.clasa,
    (case nc.tipcont when 0 then ''A'' when 1 then ''P'' when 2 then ''Bifunc.'' else ''nedef.'' end),
    (case nc.balantasintetica when 0 then ''Nu'' when 1 then ''Da'' else ''nedef.'' end),
    (case nc.vizibilbalanta when 0 then ''Nu'' when 1 then ''Da'' else ''nedef.'' end),
    nc.codconts,
    ncp.simbol,
    (case when ncp.codcont IS NULL then NULL else (case ncp.tipcont when 0 then ''A'' when 1 then ''P'' when 2 then ''Bifunc.'' else ''nedef.'' end) end),
    nc.name '||gUserAlias||'
  FROM nconts nc
    INNER JOIN nc1       ON nc1.codconts = nc.codconts
    LEFT  JOIN ncont ncp ON ncp.codcont  = nc1.codcont'|| gSuplJoins||'
  ORDER BY ltrim(nc.simbol) ';

  perform LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
end;

$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ncontt_processlist</obj_name>
  <obj_hashval>7b44658710c4ef78074b59e630ffd2cb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ncontt_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
  --Florin 03.02.2021
  gSuplCols := 'NContT NC';

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

  sInsert :=
  'INSERT INTO '||coalesce(tmpName,'')||'(
    SIMBOL, DEN_CONT, CLASA, TIP,
    BALANTASINTETICA, BALANTAANALITICA, CODCONTT,
    NAME_CONT '||gUserFields||')
  SELECT
    LPAD('' '',((CASE WHEN NC.NIVEL = 1 THEN 0 ELSE NC.NIVEL-1 END)*2)::integer)||nc.simbol simbol, nc.den_cont, nc.clasa, (CASE WHEN nc.tipcont = 0 THEN ''A'' WHEN nc.tipcont = 1 THEN ''P'' WHEN nc.tipcont = 2 THEN ''Bifunc.'' ELSE ''nedef.'' END),
    (CASE WHEN nc.balantasintetica = 0 THEN ''Nu'' WHEN nc.balantasintetica = 1 THEN ''Da'' ELSE ''nedef.'' END), (CASE WHEN nc.vizibilbalanta = 0 THEN ''Nu'' WHEN nc.vizibilbalanta = 1 THEN ''Da'' ELSE ''nedef.'' END), nc.codcontt,    nc.name '||gUserAlias||'
  FROM ncontt nc '||
    gSuplJoins||'
  ORDER BY ltrim(nc.simbol) ';

  perform LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_neccmdcli_getsume</obj_name>
  <obj_hashval>eab198181ed05a10f98447626ababb83</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_neccmdcli_getsume(acodarticol numeric, acodcomanda numeric, idx numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC  RECORD;
  aRez   varchar;
  aTotal numeric;
  i      numeric;
  Par2   varchar(500);
begin
  --Adina 12.01.2021 tichet 42144 - schimbat formatul valorilor (sa nu mai apara cu toate cele 7 zecimale)
  --Bogdan 15.09.2020
  aTotal := 0;
  i      := 0;
  Par2   := '';
  aRez   := '';

  FOR v_rec IN (SELECT a1.valoare, sum(c1.restacceptat) CANT, obj.codarticol, c1.codcomanda
                FROM natrib1            a1
                     INNER JOIN natrib  at  ON a1.codatribut = at.codatribut
                     LEFT JOIN (SELECT * FROM natrobj ato
                                WHERE EXISTS (SELECT c1.codobiect FROM comanda1 c1
                                              WHERE c1.codcomanda = aCodComanda and c1.codobiect = ato.codobiect
                                                    and c1.codobiect IN (SELECT codobiect FROM nartobj WHERE codarticol = aCodArticol)
                                             )
                               )        ao  ON ao.codvalatr = a1.codvalatr
                     LEFT JOIN nartobj  obj ON ao.codobiect = obj.codobiect
                     LEFT JOIN comanda1 c1  ON c1.codobiect = ao.codobiect and c1.codcomanda = aCodComanda
                                               and c1.codobiect IN (SELECT codobiect FROM nartobj WHERE codarticol = aCodArticol)
                WHERE at.codatribut = current_setting('PKG_LIST_BASE_NECCMDCLI.vCodAtribut', true) ::numeric
                GROUP BY a1.valoare, obj.codarticol, c1.codcomanda
                ORDER BY a1.valoare
               )
  LOOP
    aTotal := aTotal + COALESCE(v_rec.Cant, 0);
    IF v_rec.cant &gt; 0 THEN
      i := i + 1;
      IF i &lt; 15 THEN
        IF i = 1 THEN
          aRez := coalesce(v_rec.valoare,'') || ': ' || CASE WHEN (COALESCE(v_rec.cant, 0) - COALESCE(v_rec.cant, 0)::integer) = 0
                                                               THEN to_char(COALESCE(v_rec.cant, 0),'fm99999999999999999999')
                                                             ELSE to_char(COALESCE(v_rec.cant, 0),'fm9999999999999D9999999')
                                                        END ;
        ELSE
          aRez := coalesce (aRez,'') || ' | ' || coalesce (v_rec.valoare,'') || ': ' || CASE WHEN (COALESCE(v_rec.cant, 0) - COALESCE(v_rec.cant, 0)::integer) = 0
                                                                                               THEN to_char(COALESCE(v_rec.cant, 0),'fm99999999999999999999')
                                                                                             ELSE to_char(COALESCE(v_rec.cant, 0),'fm9999999999999D9999999')
                                                                                        END ;
        END IF;
      ELSE
        Par2 := Par2||' | '||v_rec.valoare||': '|| CASE WHEN (COALESCE(v_rec.cant, 0) - COALESCE(v_rec.cant, 0)::integer) = 0
                                                          THEN to_char(COALESCE(v_rec.cant, 0),'fm99999999999999999999')
                                                        ELSE to_char(COALESCE(v_rec.cant, 0),'fm9999999999999D9999999')
                                                   END;
      END IF;
    END IF;
  END LOOP;

  aRez := 'TOTAL: ' || CASE WHEN (aTotal - aTotal::integer) = 0
                              THEN to_char(aTotal,'fm99999999999999999999')
                            ELSE to_char(aTotal,'fm9999999999999D9999999')
                       END || ' | ' || coalesce (aRez,'');

  IF Idx = 1 THEN
    return aRez;
  ELSE
    return Par2;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_neccmdcli_setjoinuri</obj_name>
  <obj_hashval>1a48c008b9b4d232ef8ad3b78fa759f6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_neccmdcli_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 15.09.2020
  PERFORM pkg_list_struct_SetTableSpec (current_setting ('PKG_LIST_BASE_NECCMDCLI.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_neccmdcli_setparams</obj_name>
  <obj_hashval>3a58f50a3231b418c8c0cdfb05a2e205</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_neccmdcli_setparams(acodatribut numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 15.09.2020
  perform set_config ('PKG_LIST_BASE_NECCMDCLI.vCodAtribut',aCodAtribut::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nir_get_simbol</obj_name>
  <obj_hashval>64228e01a6b3e151150766b91957849f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_get_simbol(io_cod numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  SIMBOL varchar;
BEGIN
  --Adina 17 septembrie 2020
  SELECT C.SIMBOL INTO SIMBOL
  FROM   TMP_IOART1 T
        INNER JOIN NCONT C ON  C.CODCONT = T.CONT
  WHERE T.CODIOART1 = IO_COD;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nir_get_simbol</obj_name>
  <obj_hashval>2d0182c8db2377fb0be5d5dd055b159b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_get_simbol(INOUT wme_result character varying, INOUT io_cod numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  SIMBOL varchar;
begin
  SELECT C.SIMBOL
  INTO SIMBOL
  FROM TMP_IOART1 T INNER JOIN NCONT C ON  C.CODCONT = T.CONT
  WHERE T.CODIOART1 = IO_COD;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nir_getgnullalias</obj_name>
  <obj_hashval>2d1e32f356357e6a8933f9a6d94ffa84</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_getgnullalias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NIR.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_nir_getgsuplcols</obj_name>
  <obj_hashval>433fc2064d0ddfbed42fd9d6625d7aca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_getgsuplcols(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NIR.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_nir_getgsupljoins</obj_name>
  <obj_hashval>a92d490ab44d88ab744f9cbe1010195a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_getgsupljoins(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NIR.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_nir_getguserfields</obj_name>
  <obj_hashval>0d3d0a9badf6e53e749bc2b30bff5e84</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_getguserfields(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NIR.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_nir_getseriinir</obj_name>
  <obj_hashval>62f6e7a5abaa138739fcacf99a59736c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_getseriinir()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 17 septembrie 2020
  INSERT INTO tmp_manevra_liste(filtru, valoare)
  SELECT 'CODNIRSTOC', codnirstoc
  FROM nirstoc_man;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nir_getvcodnir</obj_name>
  <obj_hashval>a00d354e4f7f692897211753bb063039</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_getvcodnir(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_NIR.vCodNir', true),'999999999999999999');
  RETURN ;
  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_nir_getvcodnirstoc</obj_name>
  <obj_hashval>acf1a61e9d00b2da62db8585f1359846</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_getvcodnirstoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_NIR.vCodNirStoc', true),'999999999999999999');
  RETURN ;
  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_nir_getvtipdoc</obj_name>
  <obj_hashval>f312ae6253aa3fd5c12747889c87a9d4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_getvtipdoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_NIR.vTipDoc', true),'999999999999999999');
  RETURN ;
  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_nir_getvverso</obj_name>
  <obj_hashval>4c5bd67344f9fb8c45d3bd8984e945da</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_getvverso(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NIR.vVerso', 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_nir_gnullalias</obj_name>
  <obj_hashval>3ff3a6ccffa3f7578ea8cd28b99e161c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_gnullalias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NIR.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_nir_gsuplcols</obj_name>
  <obj_hashval>776419c762d98f8a10116da7b7a0d8b2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_gsuplcols(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NIR.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_nir_guserfields</obj_name>
  <obj_hashval>3bf920aeb70953c8a345f0e03c3eadc1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_guserfields(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NIR.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_nir_setgnullalias</obj_name>
  <obj_hashval>ec302480ae1de6e3876e48d116e751c2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_setgnullalias(agnullalias character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_NIR.gNullAlias',agNullAlias,false);
end;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nir_setguseralias</obj_name>
  <obj_hashval>4f446ae4776a923014b1bc175b4b4ea6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_setguseralias(aguseralias character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_NIR.gUserAlias',agUserAlias,false);
end;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nir_setparams</obj_name>
  <obj_hashval>9ea57696b530837c502dfbde804ddb98</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_setparams(pcodnir numeric, ptipdoc numeric, pverso numeric DEFAULT 1, pcodnirstoc numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 17 septembrie 2020
  IF  Coalesce( pCodNir, -1) &gt;= 0 THEN
    perform set_config('PKG_LIST_BASE_NIR.vCodNir',   pCodNir::varchar,false);
  END IF;
  perform set_config('PKG_LIST_BASE_NIR.vTipDoc',     pTipDoc::varchar                  ,false);
  perform set_config('PKG_LIST_BASE_NIR.vVerso',      (COALESCE(pVerso,1)=1)::varchar   ,false);
  perform set_config('PKG_LIST_BASE_NIR.vCodNirStoc',(COALESCE(pCodNirStoc,0))::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nir_setvcodnir</obj_name>
  <obj_hashval>843fa5b6dd90937c1646db06eaeab0b9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_setvcodnir(avcodnir numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_NIR.vCodNir',to_char(avCodNir,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nir_setvcodnirstoc</obj_name>
  <obj_hashval>485b8bb301f9f9db99987ecc24b554b2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_setvcodnirstoc(avcodnirstoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_NIR.vCodNirStoc',to_char(avCodNirStoc,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nir_setvtipdoc</obj_name>
  <obj_hashval>6b1cff05622027118706ec37541b998a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_setvtipdoc(avtipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_NIR.vTipDoc',to_char(avTipDoc,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nir_vcodnir</obj_name>
  <obj_hashval>a7d945ac77299ea513a87057d6ed43fc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_vcodnir(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_NIR.vCodNir', true),'999999999999999999');
  RETURN ;
  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_nir_vcodnirstoc</obj_name>
  <obj_hashval>a25525fee841ae9c15aa4e836969d0e4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_vcodnirstoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_NIR.vCodNirStoc', true),'999999999999999999');
  RETURN ;
  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_nir_vtipdoc</obj_name>
  <obj_hashval>e960f3348f84c7dec48db2b0e033e041</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_vtipdoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER(current_setting('PKG_LIST_BASE_NIR.vTipDoc', true),'999999999999999999');
  RETURN ;
  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_nir_vverso</obj_name>
  <obj_hashval>59aa47e9d7ece1dcad7f5ffe9eda9a30</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_vverso(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NIR.vVerso', 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_niries_processlist</obj_name>
  <obj_hashval>242abd5dcbb129d287b7581cfa5a675b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_niries_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'nirstoc ns, nartobj nao, num1 num1';
   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 = 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_NIRIES.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(ART, UM, CANTDOC, CANTNIR, PACH, PINREG ,PVANZ, VALACH, VALINREG, VALVANZ ' || gUserFields || ')
  SELECT nao.denumire, num1.den_um1, i1.cant , l1.cant, ns.pret - ns.adaos, ns.pret, i1.pu, (ns.pret - ns.adaos) * l1.cant, ns.pret * l1.cant, i1.pu * l1.cant ' || gUserAlias || '
  FROM   TMP_LIVR1 l1
        INNER JOIN tmp_iesiri1 i1 ON i1.codies1    = l1.codies1
        INNER JOIN nirstoc ns     ON ns.codnirstoc = l1.codnirstoc
        INNER JOIN nartobj nao    ON nao.codobiect = i1.codobiect
        INNER JOIN num1           ON num1.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_nirserii_processlist</obj_name>
  <obj_hashval>16936dfabc905df231542ca81e40b94e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nirserii_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'NIRSTOC NS, NARTOBJ O, NUM1 UM, NIRSER NSER, NSERII SER' ;
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodNirStoc      varchar := current_setting('PKG_LIST_BASE_NIRSERII.vCodNirStoc', true);
BEGIN
  --Adina 17 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_NIRSERII.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sINSERT :=
  'INSERT INTO ' || TMPNAME || '(
    ARTICOL, CODINTERN, CODEXTERN, SERIE, UM,
    CANT, BUCATI, DIVIZOR, LOCATIE ' || gUserFields || ')
  SELECT
    O.DENUMIRE, O.CODINTERN, O.CODEXTERN, SER.SERIE, UM.DEN_UM1,
    NSER.CANTNIR/UM.PARITATE, NSER.BUCATI, NSER.DIVIZOR, LOC.DENUMIRE ' || gUserAlias || '
  FROM NIRSTOC NS
    INNER JOIN NARTOBJ  O    ON O.CODOBIECT     = NS.CODOBIECT
    INNER JOIN NUM1     UM    ON UM.CODUM1       = NS.UMSEC
    INNER JOIN NIRSER   NSER ON NSER.CODNIRSTOC = NS.CODNIRSTOC
    INNER JOIN NSERII   SER  ON SER.CODSERIE    = NSER.CODSERIE
    LEFT  JOIN NLOCATII LOC  ON NS.CODLOCATIE   = LOC.CODLOCATIE' || gSuplJoins || '
  WHERE NS.CODNIRSTOC = ' || coalesce(vCodNirStoc ,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nirserii_setparams</obj_name>
  <obj_hashval>15d19a7637831f51b658df63b7f07a87</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nirserii_setparams(pcodnirstoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 17 septembrie 2020
  perform set_config('PKG_LIST_BASE_NIRSERII.vCodNirStoc',(pCodNirStoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nmvshistory_processlist</obj_name>
  <obj_hashval>628d24ae7b2f7ca5d78dbd095459c116</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nmvshistory_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sCondSupl   varchar;
  sKey        varchar;
  sJoinObj    varchar;
  gSuplCols   VARCHAR := '';
   gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Adina 11.08.2021 - sinc.Oracle
  --Adina 12.07.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_NMVSHISTORY.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sKey := fnc_GetValConstantaLucru('NMVSKey');
  IF  sKey = '1' THEN
    sJoinObj := chr(13) || ' LEFT JOIN NARTOBJ O ON UPPER(O.CODEXTERN) = UPPER(N.GTIN) ' || chr(13);
  ELSE
    sJoinObj := chr(13) || ' LEFT JOIN NARTOBJ O ON UPPER(O.CODINTERN) = UPPER(N.GTIN) ' || chr(13);
  END IF;

  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(
     USERX,
     SUBUNITATEA,
     DATAVERIF,
     GTIN,
     DATAEXP,
     LOT,
     SN,
     SKEMETYPE,
     MESAJ,
     CODMESAJ,
     STATUS,
     MOTIV,
     CODFUNCTIE,
     GLN ' || gUserFields || ')
    SELECT
     U.USERNAME,
     S.DEN_SUBUNIT,
     N.DATAVERIF,
     N.GTIN,
     N.DATAEXP,
     N.LOT,
     N.SN,
     N.SKEMETYPE,
     N.MESAJ,
     N.CODMESAJ,
     N.STATUS,
     N.MOTIV,
     N.CODFUNCTIE,
     N.GLN ' || gUserAlias || '
    FROM NMVS N
         LEFT JOIN TMP_UTILIZATOR U ON U.CODUTILIZATOR = N.USERID
         LEFT JOIN NSUBUNIT       S ON S.CODSUBUNIT    = N.SUBUNITATEA ' || coalesce(sJoinObj,'') || gSuplJoins || '
    WHERE N.DATAVERIF::date 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_nmvshistory_setjoinuri</obj_name>
  <obj_hashval>31962ff18ea9b60d083d6ef59b8867e2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nmvshistory_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 12.07.2021 - sinc.Oracle
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_NMVSHISTORY.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nomartamb_processlist</obj_name>
  <obj_hashval>02e6a719ba04542a753ad45eadcbcf20</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nomartamb_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplCols   VARCHAR := 'NARTOBJ OBJ, NARTOBJ OBJR, NART ART, NCLASEA CA, NUM UMPRINC, NUM1 UM1PRINC, NUM1 UMAMB, NARTAMB AMB';
  gSuplJoins  VARCHAR := '';
  sInsert     varchar;
BEGIN
  --Adina 05.11.2020 adaugat cond. AND OBJ.codarticol&lt;&gt;0 (tichet 40405)

  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM Set_Config('PKG_LIST_BASE_NOMARTAMB.gSuplCols', gSuplCols, False);

  sInsert := 'INSERT INTO ' || coalesce(tmpName, '') || '(DenArt, DenAmbRet, CodExtern, DenUMP, DenUMAmb, TipArticol' || gUserFields || ' )
          SELECT OBJ.denumire, OBJR.denumire, OBJ.CodExtern, UMPrinc.Den_UM, UMAmb.Den_UM1, (Case  When ART.tiparticol= ''0'' then ''Stoc'' else ''Serviciu'' end) TipArticol' || gUserAlias || '
          FROM NARTOBJ OBJ
               INNER JOIN NART    ART      ON ART.codarticol = OBJ.codarticol AND OBJ.codarticol&lt;&gt;0
               LEFT  JOIN NCLASEA CA       ON CA.codclasea   = ART.clasa
               LEFT  JOIN NARTAMB AMB      ON AMB.codobiect  = OBJ.CodObiect
               LEFT  JOIN NARTOBJ OBJR     ON OBJR.CODOBIECT = AMB.CODOBIECTRETURN
               LEFT  JOIN NUM     UMPrinc  ON UMPrinc.codum  = ART.UM
                LEFT  JOIN NUM1    UM1Princ ON UM1Princ.codum = ART.UM AND UM1Princ.secundara = 0
               LEFT  JOIN NUM1    UMAmb    ON UMAmb.codum1   = AMB.umsec' || gSuplJoins || '
          WHERE  1 = 1 ';

     IF current_setting('PKG_LIST_BASE_NOMARTAMB.vToateArt', true)::numeric = 0 THEN
       sInsert := coalesce(sInsert, '') ||
       ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' AND VALOARE = OBJ.CODOBIECT::varchar )';
     END IF;
--  insert into x(view_name, test) values ('nomartamb', sinsert);
--  insert into x(view_name, test) values ('vtoate', current_setting('PKG_LIST_BASE_NOMARTAMB.vToateArt', true));
  PERFORM LIST_EXECUTE_IMMEDIATE( sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nomgest_processlist</obj_name>
  <obj_hashval>f3743b2085a039adc0699c0074cd82a6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nomgest_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  gSuplCols   varchar := 'ngest g,nlocatii loc,nagenda a,nlocalit l,njudet j,nactivit act,npers p,ioart i,ncont c,ncatpret cp,DOCUMENTE DD';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Adina 05.04.2021 - alstart,alstop
  --Adina iulie 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'TMP_CAMERE_LST', 'TCL', 'TCL.CODGEST = G.CODGEST',NULL);

  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);

  PERFORM set_config('PKG_LIST_BASE_NOMGEST.gSuplCols',gSuplCols,false);

  sInsert := 'INSERT INTO ' || tmpName || '(
      Den, Locatie,SimbGest , Loc, Jud, Clasa, Activit, Gest, Custodie, TipCont, SimbCont, CatPret,
      sector, strada, nr1, nr2, bloc, scara, etaj, apart, telefon' || gUserFields || '
    )
    SELECT
      g.den_gest, loc.denumire locatie ,g.simbol, l.den_localit, j.den_judet, cg.den_claseg , act.den_activit,
      p.nume ||'' ''||p.prenume as Gestionar, case when g.custodie=0 then ''NU'' when g.custodie=1 then''DA'' else ''--'' end,
      i.den_ioart, c.simbol, cp.den_catpret,
      a.sector, a.strada, a.nr1, a.nr2, a.bloc, a.scara, a.etaj::numeric, a.apart::numeric ,a.telefon ' || gUserAlias || '
    FROM ngest g
      LEFT JOIN DOCUMENTE DD  ON g.codgest      = DD.codDOC AND DD.TIPDOC = 506
      LEFT JOIN nlocatii  loc ON g.codgest      = loc.codgest
      LEFT JOIN nagenda   a   ON a.codgest      = g.codgest
      LEFT JOIN nlocalit  l   ON l.codlocalit   = a.codlocalit
      LEFT JOIN njudet    j   ON j.codjudet     = l.codjudet
      LEFT JOIN nactivit  act ON act.codactivit = g.codactivit
      LEFT JOIN nclaseg   cg  ON cg.codclaseg   = g.codclasa
      LEFT JOIN npers     p   ON p.codpers      = g.codgestionar
      LEFT JOIN ioart     i   ON i.codioart     = g.codcont
      LEFT JOIN ioart1    i1  ON i1.codioart    = g.codcont AND ' ||coalesce(getAnLunaLucru(),'0') || ' BETWEEN i1.ALStart and i1.ALStop
      LEFT JOIN ncont     c   ON c.codcont      = i1.cont
      LEFT JOIN ncatpret  cp  ON cp.codcatpret  = g.codcatpret ' || gSuplJoins || '
    WHERE g.codgest &lt;&gt; 0';

  IF  InStr( gSuplJoins, 'TMP_CAMERE_LST') &gt; 0 THEN
    PERFORM PKG_LIST_BASE_UTILS_UMPLE_TMP_CAMERE_LST();
  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_nomoper_processlist</obj_name>
  <obj_hashval>af7d834ef152f6bc0df56f679dd8ca32</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nomoper_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;
begin
  --Bogdan 15.09.2020
  gSuplCols := 'NOPER OP, NCLASEOP CLOP';

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

  sInsert := 'INSERT INTO '|| tmpName
            || '(CODEXTERN,
                DENUMIRE,
                CLASAOP,
                ACTIV' || coalesce (gUserFields ,'')
            || ')
        SELECT OP.CODEXTERN,
            OP.DENUMIRE,
            CLOP.DEN_CLASEOP,
            case when OP.ACTIV = 1 then ''DA'' else ''NU'' end ' || coalesce (gUserAlias ,'')|| '
          FROM NOPER           OP
            LEFT JOIN NCLASEOP CLOP ON OP.CLASAOP = CLOP.CODCLASEOP '
            || coalesce (gSuplJoins ,'');
  PERFORM LIST_EXECUTE_IMMEDIATE (sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nomoper_setjoinuri</obj_name>
  <obj_hashval>c083dd8687dcbb7782d741a7638bfa2b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nomoper_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 15.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec (current_setting ('PKG_LIST_BASE_NOMOPER.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nompers_setparams</obj_name>
  <obj_hashval>d60c85ea5f201337edc7a6b3c935c7d7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nompers_setparams(adetaliere numeric, aallpers numeric, aallteme numeric, aallcursuri numeric, aperdataplanif numeric, adataini character varying, adatafin character varying, pcodjob1 numeric, agdpr numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  AnLunaIni numeric := 0;
  AnLunafin numeric := 0;
begin
  perform set_config('PKG_LIST_BASE_NOMPERS.vDetaliere'    , aDetaliere::varchar    , false);
  perform set_config('PKG_LIST_BASE_NOMPERS.vAllPers'      , aAllPers::varchar      , false);
  perform set_config('PKG_LIST_BASE_NOMPERS.vAllTeme'      , aAllTeme::varchar      , false);
  perform set_config('PKG_LIST_BASE_NOMPERS.vAllCursuri'   , aAllCursuri::varchar   , false);
  perform set_config('PKG_LIST_BASE_NOMPERS.vPerDataPlanif', aPerDataPlanif::varchar, false);
  perform set_config('PKG_LIST_BASE_NOMPERS.vDataIni'      , aDataIni               , false);
  perform set_config('PKG_LIST_BASE_NOMPERS.vDataFin'      , aDataFin               , false);
  IF pCodJob1 &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1, current_setting('PKG_LIST_BASE_NOMPERS.vDataIni', true)::varchar,
                                               current_setting('PKG_LIST_BASE_NOMPERS.vDataFin', true)::varchar, AnLunaIni, AnLunaFin);
  END IF;
  perform set_config('PKG_LIST_BASE_NOMPERS.vGDPR', COALESCE(aGDPR,1)::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_normeap_setjoinuri</obj_name>
  <obj_hashval>36720c73bad6e144a600476510aea50e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_normeap_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 14.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec (current_setting ('PKG_LIST_BASE_NORMEAP.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_notacantarcom_processlist</obj_name>
  <obj_hashval>2a031719b14a4afa6b253807a605ab25</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacantarcom_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'TMP_ONORCOM_COMENZI TC, TMP_ONORCOM_ARTICOLE TA, COMANDA C, NPARTTR D, NAGENDA SED, NLOCALIT SEDL';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 14.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_NOTACANTARCOM.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || tmpName || ' (
    NrCom, DataCom, Com,
    NrIes, DataIes, Ies,
    Dest, Sediu, Localit, Delegat,
    Art, Net, Brut,
    CantA1, CantA2, CantA3, CantA4, CantA5, CantA6, KgA1, KgA2, KgA3, KgA4, KgA5, KgA6  ' || gUserFields || ')
  SELECT
    TC.Nrcomanda, TC.DataComanda, C.PrefixDoc||C.Nrdoc::varchar||''/''||To_Char(C.DataDoc,''dd.mm.yyyy''),
    TC.NrDoc, TC.DataDoc, CASE WHEN T.CodTransf IS NULL THEN I.PrefixDoc ELSE T.PrefixDoc END||TC.Nrdoc::varchar||''/''||To_Char(TC.DataDoc,''dd.mm.yyyy''),
    TC.DenClient, TC.DenSediu, SEDL.Den_Localit, D.Delegat,
    TA.DenObiect, coalesce(TA.Net,0), coalesce(TA.Brut,0),
    coalesce(TA.A1,0), coalesce(TA.A2,0), coalesce(TA.A3,0), coalesce(TA.A4,0), coalesce(TA.A5,0), coalesce(TA.A6,0),
    coalesce(TA.KGA1,0), coalesce(TA.KGA2,0), coalesce(TA.KGA3,0), coalesce(TA.KGA4,0), coalesce(TA.KGA5,0), coalesce(TA.KGA6,0) ' || gUserAlias || '
  FROM   TMP_ONORCOM_COMENZI TC
        INNER JOIN TMP_ONORCOM_ARTICOLE TA ON TA.CODCOMANDA   = TC.CODCOMANDA
        LEFT  JOIN COMANDA C               ON C.CODCOMANDA    = TC.CODCOMANDA
        LEFT  JOIN IESIRI I                ON I.CODIES        = TC.CODDOC AND I.TIPDOC = TC.TIPDOC
        LEFT  JOIN TRANSF T                ON T.CODTRANSF     = TC.CODDOC AND T.TIPDOC = TC.TIPDOC
        LEFT  JOIN NPARTTR D               ON D.CODPARTTR     = TC.CODDELEGAT
        LEFT  JOIN NAGENDA SED             ON SED.CODAGENDA   = TC.CODSEDIU
        LEFT  JOIN NLOCALIT SEDL           ON SEDL.CODLOCALIT = SED.CODLOCALIT' || gSuplJoins || '
  WHERE TC.GDI = 1 AND coalesce(TA.NET,0) &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_notacantarcom_setjoinuri</obj_name>
  <obj_hashval>8a6dfa37df02918b7dfc497bca5f6aa6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacantarcom_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_NOTACANTARCOM.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_notacantaries_processlist</obj_name>
  <obj_hashval>cd9d8ab001b1f2a6f4a0df9e2267c95e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacantaries_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 := 'iesiri i, iesiri1 i1, nartobj o, cantar c';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodDoc          NUMERIC := current_setting('PKG_LIST_BASE_NOTACANTARIES.vCodDoc', true)::NUMERIC;
BEGIN
  --Adina 24 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_NOTACANTARIES.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
     Art, IDX, Net, Brut,
     CantA1, CantA2, CantA3, CantA4, CantA5, CantA6,
     KgA1, KgA2, KgA3, KgA4, KgA5, KgA6,
     KgP, CantT1, CantT2, KgT1, KgT2  ' || gUserFields || ')';

  sSelect := '
  SELECT
    o.denumire, i1.indexlocal, coalesce(c.net_kg,0), coalesce(c.total_kg,0),
    coalesce(c.amb1_cant,0), coalesce(c.amb2_cant,0), coalesce(c.amb3_cant,0), coalesce(c.amb4_cant,0), coalesce(c.amb5_cant,0), coalesce(c.amb6_cant,0),
    coalesce(c.amb1_kg,0), coalesce(c.amb2_kg,0), coalesce(c.amb3_kg,0), coalesce(c.amb4_kg,0), coalesce(c.amb5_kg,0), coalesce(c.amb6_kg,0),
    coalesce(c.palet_kg,0), coalesce(c.transp1_cant,0), coalesce(c.transp2_cant,0), coalesce(c.transp1_kg,0), coalesce(c.transp2_kg,0) ' || gUserAlias || '
  FROM   iesiri i
        INNER JOIN iesiri1 i1 ON i1.codies   = i.codies
        INNER JOIN cantar  c  ON c.coddoc1   = i1.codies1 AND c.tipdoc = i.tipdoc AND c.codobiect = i1.codobiect
        INNER JOIN nartobj o  ON o.codobiect = c.codobiect' || gSuplJoins || '
  WHERE c.anulat = 0 AND i.codies =' || coalesce(vCodDoc::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_notacantaries_setjoinuri</obj_name>
  <obj_hashval>bbf6d789b53507716c0be4e66ef73ff7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacantaries_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 24 septembrie 2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_NOTACANTARIES.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_notacantaries_setparams</obj_name>
  <obj_hashval>f01425829bc5ebb06ca20785c5388aa6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacantaries_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 24 septembrie 2020
  perform set_config('PKG_LIST_BASE_NOTACANTARIES.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_notacantarintr_processlist</obj_name>
  <obj_hashval>2abdfb2d69222dfb386cf84df5c10216</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacantarintr_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 := 'intrari i, intrari1 i1, nartobj o, cantar c';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodDoc          NUMERIC := current_setting('PKG_LIST_BASE_NOTACANTARINTR.vCodDoc', true)::NUMERIC;
BEGIN
  --Adina 17 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_NOTACANTARINTR.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
     Art, IDX, Net, Brut,
     CantA1, CantA2, CantA3, CantA4, CantA5, CantA6,
     KgA1, KgA2, KgA3, KgA4, KgA5, KgA6,
     KgP, CantT1, CantT2, KgT1, KgT2,
     Client, CmdCli ' || gUserFields || ')';

  sSelect := '
  SELECT
    o.denumire, i1.indexlocal, coalesce(c.net_kg,0), coalesce(c.total_kg,0),
    coalesce(c.amb1_cant,0), coalesce(c.amb2_cant,0), coalesce(c.amb3_cant,0), coalesce(c.amb4_cant,0), coalesce(c.amb5_cant,0), coalesce(c.amb6_cant,0),
    coalesce(c.amb1_kg,0), coalesce(c.amb2_kg,0), coalesce(c.amb3_kg,0), coalesce(c.amb4_kg,0), coalesce(c.amb5_kg,0), coalesce(c.amb6_kg,0),
    coalesce(c.palet_kg,0), coalesce(c.transp1_cant,0), coalesce(c.transp2_cant,0), coalesce(c.transp1_kg,0), coalesce(c.transp2_kg,0),
    P.DEN_PART, CC.NRDOC||''/''||TO_CHAR(CC.DATADOC,''DD.MM.YYYY'') ' || gUserAlias || '
  FROM intrari i
    INNER JOIN intrari1 i1   ON i1.codintr      = i.codintr
    INNER JOIN cantar   c   ON c.coddoc1       = i1.codintr1 AND c.tipdoc = i.tipdoc AND c.codobiect = i1.codobiect
    INNER JOIN nartobj  o   ON o.codobiect     = c.codobiect
    LEFT  JOIN COMANDA1 CC1 ON CC1.CODCOMANDA1 = PKG_COMANDA_DINCMDCLI(I1.CODCMDINT1)
    LEFT  JOIN COMANDA  CC   ON CC.CODCOMANDA   = CC1.CODCOMANDA
    LEFT  JOIN NPART    P   ON P.CODPART       = CC.PARTENER ' || gSuplJoins || '
  WHERE c.anulat = 0 AND i.codintr =' || coalesce(vCodDoc::varchar ,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
  PERFORM pkg_list_base_docintr_SETPARAMS(vCodDoc);
  PERFORM pkg_list_base_docintr_ProcessParams(tmpName);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_notacantarintr_setparams</obj_name>
  <obj_hashval>483e7e080442c8d1564936af5a9f3b04</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacantarintr_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 17 septembrie 2020
  perform set_config('PKG_LIST_BASE_NOTACANTARINTR.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_notacantartransf_processlist</obj_name>
  <obj_hashval>80a4479457c01b17cfce7cb547c83aef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacantartransf_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;
  gSuplCols        VARCHAR := 'transf t, transf1 t1, nartobj o, cantar c';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodDoc          NUMERIC := current_setting('PKG_LIST_BASE_NOTACANTARTRANSF.vCodDoc', true)::NUMERIC;
BEGIN
  --Adina 18 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_NOTACANTARTRANSF.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    Art, IDX, Net, Brut,
    CantA1, CantA2, CantA3,
    CantA4, CantA5, CantA6, KgA1, KgA2, KgA3, KgA4, KgA5, KgA6,
    KgP, CantT1, CantT2, KgT1, KgT2  ' || gUserFields || ')';

  sSelect := '
  SELECT
    o.denumire, t1.indexlocal, coalesce(c.net_kg,0), coalesce(c.total_kg,0),
    coalesce(c.amb1_cant,0), coalesce(c.amb2_cant,0), coalesce(c.amb3_cant,0), coalesce(c.amb4_cant,0), coalesce(c.amb5_cant,0), coalesce(c.amb6_cant,0),
    coalesce(c.amb1_kg,0), coalesce(c.amb2_kg,0), coalesce(c.amb3_kg,0), coalesce(c.amb4_kg,0), coalesce(c.amb5_kg,0), coalesce(c.amb6_kg,0),
    coalesce(c.palet_kg,0), coalesce(c.transp1_cant,0), coalesce(c.transp2_cant,0), coalesce(c.transp1_kg,0), coalesce(c.transp2_kg,0) ' || gUserAlias || '
  FROM transf t
    INNER JOIN transf1 t1 ON t1.codtransf = t.codtransf
    INNER JOIN cantar  c   ON c.coddoc1    = t1.codtransf1 AND c.tipdoc = t.tipdoc
    LEFT  JOIN nartobj o   ON o.codobiect  = c.codobiect' || gSuplJoins || '
  WHERE t.codtransf =' || coalesce(vCodDoc::varchar ,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
  PERFORM pkg_list_base_transfdoc_ProcessParams(vCodDoc);
END;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_notacont_getgnullalias</obj_name>
  <obj_hashval>abc51c32ff8177d4bcfb8e5232c6cf1a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacont_getgnullalias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NOTACONT.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_notacont_getgsuplcols</obj_name>
  <obj_hashval>32a70330c11bc7ba2e8758bcf04d4da6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacont_getgsuplcols(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NOTACONT.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_notacont_getgsupljoins</obj_name>
  <obj_hashval>36249cc8eed2ae10b4293089999e1823</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacont_getgsupljoins(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NOTACONT.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_notacont_getguseralias</obj_name>
  <obj_hashval>1de6470cb1a780da6f30fa5894087f7a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacont_getguseralias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NOTACONT.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_notacont_getguserfields</obj_name>
  <obj_hashval>295e7dac2d9b285d707606b22e2a04c8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacont_getguserfields(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NOTACONT.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_notacont_getvtipdoc</obj_name>
  <obj_hashval>00f548a238eed6fcd45150a848b55873</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacont_getvtipdoc(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NOTACONT.vTipDoc', true)::numeric;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_notacont_gnullalias</obj_name>
  <obj_hashval>da0b0dcedc43f43773c60bd963bf5f90</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacont_gnullalias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NOTACONT.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_notacont_gsuplcols</obj_name>
  <obj_hashval>b807561a1a48895f3ddf7a7a689854b8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacont_gsuplcols(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NOTACONT.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_notacont_guseralias</obj_name>
  <obj_hashval>b4fffbee66a63f72836b3a28fa832d01</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacont_guseralias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NOTACONT.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_notacont_processlist</obj_name>
  <obj_hashval>49a5439672becf8ed28bd3cf09a3878c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacont_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  sInsert         varchar := '';
  vCODUSERID       numeric := 0;
  gSuplCols        VARCHAR := 'NCont cont_d, NCont cont_c, NGest g, Jurnal j, NSubunit sub, CentreCost cc';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vTipDoc          NUMERIC := current_setting('PKG_LIST_BASE_NOTACONT.vTipDoc', true)::NUMERIC;
BEGIN
  --Adina 17 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_NOTACONT.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');


  sInsert :=
  'INSERT INTO ' || TMPNAME || ' (DEBIT,CREDIT,VALOARE,OBS, Doc, Ordine, CentruCost, Subunitatea ' || gUserFields || ')
  SELECT cont_d.simbol debit, cont_c.simbol credit, j.valoare, j.obs, j.Document, j.Codjurnal, cc.Denumire, sub.Den_Subunit ' || gUserAlias || '
  FROM JURNAL j
    INNER JOIN TMP_MANEVRA_LISTE  TMP     on TMP.VALOARE   = J.CodDoc::varchar
    LEFT  JOIN NCont              cont_d  ON j.contd       = cont_d.codcont
    LEFT  JOIN NCont              cont_c  ON j.contc       = cont_c.codcont
    LEFT  JOIN NGest              g       ON j.gest        = g.codgest
    LEFT  JOIN NSubunit           sub     ON j.subunitatea = sub.codsubunit
    LEFT  JOIN CentreCost         cc      ON cc.codcentru  = j.codcentru' || gSuplJoins || '
  WHERE J.TipDoc = ' || coalesce(vTipDoc::varchar,'') || '
    AND J.CodDoc::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODDOC'')';

  IF vTipDoc IN (36, 52) THEN
    sInsert := sInsert || '
    AND J.An*12+J.Luna = ' || coalesce(getANLUNALUCRU()::varchar,'');
  END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  IF  vTipDoc = 35 THEN
    SELECT Max(COALESCE(CODPERS, 0)) INTO vCODUSERID
    FROM   TMP_MANEVRA_LISTE T
          LEFT JOIN NC       ON  NC.CODNC     = T.VALOARE::numeric
          LEFT JOIN NPERS U ON  U.LOGONNAME = NC.USERID
    WHERE T.FILTRU = 'CODDOC';
  END IF;

  FOR v_rec IN (SELECT   COALESCE(U.Nume, '...nedefinit...') UNUME, COALESCE(U.Prenume, '...nedefinit...') UPRENUME,
                        COALESCE(U.CNP,  '...nedefinit...') UCNP,  COALESCE(U.BISERIA,'') || ' ' || COALESCE(U.BINR::varchar ,'') UBI
                FROM NPERS U
                WHERE U.CODPERS = vCODUSERID
               )
  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('Intocmit BI',      v_rec.UBI     );
    EXIT ;
  END LOOP;

  FOR V_REC IN (SELECT STRING_AGG(OBS,',') OBS
                FROM (SELECT  DISTINCT pkg_list_utilfisacont_GetObsDocJurnal(J.CODJURNAL) OBS
                      FROM   JURNAL J
                            INNER JOIN TMP_MANEVRA_LISTE TMP ON  TMP.VALOARE = J.CodDoc::varchar
                      WHERE J.TIPDOC = vTipDoc
                            AND J.CodDoc::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODDOC')
                     ) A_PG
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('OBSERVATII DOCUMENT', v_rec.OBS);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_notacont_setguseralias</obj_name>
  <obj_hashval>a1589d3350850a913e2c6cc59cfb86ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacont_setguseralias(aguseralias character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_NOTACONT.gUserAlias',agUserAlias,false);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_notacont_setvtipdoc</obj_name>
  <obj_hashval>f1c3945c754ab7a5caa494ab13264e4e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacont_setvtipdoc(avtipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_NOTACONT.vTipDoc',avTipDoc::varchar,false);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_notecredit_getdiscv</obj_name>
  <obj_hashval>2d4a272d476c6ac3efd860022e4de2aa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notecredit_getdiscv(INOUT wme_result numeric, INOUT pcodcontract numeric, INOUT pvalm numeric, INOUT pvaltot numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vProcDisc numeric;
  vValDisc  numeric;
  vResult   numeric;
begin
  --Bogdan 08.09.2020
  vResult := 0;
  IF COALESCE (pCodContract, 0) &lt;&gt; 0 THEN
    vProcDisc := (SELECT pkg_notecredit_getproccontractvolum.WME_RESULT FROM pkg_notecredit_getproccontractvolum (NULL,pValTot, pCodContract));
    IF COALESCE (vProcDisc, 0) &lt;&gt; 0 THEN
      vRESULT := pValM * vProcDisc / 100;
    ELSIF COALESCE (pValTot, 0) &lt;&gt; 0 THEN
      vValDisc := (SELECT pkg_notecredit_getvaldisccontractvolum.WME_RESULT FROM pkg_notecredit_getvaldisccontractvolum (NULL,pValTot, pCodContract));
      vRESULT  := pValM / pValTot * vValDisc;
    END IF;
  END IF;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_notecreditt_processlist</obj_name>
  <obj_hashval>fccccc0607296f69ec9131be5778fc09</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notecreditt_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 := '';
   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_NOTECREDITT.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || ' (
    Articol,
    Doc,
    Moneda,
    Termen,
    Sediu,
    Curs,
    ValDoc,
    ValLei,
    ValPlata,
    DocPlata,
    ZilePlata,
    Discount,
    ValoareOld,
    Valoare,
    Obs,
    Den_ClaseDisc,
    Previzionat,
    ProcTVA ' || gUserFields || ')
  SELECT
    tmp.articol,
    tmp.doc,
    tmp.moneda,
    tmp.termen,
    tmp.sediu,
    tmp.curs,
    tmp.valdoc,
    tmp.vallei,
    tmp.valplata,
    tmp.docplata,
    tmp.zileplata,
    tmp.discount,
    tmp.valoareold,
    tmp.valoare,
    tmp.obs,
    cls.den_clasedisc,
    tmp.previzionat,
    tmp.proctva ' || gUserAlias || '
  FROM tmp_notecreditt tmp
       left join nclasedisc cls on cls.codclasedisc = tmp.codclasedisc ' || gSuplJoins || '
  WHERE tmp.CodNCredit = ' || coalesce(current_setting('PKG_LIST_BASE_NOTECREDITT.pCodNoteCredit', true),'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  PERFORM PKG_LIST_BASE_NOTECREDITT_PROCESSPARAMS();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_notecreditt_processparams</obj_name>
  <obj_hashval>2cedcb36c229800afcc48e834556aa7a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notecreditt_processparams()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Adina 01 octombrie 2020
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN (SELECT   nc.nrdoc, nc.datastart, nc.datastop, nc.obs, nc.seriadoc, TO_CHAR(nc.curs, 'fm9G999G999G990D0099') CURS,
                        CASE WHEN  nc.trimestriala = 1 THEN 'DA' ELSE 'NU' END  TRIMESTRIALA,
                        CASE WHEN  nc.inchisa = 1      THEN 'DA' ELSE 'NU' END  INCHISA,
                        p.den_part
                FROM   NOTECREDIT        NC
                      LEFT JOIN NPART   P   ON  NC.CODPART    = P.CODPART
                      LEFT JOIN NMONEDE MON ON  MON.CODMONEDA = NC.CODMONEDA
                WHERE nc.CodNCredit = current_setting('PKG_LIST_BASE_NOTECREDITT.pCodNoteCredit', true)::numeric
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Document - numar',       v_rec.NrDoc::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Document - data start', to_char(v_rec.datastart,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Document - data stop',   to_char(v_rec.datastop,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Document - serie',       v_rec.seriadoc    );
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Trimestriala',           v_rec.trimestriala);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('INCHISA',               v_rec.inchisa     );
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener',               v_rec.den_part    );
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Curs',                   v_rec.curs        );
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_notecreditt_setparams</obj_name>
  <obj_hashval>5251449c6e1271bab57308fe735b83ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notecreditt_setparams(vcodnotecredit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01 octombrie 2020
  perform set_config('PKG_LIST_BASE_NOTECREDITT.pCodNoteCredit',(vCodNoteCredit)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_np_setjoinuri</obj_name>
  <obj_hashval>5664b67bcde9b5bcc9df3bb57935cc6a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_np_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 06.08.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_NP.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ofeproforma_baga_dinamic_cols</obj_name>
  <obj_hashval>61b3dd9f1ac501a978fc0fedd63d0a53</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ofeproforma_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_Rec   record;
  vDen     varchar;
  vNrDC    NUMERIC := current_setting('PKG_LIST_BASE_OFEPROFORMA.vNrDC', true)::numeric;
BEGIN
  --Adina 14.10.2020
  DELETE FROM tmp_dinamic_cols;

  FOR v_Rec 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
                     ) 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(vDen,''));

    INSERT INTO tmp_dinamic_cols(FieldName, Display)
    VALUES ('D' || coalesce(to_char(vNrDC + 2, 'fm999')::varchar ,''), 'Pret/' || coalesce(vDen,''));

    vNrDC := vNrDC + 2;
  END LOOP;

  perform set_config('PKG_LIST_BASE_OFEPROFORMA.vNrDC',(vNrDC)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ofeproforma_setjoinuri</obj_name>
  <obj_hashval>d1e411d4c6b0fcf8828c853802ad2dc6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ofeproforma_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_OFEPROFORMA.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ofeproforma_setparams</obj_name>
  <obj_hashval>4a22f42e99f9bfa1251958e95746265b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ofeproforma_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.10.2020
  perform set_config('PKG_LIST_BASE_OFEPROFORMA.vCodDoc'              ,(pCodDoc)::varchar                                                       ,false);
  perform set_config('PKG_LIST_BASE_OFEPROFORMA.pListareDiscLangaTot' ,fnc_GetValConstanta('ListareDiscLangaTot' , getANLUCRU(), getlunalucru()),false);
  perform set_config('PKG_LIST_BASE_OFEPROFORMA.pListareLiniiDiscPart',fnc_GetValConstanta('ListareLiniiDiscPart', getANLUCRU(), getlunalucru()),false);
  perform set_config('PKG_LIST_BASE_OFEPROFORMA.pListareUMAmbPretCant',fnc_GetValConstanta('ListareUMAmbPretCant', getANLUCRU(), getlunalucru()),false);
  perform set_config('PKG_LIST_BASE_OFEPROFORMA.pBancaCursPUV'        ,fnc_GetValConstanta('BancaCursPUV'        , getANLUCRU(), getlunalucru()),false);
  perform set_config('PKG_LIST_BASE_OFEPROFORMA.vNrDC'                ,(0)::varchar                                                             ,false);

  IF  current_setting('PKG_LIST_BASE_OFEPROFORMA.pListareUMAmbPretCant', true) = '1'   THEN
    PERFORM pkg_list_base_ofeproforma_BAGA_DINAMIC_COLS();
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ofertadoc_getcodoferta</obj_name>
  <obj_hashval>adeef8a090d9f0373fd87216f38bd0e5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ofertadoc_getcodoferta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01.10.2020
  WME_Result :=  current_setting('PKG_LIST_BASE_OFERTADOC.vCodOferta', true)::numeric;
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ofertadoc_getcodoferta</obj_name>
  <obj_hashval>d480af85a5c51bc7b5a3d148b6690106</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ofertadoc_getcodoferta()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01.10.2020
  RETURN current_setting('PKG_LIST_BASE_OFERTADOC.vCodOferta', true)::numeric;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ofertadoc_getcodoferta1furn</obj_name>
  <obj_hashval>3681401a62164673131bebf1ed97a989</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ofertadoc_getcodoferta1furn(acodobiect numeric, adatastart date, adataend date, acantmin numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  vCodOferta1 numeric;
BEGIN
  --Adina 01.10.2020
  perform set_config('PKG_LIST_BASE_OFERTADOC.vCodOferta',(0)::varchar,false);

  FOR v_rec IN (SELECT O1.CODOFERTA1
                FROM   OFERTA1 O1
                      INNER JOIN OFERTA O ON  O.CODOFERTA = O1.CODOFERTA
                WHERE O.TIPDOC = 51 AND  O1.CODOBIECT = aCodObiect AND  O1.CANTMIN &lt;= aCantMin AND
                      (O.DATASTART BETWEEN aDataStart AND aDataEnd OR O.DATAEND BETWEEN aDataStart AND aDataEnd)  AND
                      CASE WHEN  Coalesce(o.moneda, 0)=0 THEN O1.PRET
                           ELSE (PKG_LIST_BASE_UTILS_GETCURSREFERINTA(o.moneda, (fnc_GetValConstanta('BancaCursPUV', getANLUCRU(), getLUNALUCRU()))::numeric, to_char(aDataEnd,'dd.mm.yyyy'))) * O1.PRET END
                                 = (  SELECT MAX(CASE WHEN  Coalesce(oo.moneda, 0) &gt; 0 THEN (PKG_LIST_BASE_UTILS_GETCURSREFERINTA(oo.moneda, (fnc_GetValConstanta('BancaCursPUV', getANLUCRU(), getLUNALUCRU()))::numeric, to_char(aDataEnd,'dd.mm.yyyy'))) * O2.PRET
                                                     ELSE O2.PRET
                                               END
                                             )
                                    FROM   OFERTA1 O2
                                          INNER JOIN OFERTA OO ON  OO.CODOFERTA = O2.CODOFERTA
                                    WHERE OO.TIPDOC = 51 AND  O2.CODOBIECT = aCodObiect AND  O2.CANTMIN &lt;= aCantMin AND
                                          (OO.DATASTART BETWEEN aDataStart AND aDataEnd OR OO.DATAEND BETWEEN aDataStart AND aDataEnd)
                                   )
                )
  LOOP
    vCodOferta1 := v_rec.codoferta1;
    EXIT ;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ofertadoc_getcodoferta1furn</obj_name>
  <obj_hashval>a1ef4a2d21b1e891039e97122ff4c2c5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ofertadoc_getcodoferta1furn(INOUT wme_result numeric, INOUT acodobiect numeric, INOUT adatastart date, INOUT adataend date, INOUT acantmin numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  vCodOferta1 numeric;
BEGIN
  --Adina 01.10.2020
  perform set_config('PKG_LIST_BASE_OFERTADOC.vCodOferta',(0)::varchar,false);

  FOR v_rec IN (SELECT O1.CODOFERTA1
                FROM   OFERTA1 O1
                      INNER JOIN OFERTA O ON  O.CODOFERTA = O1.CODOFERTA
                WHERE O.TIPDOC = 51 AND  O1.CODOBIECT = aCodObiect AND  O1.CANTMIN &lt;= aCantMin AND
                      (O.DATASTART BETWEEN aDataStart AND aDataEnd OR O.DATAEND BETWEEN aDataStart AND aDataEnd)  AND
                      CASE WHEN  Coalesce(o.moneda, 0)=0 THEN O1.PRET
                           ELSE (PKG_LIST_BASE_UTILS_GETCURSREFERINTA(o.moneda, (fnc_GetValConstanta('BancaCursPUV', getANLUCRU(), getLUNALUCRU()))::numeric, to_char(aDataEnd,'dd.mm.yyyy'))) * O1.PRET END
                                 = (  SELECT MAX(CASE WHEN  Coalesce(oo.moneda, 0) &gt; 0 THEN (PKG_LIST_BASE_UTILS_GETCURSREFERINTA(oo.moneda, (fnc_GetValConstanta('BancaCursPUV', getANLUCRU(), getLUNALUCRU()))::numeric, to_char(aDataEnd,'dd.mm.yyyy'))) * O2.PRET
                                                     ELSE O2.PRET
                                               END
                                             )
                                    FROM   OFERTA1 O2
                                          INNER JOIN OFERTA OO ON  OO.CODOFERTA = O2.CODOFERTA
                                    WHERE OO.TIPDOC = 51 AND  O2.CODOBIECT = aCodObiect AND  O2.CANTMIN &lt;= aCantMin AND
                                          (OO.DATASTART BETWEEN aDataStart AND aDataEnd OR OO.DATAEND BETWEEN aDataStart AND aDataEnd)
                                   )
                )
  LOOP
    vCodOferta1 := v_rec.codoferta1;
    EXIT ;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_oferterac_add_list_params</obj_name>
  <obj_hashval>3bfef053899aed1adcba6559d58115f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_oferterac_add_list_params()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Adina 14.10.2020
  FOR V_REC IN (SELECT   C.OBS, NP.DEN_PART, NA.OBS OBSSEDIU, NS.DEN_SUBUNIT, NG.DEN_GEST,
                        CASE WHEN  P.TIP = 0 THEN 'zile'
                             WHEN  P.TIP = 1 THEN 'km'
                             WHEN  P.TIP = 2 THEN 'ore'
                             WHEN  P.TIP = 3 THEN 'buc'
                         END  TIPOFERTA, NM.DEN_MONEDA
                FROM   RAC_CATP C
                      INNER JOIN Rac_CatP1 C1 ON  C1.CODRAC_CatP = COALESCE(C.CODRAC_CatP  , 0)
                      INNER JOIN Rac_P P      ON  P.CODRAC_P     = COALESCE(C1.CODRAC_P    , 0)
                      INNER JOIN Rac_P0 P0    ON  P0.CODRAC_P    = COALESCE(P.CODRAC_P     , 0)
                      INNER JOIN Rac_P1 P1    ON  P1.CODRAC_P0   = COALESCE(P0.CODRAC_P0   , 0)
                      INNER JOIN NPART NP     ON  NP.CODPART     = COALESCE(C.CODPARTENER  , 0)
                      INNER JOIN NAgenda NA   ON  NA.CODAGENDA   = COALESCE(C.CODSEDIU     , 0)
                      INNER JOIN NGest NG     ON  NG.CODGEST     = COALESCE(C.CODGEST      , 0)
                      INNER JOIN NSubunit NS  ON  NS.CODSUBUNIT  = COALESCE(C.CODSUBUNITATE, 0)
                      INNER JOIN NMonede NM   ON  NM.CODMONEDA   = COALESCE(P.MONEDA       , 0)
                WHERE C.CODRAC_CATP = current_setting('PKG_LIST_BASE_OFERTERAC.vCodDoc', true)::numeric
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Denumire oferta', v_rec.OBS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener',        v_rec.DEN_PART);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Sediu',           v_rec.OBSSEDIU);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Subunitate',      v_rec.DEN_SUBUNIT);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Gestiune',        v_rec.DEN_GEST);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Tip oferta',      v_rec.TIPOFERTA);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Moneda',          v_rec.DEN_MONEDA);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_oferterac_processlist</obj_name>
  <obj_hashval>d1d99b539a5aa1ef4f484d6a4b09c83e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_oferterac_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
  sSelect varchar := '';
BEGIN
  --Florin 16.04.2024 - fixat 61686
  --Adina 14.10.2020
  sInsert :=
  'INSERT INTO ' || tmpName || '(
          PART,
          SEDIU,
          GEST,
          SUBUNIT,
          DATASTARTcat,
          DATASTOPcat,
          OBS,
          TIP,
          MONEDA,
          DATASTARTp,
          Grupa,
          I1,
          P1,
          I2,
          P2,
          I3,
          P3,
          I4,
          P4,
          I5,
          P5,
          I6,
          P6,
          VALFIXA
  )';

  sSelect := '
  SELECT
    NP.DEN_PART,
    NA.OBS,
    NG.DEN_GEST,
    NS.DEN_SUBUNIT,
    C.DATASTART CatStart,
    C.DATASTOP CatStop,
    C.OBS AS Interval,
    Case when P.TIP = 0 THEN ''zile''
         when P.TIP = 1 THEN ''km''
         when P.TIP = 2 THEN ''ore''
         when P.TIP = 3 THEN ''buc''
    end,
    NM.DEN_MONEDA,
    P0.DATASTART,
    G.DENUMIRE Grupa,
    P.I1,
    P1.P1,
    P.I2,
    P1.P2,
    P.I3,
    P1.P3,
    P.I4,
    P1.P4,
    P.I5,
    P1.P5,
    P.I6,
    P1.P6,
    P1.FIX
  FROM   Rac_CatP C
        INNER JOIN Rac_CatP1 C1 on C1.CODRAC_CatP = coalesce(C.CODRAC_CatP  ,0)
        INNER JOIN Rac_P P      on P.CODRAC_P     = coalesce(C1.CODRAC_P    ,0)
        INNER JOIN Rac_P0 P0    on P0.CODRAC_P    = coalesce(P.CODRAC_P     ,0)
        INNER JOIN Rac_P1 P1    on P1.CODRAC_P0   = coalesce(P0.CODRAC_P0   ,0)
        INNER JOIN NPART NP     on NP.CODPART     = coalesce(C.CODPARTENER  ,0)
        INNER JOIN NAgenda NA   on NA.CODAGENDA   = coalesce(C.CODSEDIU     ,0)
        INNER JOIN NGest NG     on NG.CODGEST     = coalesce(C.CODGEST      ,0)
        INNER JOIN NSubunit NS  on NS.CODSUBUNIT  = coalesce(C.CODSUBUNITATE,0)
        INNER JOIN NMonede NM   on NM.CODMONEDA   = coalesce(P.MONEDA       ,0)
        INNER JOIN GRECHIV G    ON G.CODGRECHIV   = coalesce(P1.CODGRUPA    ,0)
  WHERE C.CODRAC_CATP = ' || coalesce(current_setting('PKG_LIST_BASE_OFERTERAC.vCodDoc', true)::numeric::varchar ,'');

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_oferterac_setjoinuri</obj_name>
  <obj_hashval>5729364cecee03843674e180625c8619</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_oferterac_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.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_oferterac_setparams</obj_name>
  <obj_hashval>3e532ea04793060f098cb9db4af4bc44</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_oferterac_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.10.2020
  perform set_config('PKG_LIST_BASE_OFERTERAC.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_oportunitati_umpletmplista</obj_name>
  <obj_hashval>55d4a6b0b3b8483c3e43e7ed092a812f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_oportunitati_umpletmplista()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_P     RECORD;
  V_REC   RECORD;
  aAlStop numeric;
  aMax    numeric;
BEGIN
  --Adina 28.04.2021 - sinc.Oracle din 27.04.2021
  FOR V_P IN (SELECT CODPART FROM NPART WHERE CODPART &gt; 0) LOOP
    FOR V_REC IN (SELECT CRM1.CODPART, CRM1.ANSTART * 12 + CRM1.LUNASTART ALSTART, ACT.DEN_ACTIVIT,
                         ROW_NUMBER() OVER (PARTITION BY CRM1.CODPART, CRM1.ANSTART, CRM1.LUNASTART ORDER BY PACT.CODACTIVIT) INDEXLOCAL
                  FROM NPART1CRM CRM1
                       INNER JOIN NPARTACTIVIT PACT ON  PACT.CODPART1CRM = CRM1.CODPART1CRM
                       INNER JOIN NACTIVIT     ACT  ON  ACT.CODACTIVIT   = PACT.CODACTIVIT
                  WHERE CRM1.CODPART = V_P.CODPART
                  ORDER BY CRM1.ANSTART , CRM1.LUNASTART
                 )
    LOOP
      SELECT max(anstart * 12 + lunastart) INTO aMax FROM npart1crm WHERE codpart = v_p.codpart;

      IF  aMax = v_rec.alstart THEN
        aAlStop := 9999 * 12 + 12;
      ELSE
        SELECT min(anstart * 12 + lunastart) - 1 INTO aAlStop FROM npart1crm WHERE codpart = v_p.codpart and  anstart * 12 + lunastart &gt; v_rec.alstart;
      END IF;

      INSERT INTO TMP_LST_PART1CRM(CODPART, INDEXLOCAL, DEN_ACTIVIT, ALSTART, ALSTOP)
      VALUES(v_p.codpart, v_rec.indexlocal, v_rec.den_activit, v_rec.alstart, aAlStop);
    END LOOP;
  END LOOP;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_parcauto_setjoinuri</obj_name>
  <obj_hashval>098e9926068dc23648363c6c9e33262d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_parcauto_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 15.06.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_PARCAUTO.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_parcautoanv_setjoinuri</obj_name>
  <obj_hashval>5bb410d8c2c008417c741fbbe7a5e9a3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_parcautoanv_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 15.06.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_PARCAUTOANV.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_parcautoaut_processlist</obj_name>
  <obj_hashval>586de7cf79d49cafc6bd757f959abd95</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_parcautoaut_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  gSuplCols   varchar := 'nparcaut pa, nparc2 p2, npers s, mifix mf, nirstoc ns, ngest g, nartobj o ';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 16.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_PARCAUTOAUT.gSuplCols', gSuplCols, FALSE);

  sInsert := 'INSERT INTO ' || tmpName || '(
      NAV_CodDoc,
      NAV_TipDoc,
      Den, NrInv, Sofer, Gest, Tip,
      NrInreg, DataInreg, Marca, Model, AnFab, SerieC, Culoare, Lung, Lat, Inalt,
      TipMotor, SerieMotor, Combustibil, Cilindree, Putere, Rezervor, CMM, CMU, CME,
      TipIncarc, Greutate, MasaMax, MasaUtil, MasaURDF, MasaURFDF,
      VolumUtil, LocTot, LocFata, LocSpate, LocPic,
      Aut, Sn, Eliberat, Expira, Atentie ' || gUserFields || ')
    WITH mf1 AS (SELECT codmifix, Max(codnirstoc) codnirstoc FROM mifix1 GROUP BY codmifix)
    SELECT
      pa.codnparcaut, 505,
      o.denumire, pa.nrinv, (s.nume||'' ''||s.prenume) sofer, g.den_gest, (CASE WHEN pa.tip = 0 THEN ''TRACTAT'' ELSE ''MOTORIZAT'' END) tip,
      pa.nrinreg, pa.datainreg, ma.marca, mo.model, pa.anf, pa.seriec, pa.culoare, pa.lung, pa.lat, pa.inalt,
      pa.tipmotor, pa.seriem, pa.sursae, pa.cilindree, pa.putere, pa.rezervor, pa.cmm, pa.cmu, pa.cme,
      (CASE WHEN tipincarc = 1 THEN ''Marfa'' WHEN tipincarc = 2 THEN ''Persoane'' WHEN tipincarc = 3 THEN ''Mixta'' END) tipincarc, pa.greutate, pa.masam, pa.masau, pa.masaurdf, pa.masaurfdf,
      pa.volumu, pa.loct, pa.locf, pa.locs, pa.locp,
      COALESCE(aut.denumire, auti.denumire), p2.sn, p2.eliberat, p2.expira, p2.atentie ' || gUserAlias || '
    FROM nparcaut pa
      INNER JOIN nparc2           p2   ON p2.cod             = pa.codnparcaut
      LEFT  JOIN nautorizatiiauto aut  ON aut.codautorizatii = p2.doc
      LEFT  JOIN intrari1         i1   on p2.codintr1        = i1.codintr1
      LEFT  JOIN nautorizatiiauto auti ON auti.codserviciu   = i1.codobiect
      LEFT  JOIN npers            s    on s.codpers          = pa.sofer
      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;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_parcautoaut_setjoinuri</obj_name>
  <obj_hashval>6c932780924c4a8759a584a84e573dbb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_parcautoaut_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 15.06.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_PARCAUTOAUT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_parcautocarb_baga_dinamic_cols</obj_name>
  <obj_hashval>4cbe537cee79a45cadb91da46da97b13</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_parcautocarb_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAn     numeric;
  vLuna   numeric;
  vNrZile numeric := 31;
  vTipA   numeric := 2;
  vTipB   numeric := 1;
BEGIN
  --Adina 06.01.2021 tichet 41989 - modif. linia 48 (am pus "vTipA AND vTipB" in loc de "1 AND 2")
  --Florin 16.09.2020
  DELETE FROM tmp_dinamic_cols;

  IF current_setting('PKG_LIST_BASE_PARCAUTOCARB.vDistZile', true)::BOOLEAN OR current_setting('PKG_LIST_BASE_PARCAUTOCARB.vConsZile', true)::BOOLEAN THEN
    SELECT pkg_list_base_utils_ExtractAnLuna.pAn, pkg_list_base_utils_ExtractAnLuna.pLUna
    FROM pkg_list_base_utils_ExtractAnLuna(current_setting('PKG_LIST_BASE_PARCAUTOCARB.vAnLunaIni', true)::numeric, vAn, vLuna) INTO vAn, vLuna;
    vNrZile := EXTRACT(DAY FROM LAST_DAY(To_Date(coalesce(vAn,0) || '.' || coalesce(vLuna,0), 'yyyy.mm')));

    IF current_setting('PKG_LIST_BASE_PARCAUTOCARB.vDistZile', true)::BOOLEAN THEN
      vTipA := 1;
    END IF;

    IF current_setting('PKG_LIST_BASE_PARCAUTOCARB.vConsZile', true)::BOOLEAN THEN
      vTipB := 2;
    END IF;

    INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, COD, COD2)
    WITH RECURSIVE z(ZI) AS(
       SELECT 1 ZI
       UNION ALL
       SELECT ZI + 1 from Z WHERE zi &lt;= 30
    ),
    TT AS (SELECT * FROM (
                          WITH RECURSIVE T(TIP) AS(
                           SELECT 1 TIP
                           UNION ALL
                           SELECT TIP + 1 FROM T WHERE TIP &lt;= 2)
                           SELECT * FROM T
                         ) A_PG
    )
    SELECT 'D'|| COALESCE(ROW_NUMBER() OVER()::VARCHAR) AS ROWNUM, CASE WHEN TIP = 1 THEN 'KM/' ELSE 'CONS./' END||ZI, ROW_NUMBER() OVER(), ZI, TIP
      FROM (
            SELECT Z.ZI, TT.TIP
            FROM Z
            CROSS JOIN TT
            WHERE TT.TIP BETWEEN vTipA AND vTipB
            ORDER BY Z.ZI , TT.TIP
           ) B_PG;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_parcautocarb_setjoinuri</obj_name>
  <obj_hashval>7338a0f7857966b32c050f3441a13cbe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_parcautocarb_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 15.06.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_PARCAUTOCARB.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_parcautocarb_setparams</obj_name>
  <obj_hashval>e17e5fa4a89b52f5b4d950d4088ec288</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_parcautocarb_setparams(panlunaini numeric, panlunafin numeric, pdistzile numeric, pconszile numeric, v_codjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  dDataS date;
  dDataF date;
BEGIN
  --Florin 16.09.2020
  PERFORM set_config('PKG_LIST_BASE_PARCAUTOCARB.vAnLunaIni', pAnLunaIni::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_PARCAUTOCARB.vAnLunaFin', pAnLunaFin::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_PARCAUTOCARB.vAnLunaIni', true)::numeric, current_setting('PKG_LIST_BASE_PARCAUTOCARB.vAnLunaFin', true)::numeric);
  END IF;

  PERFORM set_config('PKG_LIST_BASE_PARCAUTOCARB.vDistZile', (COALESCE(pDistZile,0) = 1 AND (pAnLunaIni = pAnLunaFin))::varchar,false);
  PERFORM set_config('PKG_LIST_BASE_PARCAUTOCARB.vConsZile', (COALESCE(pConsZile,0) = 1 AND (pAnLunaIni = pAnLunaFin))::varchar,false);

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_parcautochelt_baga_dinamic_cols</obj_name>
  <obj_hashval>2400059f1776eba77d0060894f207323</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_parcautochelt_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 16.09.2020
  DELETE FROM tmp_dinamic_cols;

  INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, Cod, Cod2)
  VALUES('CC0', 'Total', 0, 0, 0);

  INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal, Cod, Cod2)
  SELECT 'CC' || coalesce(row_number() over()::varchar,''), Denumire, (row_number() over()) as ROWNUM, CodCentru, 0
  FROM (SELECT CODCENTRU, DENUMIRE
        FROM CENTRECOST
        WHERE CODCENTRU::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE Upper(FILTRU) = 'CODCENTRU') AND CODCENTRU &gt; 0
        ORDER BY CODCENTRU
       ) A_PG;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_parcautochelt_contcodcentru</obj_name>
  <obj_hashval>aa25a1afa9646d071b64ebd6a10b5f4b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_parcautochelt_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 17.09.2020
  vResult := COALESCE(pCodAuto, 0);

  IF  vResult = 0 THEN
    vResult := (SELECT PKG_LIST_BASE_PARCAUTOCHELT_xCodCentru.WME_RESULT FROM PKG_LIST_BASE_PARCAUTOCHELT_xCodCentru(NULL,pCodCont1, pAnLuna));
  END IF;

  IF vResult = 0 AND  COALESCE(pCodCont2, 0) &lt;&gt; 0 THEN
    vResult := (SELECT PKG_LIST_BASE_PARCAUTOCHELT_xCodCentru.WME_RESULT FROM PKG_LIST_BASE_PARCAUTOCHELT_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_parcautochelt_icontcodcentru</obj_name>
  <obj_hashval>2015b8e5da12fce4897b062861d250eb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_parcautochelt_icontcodcentru(INOUT wme_result numeric, INOUT pcodauto numeric, INOUT panluna numeric, INOUT picont numeric, INOUT pcodpart numeric, INOUT psemnif numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vResult numeric;
BEGIN
  --Florin 17.09.2020
  --Florin 21.12.2020 - fixat #41753
  vResult := COALESCE(pCodAuto, 0);

  IF vResult = 0 THEN
    vResult := (SELECT PKG_LIST_BASE_PARCAUTOCHELT_xCodCentru.WME_RESULT FROM PKG_LIST_BASE_PARCAUTOCHELT_xCodCentru(NULL, pkg_list_base_utils_iCont_CodCont(pICont, pCodPart, pAnLuna, pSemnif), pAnLuna));
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_parcautochelt_setparams</obj_name>
  <obj_hashval>aed98565e0b8c3c3b42512c2accd00de</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_parcautochelt_setparams(panlunaini numeric, panlunafin numeric, pcc0 numeric, v_codjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
  sDataS     varchar;
  sDataF     varchar;
  xAn        numeric;
  xLuna      numeric;
  gDataS     date;
  gDataF     date;
BEGIN
  --Florin 16.09.2020
  xLunaAnIni := pAnLunaIni;
  xLunaAnFin := pAnLunaFin;

  IF Trunc(xLunaAnIni / 12) = xLunaAnIni / 12 THEN
    xAn   := xLunaAnIni / 12 - 1;
    xLuna := 12;
  ELSE
    xAn   := Trunc(xLunaAnIni / 12);
    xLuna := xLunaAnIni - Trunc(xLunaAnIni / 12) * 12;
  END IF;

  sDataS := '01.' || coalesce(LPAD((trunc(xLuna))::varchar, 2, '0'),'') || '.' || coalesce((xAn)::varchar,'');

  IF Trunc(xLunaAnFin / 12) = xLunaAnFin / 12 THEN
    xAn   := xLunaAnFin / 12 - 1;
    xLuna := 12;
  ELSE
    xAn   := Trunc(xLunaAnFin / 12);
    xLuna := xLunaAnFin - Trunc(xLunaAnFin / 12) * 12;
  END IF;

  sDataF := to_char(LAST_DAY(to_date('01.' || coalesce(LPAD((trunc(xLuna))::varchar, 2, '0'),'') || '.' || coalesce((xAn)::varchar,''), 'dd.mm.yyyy')), 'dd.mm.yyyy');

  PERFORM set_config('PKG_LIST_BASE_PARCAUTOCHELT.vCC0', COALESCE(pCC0,0)::varchar, FALSE);

  PERFORM pkg_list_base_parcautochelt_BAGA_DINAMIC_COLS();

  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_PARCAUTOCHELT.vAnLunaIni', xLunaAnIni::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_PARCAUTOCHELT.vAnLunaFin', xLunaAnFin::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_PARCAUTOCHELT.gDataS', sDataS, FALSE);
  PERFORM set_config('PKG_LIST_BASE_PARCAUTOCHELT.gDataF', sDataF, FALSE);
  PERFORM PKG_ORA_LISTS_SET_INTERVAL_LISTARE(gDataS, gDataF);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_parcautochelt_xcodcentru</obj_name>
  <obj_hashval>7e5f0b6d48d37497e53f84aa55ad0f46</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_parcautochelt_xcodcentru(INOUT wme_result numeric, INOUT pcodcont numeric, INOUT panluna numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vResult numeric;
BEGIN
  --Adina 10.05.2021 - alstart,alstop (prc_al_check e pus in processlist)
  --Adina 22.12.2020
  --Florin 17.09.2020

  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_parcautointerv_setjoinuri</obj_name>
  <obj_hashval>07e8c23b4caa384c241fdfddd2a2f98a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_parcautointerv_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 15.06.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_PARCAUTOINTERV.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_penalitati_processlist</obj_name>
  <obj_hashval>724cb357f11a5bc2d5670ce7df9e8c72</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_penalitati_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 11.09.2020
  gSuplCols := '';

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

  IF (PKG_LIST_SELDATA_ChkExtra1 ()) THEN
    PERFORM PKG_NOTECREDIT_GEN_TMP_PEN (0, TO_CHAR ( PKG_LIST_SELDATA_GetDataRef() , 'DD.MM.YYYY') , 0, 1, 1, TO_CHAR ( PKG_LIST_SELDATA_GetDataRef(), 'DD.MM.YYYY') , 1, 1);
  ELSE
    PERFORM PKG_NOTECREDIT_GEN_TMP_PEN (0, TO_CHAR ( PKG_LIST_SELDATA_GetDataRef() , 'DD.MM.YYYY') , 0, 1, 1, TO_CHAR ( PKG_LIST_SELDATA_GetDataRef() , 'DD.MM.YYYY') , 1);
  END IF;

  sInsert := 'INSERT INTO '|| TMPNAME
          || ' (
          CODOBLIGPIF,
          PREFIXDOC,
          NRDOC,
          DATADOC,
          VALDOC,
          TERMEN,
          REST,
          MAJORARI,
          LOCATIE,
          DEN_PART,
          DEN_SUBUNIT,
          MONEDA,
          MAJANTERIOARE,
          DATA_LAST_FACTMAJ,
          DATA_LAST_PLATA,
          GRATIEDOC,
          STORNO,
          SCADENTAV,
          VALMAJ,
          RESTLADATA,
          ZILE '
          || coalesce (gUserFields ,'')
          || ')
      SELECT tmp.CODOBLIGPIF,
        tmp.PREFIXDOC,
        tmp.NRDOC,
        tmp.DATADOC,
        tmp.VALDOC,
        tmp.TERMEN,
        tmp.REST,
        tmp.MAJORARI,
        tmp.LOCATIE,
        tmp.DEN_PART,
        tmp.DEN_SUBUNIT,
        m.simbol MONEDA,
        tmp.MAJANTERIOARE,
        tmp.DATA_LAST_FACTMAJ,
        tmp.DATA_LAST_PLATA,
        tmp.GRATIEDOC,
        tmp.STORNO,
        tmp.SCADENTAV,
        tmp.VALMAJ,
        tmp.RESTLADATA,
        tmp.Zile '
          || coalesce (gUserAlias ,'') || '
      FROM tmp_gen_penalitati tmp
        left join nmonede   m on m.codmoneda = coalesce (tmp.moneda,0) '
          || coalesce (gSuplJoins ,'');
  PERFORM LIST_EXECUTE_IMMEDIATE (sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_perscontact_processlist</obj_name>
  <obj_hashval>7284865e78b850d7c7fba03b6c6223f9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_perscontact_processlist(tmp_name character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  gSuplCols   varchar := 'npart p, nperscontact pc, nagenda a, npers ag, nparttr del';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
begin
  --Florin 15.03.2023 - fixat 57645
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_PERSCONTACT.gSuplCols', gSuplCols, false);

  sInsert := 'INSERT INTO ' || tmp_name || ' (
      DEN_PART,
      ADRESAP,
      NUME, PRENUME, TELEFON, EMAIL, FUNCTIE, DATANASTERE, ID, RZONA' || gUserFields || ')
    SELECT
      p.den_part,
      (select getadresa.wme_result from getadresa('''', a.sector, a.strada, a.nr1, a.nr2, a.bloc, a.scara, a.etaj, a.apart, a.codpostal)),
      pc.nume, pc.prenume, pc.telefon, pc.email, pc.functie, pc.datanastere, pc.id, case when pc.rzona = 1 then ''Da'' else ''Nu'' end RZONA' || gUserAlias || '
    FROM npart p
      INNER JOIN nperscontact pc  ON p.codpart     = pc.codpart
      LEFT  JOIN nagenda      a   ON a.codpart     = p.codpart AND A.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(A.INACTIV, 0) = 0
      LEFT  JOIN npers        ag  ON ag.codpers    = a.codagent
      left  join nparttr      del on del.codparttr = p.codpart - p.codpart '|| gSuplJoins ||'
    UNION ALL
    SELECT
      p.den_part,
      (select getadresa.wme_result from getadresa('''', a.sector, a.strada, a.nr1, a.nr2, a.bloc, a.scara, a.etaj, a.apart, a.codpostal)),
      del.delegat, cast(null as varchar(200)), del.telefon, del.email, cast(null as varchar(100)), del.datadoc, cast(null as NUMERIC(27,7)),''Da'' ' || gUserAlias || '
    FROM NPARTTR DEL
      INNER JOIN npart        p  ON p.codpart   = del.codpart
      LEFT  JOIN nagenda      a  ON a.codpart   = del.codpart AND A.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(A.INACTIV, 0) = 0
      LEFT  JOIN npers        ag ON ag.codpers  = a.codagent
      left  join nperscontact pc on pc.codpersc = p.codpart - p.codpart' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_persleg_processlist</obj_name>
  <obj_hashval>ec1038d6d458a7d8997c9321530d0648</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_persleg_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
BEGIN
  --Adina 16.10.2020 (??)
  sInsert :=
  'INSERT INTO ' || tmpName || ' (DEN_PART,NUME,PRENUME,TELEFON,EMAIL,FUNCTIE,DATANASTERE,RZONA,ID) ' ||
  'SELECT  np.den_part, ' ||
          'pc.nume, pc.prenume, pc.telefon, pc.email, pc.functie, pc.datanastere, ' ||
          '(case pc.rzona when 1 then ''Da'' when 0 then ''Nu'' end) rzona,pc.ID  ' ||
  'FROM npart np INNER JOIN nperscontact pc ON np.codpart = pc.codpart ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_persleg_setjoinuri</obj_name>
  <obj_hashval>2b9c697e0499509d4d3dc80a659d1305</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_persleg_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec('');
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_pf_locm_setjoinuri</obj_name>
  <obj_hashval>ea5dfb75f595742d7991d59e49237160</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pf_locm_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 14.09.2020
PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_PF_LOCM.gSuplCols', true));
PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_pf_luna_setjoinuri</obj_name>
  <obj_hashval>787cf2d8645032d01d5702086e566175</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pf_luna_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 14.09.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_PF_LUNA.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_pf_processlist</obj_name>
  <obj_hashval>ae98cdb9c62a8500b8be08558c611ed2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pf_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  vTabla      varchar;
  gSuplCols   varchar := 'NGEST NG, COMANDA1 C1, COMANDA C, NARTOBJ NOBJ, NUM1 NUM1, COMANDA1 C1CLIENT, COMANDA CCLIENT, NPART NP, PROGRAMF1 PF1';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 20.06.2024 - fixat 62409
  --Florin 11.01.2021
  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,  vTabla     , 'CCV' , 'CCV.CODCOMANDA = CCLIENT.CODCOMANDA',NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_PF.gSuplCols', gSuplCols, false);

  sInsert := 'INSERT INTO ' || TMPNAME || '(
      PRIORITATE,
      CANTPROGRAMAT,
      DEN_GEST,
      NRCMD,
      DEN_OBIECT,
      CODEXTERN,
      UM,
      TERMENEXEC,
      DEN_CLIENT,
      TERMENLIVR,
      DURATA,
      DataOraStart,
      DataOraStop,
      Formatie,
      Schimb,
      Rest
      ' || gUserFields || ')
    SELECT PF1.PRIORITATE,
      PF1.CANTPROGRAMAT,
      NG.DEN_GEST,
      C.NRDOC,
      NOBJ.DENUMIRE,
      NOBJ.CODEXTERN,
      NUM1.DEN_UM1,
      COALESCE(PF1.TERMEN,C1.TERMEN),
      NP.DEN_PART,
      c1client.termen,
      PF1.CANTPROGRAMAT * NUM1.Paritate / PC.CANT * PC.DURATA,
      ADD_DAYS(PF.VDELA::date,
      (- (PF1.CANTPROGRAMAT * NUM1.Paritate / PC.CANT * (PC.DURATA/60) / 24)
      + SUM(PF1.CANTPROGRAMAT * NUM1.Paritate / PC.CANT * (PC.DURATA/60) / 24)
      over (PARTITION BY PF1.CODGEST ORDER BY PF1.PRIORITATE ROWS BETWEEN unbounded preceding AND CURRENT ROW ))::INTEGER),
      ADD_DAYS(PF.VDELA::date,
      (SUM(PF1.CANTPROGRAMAT * NUM1.Paritate / PC.CANT * (PC.DURATA/60) / 24)
      over (PARTITION BY PF1.CODGEST ORDER BY PF1.PRIORITATE ROWS BETWEEN unbounded preceding AND CURRENT ROW ))::INTEGER),
      FR.Den_Formatie,
      PF1.Schimb,
      PF1.CANTPROGRAMAT - COALESCE((select sum(l.cant) from intrprodlink l where l.codprogramf1 = pf1.CODPROGRAMF1),0) ' || coalesce(current_setting('PKG_LIST_BASE_PF.gUserAlias', true),'') || '
    FROM PROGRAMF1 PF1
      INNER JOIN PROGRAMF PF       ON PF1.CODPROGRAMF      = PF.CODPROGRAMF
      INNER JOIN NGEST    NG       ON NG.CODGEST           = PF1.CODGEST
      INNER JOIN COMANDA1 C1       ON C1.CODCOMANDA1       = PF1.CODCOMANDA1
      INNER JOIN COMANDA  C        ON C.CODCOMANDA         = C1.CODCOMANDA
      INNER JOIN PRODCOMP PC       ON C1.CODRETETA         = PC.CODPRODCOMP
      INNER JOIN NARTOBJ  NOBJ     ON NOBJ.CODOBIECT       = C1.CODOBIECT
      INNER JOIN NUM1              ON NUM1.CODUM1          = C1.UMSEC
      LEFT  JOIN FORMATII FR       ON PF1.CodFormatie      = FR.CodFormatie
      LEFT  JOIN CMDLINK  CLINK    ON CLINK.CODCOMANDA1    = C1.CODCOMANDA1
      LEFT  JOIN COMANDA1 C1CLIENT ON C1CLIENT.CODCOMANDA1 = CLINK.CODLINIECOMANDA
      LEFT  JOIN COMANDA  CCLIENT  ON CCLIENT.CODCOMANDA   = C1CLIENT.CODCOMANDA
      LEFT  JOIN NPART    NP       ON NP.CODPART           = CCLIENT.PARTENER' || gSuplJoins || '
    WHERE PF1.CODPROGRAMF = ' || coalesce(current_setting('PKG_LIST_BASE_PF.vCodProgramF', true)::varchar ,'') || ' ORDER BY PF1.PRIORITATE ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_pfgantt_processlist</obj_name>
  <obj_hashval>4afd1562c0045d26f2a3f0b6cb6d772a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pfgantt_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sSelect     varchar;
  gSuplCols   varchar := 'CMDPRODMAN MAN, NOPER OP, LOCMUNCA LM';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 20.06.2024 - fixat 62410
  --Florin 21.07.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_PFGANTT.gSuplCols', gSuplCols, false);

  sInsert :=
  'INSERT INTO '||TMPNAME||'(
    LOCMUNCA        ,
    NROP            ,
    OPERATIE        ,
    TU              ,
    CODCMDPRODMAN   ,
    SAPT  ,
    TOTAL           ,
    LUNI            ,
    MARTI           ,
    MIERCURI        ,
    JOI             ,
    VINERI          ,
    SAMBATA         ,
    DUMINICA        ,
    CODPROGRAMF     ,
    PRIORITATE      ,
    CODCOMANDA1     ,
    NrCMD           ,
    IDENTIFICATOR   ,
    OBS             ,
    DEN_GEST        ,
    DENUMIRE        ,
    CODEXTERN       ,
    DEN_UM1         ,
    CANTPROGRAMAT   ,
    TERMEN          ,
    DEN_FORMATIE    ,
    SCHIMB  '||gUserFields||')
with  PF as
  (SELECT
    PF1.CODPROGRAMF,
    PF1.PRIORITATE,
    C1.CodComanda1,
    Round(C.NRDOC + C1.IndexLocal/100, 2) NRDOC,
    PC.IDENTIFICATOR,
    PC.OBS,
    NG.DEN_GEST,
    NOBJ.DENUMIRE,
    NOBJ.CODEXTERN,
    NUM1.DEN_UM1,
    PF1.CANTPROGRAMAT,
    C1.TERMEN,
    FR.Den_Formatie,
    PF1.Schimb
  FROM PROGRAMF1        PF1
    INNER JOIN PROGRAMF PF   ON PF1.CODPROGRAMF = PF.CODPROGRAMF
    INNER JOIN NGEST    NG   ON NG.CODGEST      = PF1.CODGEST
    INNER JOIN COMANDA1 C1   ON C1.CODCOMANDA1  = PF1.CODCOMANDA1
    INNER JOIN COMANDA  C    ON C.CODCOMANDA    = C1.CODCOMANDA
    INNER JOIN PRODCOMP PC   ON C1.CODRETETA    = PC.CODPRODCOMP
    INNER JOIN NARTOBJ  NOBJ ON NOBJ.CODOBIECT  = C1.CODOBIECT
    INNER JOIN NUM1          ON NUM1.CODUM1     = C1.UMSEC
    LEFT  JOIN FORMATII FR   ON PF1.CodFormatie = FR.CodFormatie
    WHERE PF1.CODPROGRAMF = '|| current_setting('PKG_LIST_BASE_PFGANTT.vCodProgramF', TRUE)::NUMERIC ||'),
  G as
  ( Select CODCMDPRODMAN, Saptamana, Total, Sum(Luni) Luni, Sum(Marti) Marti, Sum(Miercuri) Miercuri, Sum(Joi) Joi, Sum(Vineri) Vineri, Sum(Sambata) Sambata,Sum(Duminica) Duminica
    from (
          Select  CODCMDPRODMAN, Saptamana, Total,
                  Case when Z = 1 then CantZi else 0 end Luni,
                  Case when Z = 2 then CantZi else 0 end Marti,
                  Case when Z = 3 then CantZi else 0 end Miercuri,
                  Case when Z = 4 then CantZi else 0 end Joi,
                  Case when Z = 5 then CantZi else 0 end Vineri,
                  Case when Z = 6 then CantZi else 0 end Sambata,
                  Case when Z = 7 then CantZi else 0 end Duminica
          from( Select G.CODCMDPRODMAN,  G.CANT Total, TO_NUMBER(TO_CHAR(G.DStart,''IW'')) Saptamana,  TRUNC(G.DStart - TRUNC(G.DStart,''IW'')) + 1 +G1.DEPLASARE Z, G1.CANT CantZi
                from Gantt G
                     LEFT JOIN Gantt1 G1  ON G1.CODGANTT = G.CodGantt
              ) b_pg
         ) a_pg Group by CODCMDPRODMAN, Saptamana, Total
   )
  Select Lm.Denumire LocMunca, Man.nrop, op.denumire operatie, Man.TU,
         G.*, PF.*'||gUserAlias||'
  from pf
    inner join CMDPRODMAN Man on Man.CodComanda1 = PF.CodComanda1
    LEFT  JOIN noper      op  ON op.codop        = Man.codop
    LEFT  JOIN locmunca   lm  ON lm.codloc       = Man.codloc
    LEFT  JOIN G              on G.CodCmdProdMan = MAn.Codcmdprodman'||
    gSuplJoins||'
  WHERE PF.CODPROGRAMF = '|| current_setting('PKG_LIST_BASE_PFGANTT.vCodProgramF', TRUE)::NUMERIC;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_pflocm_processlist</obj_name>
  <obj_hashval>9cdbe0120000af779c607ecdaf1dd9de</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pflocm_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
BEGIN
  --Adina 14.10.2020
  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
        LocMunca,
        Disp,
        Necesar,
        Dif,
        Sectie,
        DispS,
        NecesarS,
        DifS,
        NrCmd,
        DataProg,
        Prioritate,
        Produs,
        NecesarCmd,
        Programat)
      SELECT TMP_B.DENUMIRE,
             TMP_B.DISPONIBIL,
             TMP_B.NECESAR,
             TMP_B.DIFERENTE,
             TMP_G.SECTIE,
             TMP_G.DISPONIBIL,
             TMP_G.NECESAR,
             TMP_G.DIFERENTE,
             TMP_C.NRCMD,
             TMP_C.DATAPROGRAMARE,
             TMP_C.PRIORITATE,
             TMP_C.DEN_OBIECT,
             TMP_C.NECESAR,
             TMP_C.CANTPROD
      FROM TMP_PF_LOCM_CMD TMP_C
           LEFT JOIN TMP_PF_LOCM TMP_B      ON TMP_C.CODLOC  = TMP_B.CODLOCMUNCA
           LEFT JOIN TMP_PF_LOCM_GEST TMP_G ON TMP_G.CODGEST = TMP_C.CODGEST AND TMP_G.CODLOCMUNCA = TMP_C.CODLOC ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_pflocm_setjoinuri</obj_name>
  <obj_hashval>ac9a18b47acd65307819710d69375f46</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pflocm_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.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_pflocm_setparams</obj_name>
  <obj_hashval>5e45999585e056cecaa78b99d21a7520</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pflocm_setparams(pcodprogramf numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.10.2020
  perform set_config('PKG_LIST_BASE_PFLOCM.vCodProgramF',(pCodProgramF)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_pfman_processlist</obj_name>
  <obj_hashval>25f15b8bef4c487b89cd0b8e840a553c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pfman_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
BEGIN
  --Adina 14.10.2020
  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
        Operatie,
        DenumireTarif,
        Tarif,
        Ore,
        Valoare,
        Sectie,
        OreS,
        ValoareS,
        NrCmd,
        DataCmd,
        Produs,
        CodExtern,
        Necesar)
      SELECT TMP_B.DEN_OP,
             TMP_B.DEN_TARIF,
             TMP_B.Tarif,
             TMP_B.Ore,
             TMP_B.Valoare,
             TMP_G.DEN_GEST,
             TMP_G.ORE,
             TMP_G.Valoare,
             TMP_C.NrDoc,
             TMP_C.DATADOC,
             TMP_C.DENUMIRE,
             TMP_C.CodExtern,
             TMP_C.Necesar
      FROM TMP_PF_MAN_CMD TMP_C
           INNER JOIN TMP_PF_MAN TMP_B      ON TMP_C.CODOP   = TMP_B.CODOP
           INNER JOIN TMP_PF_MAN_GEST TMP_G ON TMP_G.CODGEST = TMP_C.CODGEST AND TMP_G.CODOP = TMP_C.CODOP ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_pfman_setjoinuri</obj_name>
  <obj_hashval>4df4134df786ce6afca8915ecfcf60fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pfman_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.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_pfman_setparams</obj_name>
  <obj_hashval>52f60fa635063ec4cc9411f442cd68aa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pfman_setparams(pcodprogramf numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.10.2020
  perform set_config('PKG_LIST_BASE_PFMAN.vCodProgramF',(pCodProgramF)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_pfmat_processlist</obj_name>
  <obj_hashval>e68e18ffb6e2d66d03ee34f5922c5ff1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pfmat_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  vTabla           varchar := '';
  gSuplCols        VARCHAR := 'PROGRAMF PF, COMANDA1 C1CLIENT, COMANDA CCLIENT';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 14.10.2020
  vTabla := 'COMANDC';
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, vTabla, 'CCV', 'CCV.CODCOMANDA = CCLIENT.CODCOMANDA',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_PFMAT.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
      Mat,
      CodExternMat,
      UMMat,
      NecesarMat,
      RezervatMat,
      StocDispMat,
      ComFurnMat,
      AlteRezMat,
      Sectie,
      NecesarPr,
      RestAsigPr,
      NrCmd,
      DataCmd,
      Produs,
      CodExternProdus,
      NecesarProdus,
      RezervatProdus,
      UMProd,
      CantProdProg
      ' || gUserFields || ')
      SELECT TMP_B.DENUMIRE,
             TMP_B.CODEXTERN,
             TMP_B.DEN_UM1,
             TMP_B.NECESAR,
             TMP_B.REZERVAT,
             TMP_B.STOCDISP,
             TMP_B.STOCFURN,
             TMP_B.ALTEREZ,
             TMP_G.DEN_GEST,
             TMP_G.CANTPROGRAMAT,
             TMP_G.RESTASIGURAT,
             TMP_C.NRDOC,
             TMP_C.DATADOC,
             TMP_C.DENOBJ,
             TMP_C.CODEXTERN,
             TMP_C.CANT,
             TMP_C.STOCREZ,
             TMP_C.DEN_UM,
             TMP_C.CANTPROD' || gUserAlias || '
      FROM TMP_PF_MAT_CMD TMP_C
           INNER JOIN TMP_PF_MAT TMP_B      ON TMP_C.CODOBIECT      = TMP_B.CODOBIECT
           INNER JOIN TMP_PF_MAT_GEST TMP_G ON TMP_G.CODGEST        = TMP_C.CODGEST AND TMP_G.CODOBIECT = TMP_C.CODOBIECT
           INNER JOIN PROGRAMF PF           ON PF.CodProgramF       = ' || coalesce(current_setting('PKG_LIST_BASE_PFMAT.vCodProgramF', true)::varchar ,'') || '
           INNER JOIN COMANDA1 C1           ON TMP_C.CODCOMANDA1    = C1.CODCOMANDA1
           LEFT  JOIN CMDLINK CLINK         ON CLINK.CODCOMANDA1    = C1.CODCOMANDA1
           LEFT  JOIN COMANDA1 C1CLIENT     ON C1CLIENT.CODCOMANDA1 = CLINK.CODLINIECOMANDA
           LEFT  JOIN COMANDA CCLIENT       ON CCLIENT.CODCOMANDA   = C1CLIENT.CODCOMANDA
           ' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_pfmat_setjoinuri</obj_name>
  <obj_hashval>b2c7a2b60c784aff794dfa4db96a755a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pfmat_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_PFMAT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_pfmat_setparams</obj_name>
  <obj_hashval>e9596db110fc69d34e0c0fd9b9988b6e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pfmat_setparams(pcodprogramf numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.10.2020
  perform set_config('PKG_LIST_BASE_PFMAT.vCodProgramF',(pCodProgramF)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_pfsdv_processlist</obj_name>
  <obj_hashval>964eb96adedc7c4b0f2bedb27fe6fca5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pfsdv_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
BEGIN
  --Adina 14.10.2020
  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
        SDV,
        CodExternSDV,
        UMSDV,
        NecesarSDV,
        NecesarStabilit,
        StocDisp,
        ComFurn,
        Sectie,
        NecesarPr,
        StocExistent,
        NrCmd,
        Prioritate,
        Produs,
        CodExternProdus,
        UMProdus,
        CantProgramat)
      SELECT TMP_B.DENUMIRE,
             TMP_B.CODEXTERN,
             TMP_B.DEN_UM,
             TMP_B.CANTDOC,
             TMP_B.CANTACT,
             TMP_B.REST,
             TMP_B.STOCFURN,
             TMP_G.DEN_GEST,
             TMP_G.CANT,
             TMP_G.STOC,
             TMP_C.NrCmd,
             TMP_C.Prioritate,
             TMP_C.DEN_OBIECT,
             TMP_C.CodExtern,
             TMP_C.UM,
             TMP_C.CantProgramat
      FROM TMP_PF_SDV_CMD TMP_C
           LEFT JOIN TMP_PF_SDV TMP_B      ON TMP_C.CODOBIECT = TMP_B.CODOBIECT
           LEFT JOIN TMP_PF_SDV_GEST TMP_G ON TMP_G.CODGEST   = TMP_C.SECTIE AND TMP_G.CODOBIECT = TMP_C.CODOBIECT ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_planachiz_processlist</obj_name>
  <obj_hashval>face39223a0bb7951ff1316b84fe3a70</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_planachiz_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar;
  sAn             varchar := getANLUCRU()::varchar;
  gSuplCols        VARCHAR := 'CENTRECOST CC';
   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_PLANACHIZ.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(CCDENUMIRE, VAL_BUGET, VAL_PLATI, DIFERENTA ' || gUserFields || ')
  SELECT CC.Denumire, coalesce(v_b.val_buget, 0) val_buget, coalesce(v_p.val_plati, 0) val_plati, coalesce(v_b.val_buget, 0) - coalesce(v_p.val_plati, 0) dif ' || gUserAlias || '
  FROM (
        select codcentru, Sum(buget) val_buget
        from bugetanaliza
        where Coalesce(codcentru, 0) &lt;&gt; 0 AND an = ' || coalesce(sAn,'') || '
        group by codcentru
       ) v_b
  FULL JOIN (
              select op.codcentru, sum(p1.valoare) val_plati
              from   plati p
                    inner join plati1   p1 on p1.codplata    = p.codplata
                    inner join obligpif op on op.codobligpif = p1.codobligpif
              where coalesce(op.codcentru, 0) &lt;&gt; 0 AND p.an = ' || coalesce(sAn,'') || ' AND p.tipdoc = 1
              group by op.codcentru
            ) v_p ON v_p.codcentru = v_b.codcentru
  LEFT JOIN CENTRECOST CC ON CC.CODCENTRU = Coalesce(v_b.codcentru, v_p.codcentru)';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_planifcmd_centr_processlist</obj_name>
  <obj_hashval>2b77825bbc95cb825b4651bf47990dc2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_planifcmd_centr_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sString         varchar := '';
  ssTable         varchar := '';
  gSuplCols        VARCHAR := 'stareestimari1 se1, nartobj obj';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 14.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_PLANIFCMD_CENTR.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  PERFORM PKG_PLANIFCMD_MakeTemporarCentralizat(current_setting('PKG_LIST_BASE_PLANIFCMD_CENTR.pSet', true)::numeric, current_setting('PKG_LIST_BASE_PLANIFCMD_CENTR.pAn', true)::numeric);

  sString :=
  'insert into ' || tmpName || ' (
    stocmin,
    stocini,
    StocPrec,
    Estimari,
    Consum,
    CmdF,
    CmdFP,
    Necesar,
    StocFinal,
    Pret,
    StocVal,
    denumire,
    INDEXLOCAL,
    RESTPRECMD,
    RESTPRECMDA,
    RESTNECESAR,
    AN,
    SAPTAMANA ' || gUserFields || '
  )
  select
    tse1.stocmin,
    tse1.stocini,
    tse1.StocPrec,
    tse1.Estimari,
    tse1.Consum,
    tse1.CmdF,
    tse1.CmdFP,
    tse1.Necesar,
    tse1.StocFinal,
    tse1.Pret,
    tse1.StocVal,
    tse1.denumire,
    tse1.INDEXLOCAL,
    tse1.RESTPRECMD,
    tse1.RESTPRECMDA,
    tse1.RESTNECESAR,
    tse1.an,
    tse1.saptamana' || gUserAlias || '
  from tmp_stareestimari1_centr  tse1
       inner join stareestimari1 se1 on tse1.codstare1 = se1.codstare1
       inner join stareestimari  se  on se1.codstare   = se.codstare
       inner join nartobj        obj on se1.codobiect  = obj.codobiect
  ' || gSuplJoins || '
  where tse1.userid = ' || coalesce(current_setting('PKG_GLOBALS.USERID', true)::numeric,'');

  EXECUTE (  sString) ;

  DELETE FROM tmp_stareestimari1_centr WHERE userid = current_setting('PKG_GLOBALS.USERID', true)::numeric;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_planifcmd_centr_processparams</obj_name>
  <obj_hashval>76f244b3791522dd3e25d8a1eb7dddc9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_planifcmd_centr_processparams(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  sSet    varchar;
  sSetG   varchar;
  sOferta varchar;
BEGIN
  --Adina 14.10.2020
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN
  (
    SELECT   coalesce((se.saptamana)::varchar,'') || '/' || coalesce((se.an)::varchar,'') SETC,
            coalesce(o.nrdoc::varchar,'') || ' - ' || coalesce(p.den_part,'') OFERTA
    FROM   stareestimari se
          LEFT JOIN oferta o ON  se.codoferta = o.codoferta
          LEFT JOIN npart  p ON  p.codpart    = o.partener
    WHERE SE.AN = current_setting('PKG_LIST_BASE_PLANIFCMD_CENTR.PAN', true)::numeric AND
          SE.SAPTAMANA = current_setting('PKG_LIST_BASE_PLANIFCMD_CENTR.PSET', true)::numeric
  )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Saptamana curenta', v_rec.SetC);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Oferta',            v_rec.oferta);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_planifcmd_centr_setparams</obj_name>
  <obj_hashval>d05f9a89eab45d43dd1ac46f534dc8a4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_planifcmd_centr_setparams(aan numeric, aset numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.10.2020
  perform set_config('PKG_LIST_BASE_PLANIFCMD_CENTR.pAn' ,(aAn)::varchar ,false);
  perform set_config('PKG_LIST_BASE_PLANIFCMD_CENTR.pSet',(aSet)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_planifcmd_processlist</obj_name>
  <obj_hashval>b5a4914f386c7c2fbc4ef481e5a13444</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_planifcmd_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sString         varchar := '';
  gSuplCols        VARCHAR := 'stareestimari1 se1, nartobj obj';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 14.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_PLANIFCMD.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sString :=
  'insert into ' || tmpName || ' (
    stocmin,
    stocini,
    StocPrec,
    Estimari,
    Consum,
    CmdF,
    CmdFP,
    Necesar,
    StocFinal,
    Pret,
    StocVal,
    denumire,
    INDEXLOCAL,
    RESTPRECMD,
    RESTPRECMDA,
    RESTNECESAR ' || gUserFields || '
  )
  select
    tse1.stocmin,
    tse1.stocini,
    tse1.StocPrec,
    tse1.Estimari,
    tse1.Consum,
    tse1.CmdF,
    tse1.CmdFP,
    tse1.Necesar,
    tse1.StocFinal,
    tse1.Pret,
    tse1.StocVal,
    tse1.denumire,
    tse1.INDEXLOCAL,
    tse1.RESTPRECMD,
    tse1.RESTPRECMDA,
    tse1.RESTNECESAR
  ' || gUserAlias || '
  from tmp_stareestimari1        tse1
       inner join stareestimari1 se1 on tse1.codstare1 = se1.codstare1
       inner join stareestimari  se  on se1.codstare   = se.codstare
       inner join nartobj        obj on se1.codobiect  = obj.codobiect
  ' || gSuplJoins;
  EXECUTE (sString) ;
  PERFORM PKG_LIST_BASE_PLANIFCMD_PROCESSPARAMS(tmpName);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_planifcmd_processparams</obj_name>
  <obj_hashval>672686760ddbf2b2bfa7f6f1c66e01f6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_planifcmd_processparams(tmpname character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  sSet    varchar := '';
  sSetG   varchar := '';
  sOferta varchar := '';
BEGIN
  --Adina 14.10.2020
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN
  (
    SELECT   coalesce((se.saptamana)::varchar,'')  || '/' || coalesce((se.an )::varchar,'') SETC,
            coalesce((se.saptamanaG)::varchar,'') || '/' || coalesce((se.anG)::varchar,'') SETG,
            coalesce(o.nrdoc,'') || ' - ' || coalesce(p.den_part,'') OFERTA
    FROM   stareestimari se
          INNER JOIN tmp_stareestimari1 se1 ON  se1.codstare = se.codstare
          LEFT  JOIN oferta o               ON  se.codoferta = o.codoferta
          LEFT  JOIN npart p                ON  p.codpart    = o.partener
  )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Saptamana curenta',  v_rec.SetC);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Saptamana generare', v_rec.SetG);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Oferta',             v_rec.oferta);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_planifcmd_setparams</obj_name>
  <obj_hashval>d70b2479dbcc7913f0dd397f60a34fdf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_planifcmd_setparams(aan numeric, aset numeric, aang numeric, asetg numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.10.2020
  perform set_config('PKG_LIST_BASE_PLANIFCMD.pAn'  ,(aAn)::varchar  ,false);
  perform set_config('PKG_LIST_BASE_PLANIFCMD.pSet' ,(aSet)::varchar ,false);
  perform set_config('PKG_LIST_BASE_PLANIFCMD.pAnG' ,(aAnG)::varchar ,false);
  perform set_config('PKG_LIST_BASE_PLANIFCMD.pSetG',(aSetG)::varchar,false);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_planifprod_setparams</obj_name>
  <obj_hashval>f8f5774f756c745ec6c64fa267216c50</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_planifprod_setparams(asetimana numeric, aan numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14 septembrie 2020
  perform set_config('PKG_LIST_BASE_PLANIFPROD.pSetimana',(aSetimana)::varchar,false);
  perform set_config('PKG_LIST_BASE_PLANIFPROD.pAn'      ,(aAn)::varchar      ,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_planifstoc_getgnullalias</obj_name>
  <obj_hashval>fc4dc8ab734b0b82983d84e3972c7494</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_planifstoc_getgnullalias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_PLANIFSTOC.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_planifstoc_getgsuplcols</obj_name>
  <obj_hashval>2592787091bd21fd0a047c0be4c3051c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_planifstoc_getgsuplcols(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_PLANIFSTOC.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_planifstoc_getparbycodextern</obj_name>
  <obj_hashval>8871a41358cbdf07226266a86081b31c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_planifstoc_getparbycodextern(acodextern character varying, acodobiect numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aParitate numeric;
BEGIN
  --Adina 11.12.2020 tichet 41557
  --Bogdan 31.08.2020
  BEGIN
    SELECT num1.paritate
    INTO STRICT aParitate
    FROM nartamb amb
      INNER JOIN num1 ON  num1.codum1 = amb.umsec
    WHERE
         amb.codobiect = aCodObiect
         and  upper(num1.codextern) = upper(aCodExtern)
    ORDER BY
        amb.codamb
       limit 1;
  EXCEPTION
    WHEN NO_DATA_FOUND THEN aParitate := 1;
    WHEN OTHERS        THEN aParitate := 1;
  END;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_planifstoc_setparams</obj_name>
  <obj_hashval>9a7846cab244408a8d6cb764783f165e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_planifstoc_setparams(adatastart character varying, adatafin character varying, allgeststoc numeric, allgestcmd numeric, notermen numeric, v_codjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
BEGIN
  --Adina 02 septembrie 2020
  perform set_config('PKG_LIST_BASE_PLANIFSTOC.vDataStart'  ,  COALESCE(aDataStart , '')            ,false);
  perform set_config('PKG_LIST_BASE_PLANIFSTOC.vDataFin'    ,  COALESCE(aDataFin   , '')            ,false);
  perform set_config('PKG_LIST_BASE_PLANIFSTOC.vAllGestStoc',( COALESCE(AllGestStoc,0) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_PLANIFSTOC.vAllGestCmd' ,( COALESCE(AllGestCmd ,0) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_PLANIFSTOC.vNoTermen'   ,( COALESCE(NoTermen   ,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_PLANIFSTOC.vDataStart', true), current_setting('PKG_LIST_BASE_PLANIFSTOC.vDataFin', true), xLunaAnIni, xLunaAnFin);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_pontajesa_setjoinuri</obj_name>
  <obj_hashval>aa5ee3ca097c79b1bd5e9be388d95861</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pontajesa_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_PONTAJESA.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_postcalcul_setparams</obj_name>
  <obj_hashval>3f238d8f181312de76d286da152e2330</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_postcalcul_setparams(pcodpc numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14 septembrie 2020
  perform set_config('PKG_LIST_BASE_POSTCALCUL.vCodPC',(pCodPC)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_prodcomp_getcod</obj_name>
  <obj_hashval>644f16e30db73104aaaa2580ab677fe5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_prodcomp_getcod()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.10.2020
  RETURN current_setting('PKG_LIST_BASE_PRODCOMP.p_CodProdComp', true)::numeric;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_prodcomp_processlist</obj_name>
  <obj_hashval>977b0c89652287448e377d6950ff8ff5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_prodcomp_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, NCLASEA CLASA, IOART IOART, NPART PROD ';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  sAnLunaLucru    varchar := COALESCE((getanlucru() * 12 + GetLunaLUCRU())::varchar,'0');
BEGIN
  --Adina 11.05.2021 - alstart, alstop, sAnLunaLucru
  --Adina 18.02.2021 - dupa modif.Oracle din 17.02.2021
  --Adina 14.10.2020
  --perform set_config('PKG_LIST_BASE_PRODCOMP.gSuplCols',('NART ART, NARTOBJ OBJ, NCLASEA CLASA, IOART IOART, NPART PROD ')::varchar,false);
  CALL PRC_AL_CHECK('tarifeman1', 0);

  IF  current_setting('PKG_LIST_BASE_PRODCOMP.p_CodProdComp', true)::numeric &gt; 0 THEN
    gSuplCols := gSuplCols||',PRODCOMP P, PRODMAT MAT, PRODREZ REZ';
  ELSE
    IF  current_setting('PKG_LIST_BASE_PRODCOMP.p_CodComanda1', true)::numeric &gt; 0 THEN
      gSuplCols := gSuplCols||',PRODCOMP P, PRODMAT MAT, PRODREZ REZ';
    END IF;
  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_PRODCOMP.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF  current_setting('PKG_LIST_BASE_PRODCOMP.p_CodProdComp', true)::numeric &gt; 0 THEN
    sInsert :=
    'INSERT INTO ' || TMPNAME || ' (
      DenArt, UM, Cant, Pret, D1, D2, D3, UM1, CantUM1, Atribut, IndexLocal,
      ValMat, ValMan, ValRegie, SectieExec, Obs, Tip, Reteta, Proc, ProcTransp ' || gUserFields || ')
    SELECT
      obj.Denumire DenArt, NUM.Den_UM, MAT.Cant, MAT.Pret, MAT.D1, MAT.D2, MAT.D3, NUM1.Den_UM, Mat.CantUM1, atr.denumire, mat.indexlocal,
      mat.valmat, mat.valman, mat.valregie, g.den_gest, mat.obs, ''Articol folosit'' tip, P.OBS, mat.adddim, mat.adddim_transp ' || gUserAlias || '
    FROM   ProdComp P
          INNER JOIN prodgest      pg    on pg.codprodcomp    = p.codprodcomp
          INNER JOIN prodmat       mat   on p.codprodcomp     = mat.codprodcomp and mat.codprodgest = pg.codprodgest
          INNER JOIN ngest         g     on pg.codgest        = g.codgest
          INNER JOIN nartobj       obj   on mat.codobiect     = obj.codobiect
          INNER JOIN nart          art   on obj.codarticol    = art.codarticol
          INNER JOIN num                 on art.um            = num.codum
          LEFT  JOIN PRODREZ       REZ   on REZ.CODPRODCOMP   = P.CODPRODCOMP - P.CODPRODCOMP
          LEFT  JOIN num           NUM1  on art.um1           = num1.codum
          LEFT  JOIN natrib        atr   on mat.codatribut    = atr.codatribut
          LEFT  JOIN nclasea       clasa on clasa.codclasea   = art.clasa
          LEFT  JOIN nartimplicite imp   on art.codarticol    = imp.codarticol and imp.codsubunit  = getsubunitate()
          LEFT  JOIN nartobjimp    impo  on obj.codobiect     = impo.codobiect and impo.codsubunit = getsubunitate()
          LEFT  JOIN ioart         ioart on ioart.codioart    = case when coalesce(impo.contimplicit,0) = 0 then imp.contimplicit else coalesce(impo.contimplicit,0) end
          LEFT  JOIN npart         prod  on obj.codproducator = prod.codpart ' || gSuplJoins || '
    WHERE P.CodProdComp = ' || coalesce(current_setting('PKG_LIST_BASE_PRODCOMP.p_CodProdComp', true),'') || '
    UNION ALL
    SELECT
      obj.Denumire DenArt, NUM.Den_UM, rez.Cant, rez.Pret, rez.D1, rez.D2, rez.D3, NUM1.Den_UM, rez.CantUM1, '''' denumire, rez.indexlocal,
      0 valmat, 0 valman, 0 valregie, g.den_gest, NULL Obs, ''Articol rezultat'' tip, P.OBS, null addim , null adddim_transp ' || gUserAlias || '
    FROM   ProdComp P
          INNER JOIN prodgest      pg    on pg.codprodcomp    = p.codprodcomp
          INNER JOIN prodrez       rez   on p.codprodcomp     = rez.codprodcomp and rez.codprodgest = pg.codprodgest
          INNER JOIN ngest         g     on pg.codgest        = g.codgest
          INNER JOIN nartobj       obj   on rez.codobiect     = obj.codobiect
          INNER JOIN nart          art   on obj.codarticol    = art.codarticol
          INNER JOIN num                 on art.um            = num.codum
          LEFT  JOIN PRODMAT       MAT   on MAT.CODPRODCOMP   = P.CODPRODCOMP - P.CODPRODCOMP
          LEFT  JOIN num           NUM1  on art.um1           = num1.codum
          LEFT  JOIN nclasea       clasa on clasa.codclasea   = art.clasa
          LEFT  JOIN nartimplicite imp   on art.codarticol    = imp.codarticol and imp.codsubunit  = getsubunitate()
          LEFT  JOIN nartobjimp    impo  on obj.codobiect     = impo.codobiect and impo.codsubunit = getsubunitate()
          LEFT  JOIN ioart         ioart on ioart.codioart    = case when coalesce(impo.contimplicit,0) = 0 then imp.contimplicit else coalesce(impo.contimplicit,0) end
          LEFT  JOIN npart         prod  on obj.codproducator = prod.codpart ' || gSuplJoins || '
    WHERE P.CodProdComp = ' || coalesce(current_setting('PKG_LIST_BASE_PRODCOMP.p_CodProdComp', true),'');

    sInsert1 :=
    'INSERT INTO ' || TMPNAME || ' (
        SectieExec, Ordine, NrOp, Operatie, LocMunca, DenTarif, tarif, tu, valoare, dsv, bps, tpi, obs, detalii, tip ' || gUserFields || ')
      SELECT
        X.SectieExec, X.Ordine, X.NrOp, X.Operatie, X.LocMunca, X.DenTarif, X.tarif, X.tu, X.valoare, X.dsv, X.bps, X.tpi, X.obs, X.detalii, X.tip ' || gUserAlias || '
      FROM (
            SELECT
              pc.codprodcomp, G.Den_Gest SectieExec, pm.Ordine, pm.NrOp, op.denumire Operatie, lm.denumire LocMunca,
              t.denumire DenTarif, t.tarif, pm.tu, round((pm.tu * t.tarif)/60,5) valoare,
              pm.dsv, pm.bps, pm.tpi, pm.obs, pm.detalii,  ''Manopera'' tip, 0 codobiect, 0 codarticol
            FROM   prodcomp pc
                  INNER JOIN prodgest pg on pc.codprodcomp          = pg.codprodcomp
                  INNER JOIN ngest    g  on coalesce(pg.codgest, 0) = g.codgest
                  INNER JOIN (select m.*, Row_number() over() Ordine from prodman m order by m.nrop, m.detalii) pm on pm.codprodcomp = pc.codprodcomp and pm.codprodgest = pg.codprodgest
                  INNER JOIN noper    op on pm.codop  = op.codop
                  INNER JOIN locmunca lm on lm.codloc = pm.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 PM.CODTARIF = T.CODTARIF
            WHERE PC.CodProdComp = ' || coalesce(current_setting('PKG_LIST_BASE_PRODCOMP.p_CodProdComp', true)::numeric::varchar ,'') || '
           )   x
              INNER JOIN PRODCOMP      P     ON X.CODPRODCOMP     = P.CODPRODCOMP
              LEFT  JOIN PRODMAT       MAT   on MAT.CODPRODCOMP   = P.CODPRODCOMP - P.CODPRODCOMP
              LEFT  JOIN PRODREZ       REZ   on REZ.CODPRODCOMP   = P.CODPRODCOMP - P.CODPRODCOMP
              LEFT  JOIN nartobj       obj   on x.codobiect       = obj.codobiect
              LEFT  JOIN nart          art   on obj.codarticol    = art.codarticol
              LEFT  JOIN nclasea       clasa on clasa.codclasea   = art.clasa
              LEFT  JOIN nartimplicite imp   on x.codarticol      = imp.codarticol and imp.codsubunit  = getsubunitate()
              LEFT  JOIN nartobjimp    impo  on obj.codobiect     = impo.codobiect and impo.codsubunit = getsubunitate()
              LEFT  JOIN ioart         ioart on ioart.codioart    = case when coalesce(impo.contimplicit,0) = 0 then imp.contimplicit else coalesce(impo.contimplicit,0) end
              LEFT  JOIN npart         prod  on obj.codproducator = prod.codpart' || gSuplJoins ;

    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert1, aListID, aListVer);
    PERFORM PKG_LIST_BASE_PRODCOMP_PROCESSPARAMSRET();
  ELSE
    IF  current_setting('PKG_LIST_BASE_PRODCOMP.p_CodComanda1', true)::numeric &lt; 0 THEN
      sInsert :=
      'INSERT INTO ' || TMPNAME || ' (
        DenArt, UM, Cant, D1, D2, D3,
        ValMat, ValMan, ValRegie, SectieExec, Tip, Stoc, Rezervat, AlteRez, Necesar, NecesarCalc ' || gUserFields || ')
      SELECT
        x.DenArt, x.UM, x.Cant, x.D1, x.D2, x.D3,
        x.ValMat, x.ValMan, x.ValRegie, x.SectieExec, x.Tip, coalesce(X.STOC,0), coalesce(X.REZERVAT,0), coalesce(X.REZALTE,0),
        coalesce(X.NECESAR,0), coalesce(X.NECESARCALC,0) ' || gUserAlias || '
      from (
            select
              obj.codobiect, obj.Denumire DenArt, NUM.Den_UM UM, sum(cmd.Cant) Cant, coalesce(CMD.D1,0) D1, coalesce(CMD.D2,0) D2, coalesce(CMD.D3,0) D3,
              sum(cmd.cant/pc.cant*mat.valmat) ValMat, sum(cmd.cant/pc.cant*mat.valman) ValMan, sum(cmd.cant/pc.cant*mat.valregie) ValRegie,
              g.den_gest SectieExec, ''Articol folosit'' Tip, coalesce(CMD.STOC,0) STOC,
              SUM(coalesce(CMD.REZERVAT,0)) REZERVAT, SUM(coalesce(CMD.ALTEREZERVARI,0)) REZALTE, SUM(coalesce(CMD.NECESAR,0)) NECESAR,
              coalesce(CMD.STOC,0) - SUM(coalesce(CMD.ALTEREZERVARI,0)) - SUM(coalesce(CMD.NECESAR,0)) NECESARCALC
            FROM   comanda1 cc1
                  INNER JOIN COMANDA1       C1  ON CC1.CODCOMANDA  = C1.CODCOMANDA
                  INNER JOIN COMANDA        C   ON C.CODCOMANDA    = C1.CODCOMANDA
                  INNER JOIN TMP_CMDPRODMAT CMD ON CMD.CODCOMANDA1 = C1.CODCOMANDA1
                  INNER JOIN prodmat        mat on CMD.CODPRODMAT  = MAT.CODMAT
                  inner join prodcomp       pc  on mat.codprodcomp = pc.codprodcomp
                  INNER JOIN ngest          g   on c.codgest       = g.codgest
                  INNER JOIN nartobj        obj on cmd.codobiect   = obj.codobiect
                  INNER JOIN nart           art on obj.codarticol  = art.codarticol
                  INNER JOIN num                on art.um          = num.codum
            WHERE cmd.tip = 1 and cc1.CodCOMANDA1 = ' || coalesce(-current_setting('PKG_LIST_BASE_PRODCOMP.p_CodComanda1', true),'') || '
            group by obj.codobiect, obj.denumire, num.den_um, coalesce(CMD.D1,0), coalesce(CMD.D2,0), coalesce(CMD.D3,0), g.den_gest, CMD.STOC
           )   x
              left join nartobj       obj   on obj.codobiect     = x.codobiect
              LEFT JOIN nart          art   on obj.codarticol    = art.codarticol
              LEFT JOIN nclasea       clasa on clasa.codclasea   = art.clasa
              LEFT JOIN nartimplicite imp   on art.codarticol    = imp.codarticol and imp.codsubunit  = getsubunitate()
              LEFT JOIN nartobjimp    impo  on obj.codobiect     = impo.codobiect and impo.codsubunit = getsubunitate()
              LEFT JOIN ioart         ioart on ioart.codioart    = case when coalesce(impo.contimplicit,0) = 0 then imp.contimplicit else coalesce(impo.contimplicit,0) end
              LEFT JOIN npart         prod  on obj.codproducator = prod.codpart
      ' || gSuplJoins || '
      UNION ALL
      SELECT
        x.DenArt, x.UM, x.Cant, x.D1, x.D2, x.D3,
        x.ValMat, x.ValMan, x.ValRegie, x.SectieExec, x.Tip, coalesce(x.STOC,0) STOC, coalesce(x.REZERVAT,0) REZERVAT, coalesce(x.REZALTE,0) REZALTE, 0 NECESAR,
        0 NECESARCALC ' || gUserAlias || '
      from (
            select
              c1.codreteta, obj.codobiect, obj.Denumire DenArt, NUM.Den_UM UM, sum(cmd.Cant) Cant, coalesce(CMD.D1,0) D1, coalesce(CMD.D2,0) D2, coalesce(CMD.D3,0) D3,
              0 ValMat, 0 ValMan, 0 ValRegie,
              g.den_gest SectieExec, ''Articol rezultat'' Tip,
              sum(coalesce(CMD.STOC,0)) STOC, sum(coalesce(CMD.REZERVAT,0)) REZERVAT, sum(coalesce(CMD.ALTEREZERVARI,0)) REZALTE
            FROM   comanda1 cc1
                  INNER JOIN COMANDA1 C1        ON Cc1.CODCOMANDA = C1.CODCOMANDA
                  INNER JOIN COMANDA C          ON C.CODCOMANDA   = C1.CODCOMANDA
                  inner join TMP_CMDPRODMAT CMD on c1.codcomanda1 = cmd.codcomanda1
                  INNER JOIN ngest g            on c.codgest = g.codgest
                  INNER JOIN nartobj obj        on cmd.codobiect  = obj.codobiect
                  INNER JOIN nart art           on obj.codarticol = art.codarticol
                  INNER JOIN num                on art.um = num.codum
            WHERE cmd.tip = 2 and Cc1.CodCOMANDA1 = ' || coalesce(-current_setting('PKG_LIST_BASE_PRODCOMP.p_CodComanda1', true),'') || '
            group by c1.codreteta, obj.codobiect, obj.denumire, num.den_um, coalesce(CMD.D1,0), coalesce(CMD.D2,0), coalesce(CMD.D3,0), g.den_gest
           )   x
              left join nartobj       obj   on obj.codobiect     = x.codobiect
              LEFT JOIN nart          art   on obj.codarticol    = art.codarticol
              LEFT JOIN nclasea       clasa on clasa.codclasea   = art.clasa
              LEFT JOIN nartimplicite imp   on art.codarticol    = imp.codarticol and imp.codsubunit  = getsubunitate()
              LEFT JOIN nartobjimp    impo  on obj.codobiect     = impo.codobiect and impo.codsubunit = getsubunitate()
              LEFT JOIN ioart         ioart on ioart.codioart    = case when coalesce(impo.contimplicit,0) = 0 then imp.contimplicit else coalesce(impo.contimplicit,0) end
              LEFT JOIN npart         prod  on obj.codproducator = prod.codpart
              left join prodcomp      pc    on x.codreteta       = pc.codprodcomp
              ' || gSuplJoins;

      PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
    ELSE
      sInsert :=
      'INSERT INTO ' || TMPNAME || ' (
        DenArt, UM, Cant, Pret, D1, D2, D3, UM1, CantUM1, Atribut, IndexLocal,
        ValMat, ValMan, ValRegie, SectieExec, Obs, Tip, Stoc, Rezervat, AlteRez, Necesar, NecesarCalc ' || gUserFields || ')
      SELECT
        obj.Denumire DenArt, NUM.Den_UM, cmd.Cant, cmd.Pret, MAT.D1, MAT.D2, MAT.D3, NUM1.Den_UM, Mat.CantUM1, atr.denumire, mat.indexlocal,
        cmd.cant/pc.cant*mat.valmat, cmd.cant/pc.cant*mat.valman, cmd.cant/pc.cant*mat.valregie, g.den_gest, mat.obs, ''Articol folosit'',
        coalesce(CMD.STOC,0) STOC, coalesce(CMD.REZERVAT,0) REZERVAT, coalesce(CMD.ALTEREZERVARI,0) REZALTE, coalesce(CMD.NECESAR,0) NECESAR,
        coalesce(CMD.STOC,0) - coalesce(CMD.ALTEREZERVARI,0) - coalesce(CMD.NECESAR,0) NECESARCALC ' || gUserAlias || '
      FROM   TMP_CMDPRODMAT CMD
            INNER JOIN prodmat       mat    on CMD.CODPRODMAT    = MAT.CODMAT
            inner join prodcomp      pc    on mat.codprodcomp   = pc.codprodcomp
            INNER JOIN COMANDA1      C1    ON CMD.CODCOMANDA1   = C1.CODCOMANDA1
            INNER JOIN COMANDA       C      ON C.CODCOMANDA      = C1.CODCOMANDA
            INNER JOIN ngest         g      on c.codgest         = g.codgest
            INNER JOIN nartobj       obj    on cmd.codobiect     = obj.codobiect
            INNER JOIN nart          art    on obj.codarticol    = art.codarticol
            INNER JOIN num                  on art.um            = num.codum
            LEFT  JOIN num           NUM1  on art.um1           = num1.codum
            LEFT  JOIN natrib        atr    on mat.codatribut    = atr.codatribut
            LEFT  JOIN nclasea       clasa on clasa.codclasea   = art.clasa
            LEFT  JOIN nartimplicite imp   on art.codarticol    = imp.codarticol and imp.codsubunit  = getsubunitate()
            LEFT  JOIN nartobjimp    impo  on obj.codobiect     = impo.codobiect and impo.codsubunit = getsubunitate()
            LEFT  JOIN ioart         ioart on ioart.codioart    = case when coalesce(impo.contimplicit,0) = 0 then imp.contimplicit else coalesce(impo.contimplicit,0) end
            LEFT  JOIN npart         prod  on obj.codproducator = prod.codpart
          ' || gSuplJoins || '
      WHERE cmd.tip = 1 and CMD.CodCOMANDA1 = ' || coalesce(current_setting('PKG_LIST_BASE_PRODCOMP.p_CodComanda1', true),'') || '
      UNION ALL
      SELECT
        obj.Denumire DenArt, NUM.Den_UM, cmd.Cant, cmd.Pret, rez.D1, rez.D2, rez.D3, NUM1.Den_UM, rez.CantUM1, '''', rez.indexlocal,
        0, 0, 0, g.den_gest, NULL Obs, ''Articol rezultat'', coalesce(CMD.STOC,0) STOC, coalesce(CMD.REZERVAT,0) REZERVAT, coalesce(CMD.ALTEREZERVARI,0) REZALTE, 0 NECESAR,
        0 ' || gUserAlias || '
      FROM   TMP_CMDPRODMAT CMD
            INNER JOIN prodrez       rez    on CMD.CODPRODMAT    = rez.CODrez
            inner join prodcomp      pc    on rez.codprodcomp   = pc.codprodcomp
            INNER JOIN COMANDA1      C1    ON CMD.CODCOMANDA1   = C1.CODCOMANDA1
            INNER JOIN COMANDA       C      ON C.CODCOMANDA      = C1.CODCOMANDA
            INNER JOIN ngest         g      on c.codgest         = g.codgest
            INNER JOIN nartobj       obj    on cmd.codobiect     = obj.codobiect
            INNER JOIN nart          art    on obj.codarticol    = art.codarticol
            INNER JOIN num                  on art.um            = num.codum
            LEFT  JOIN num           NUM1  on art.um1           = num1.codum
            LEFT  JOIN nclasea       clasa on clasa.codclasea   = art.clasa
            LEFT  JOIN nartimplicite imp   on art.codarticol    = imp.codarticol and imp.codsubunit  = getsubunitate()
            LEFT  JOIN nartobjimp    impo  on obj.codobiect     = impo.codobiect and impo.codsubunit = getsubunitate()
            LEFT  JOIN ioart         ioart on ioart.codioart    = case when coalesce(impo.contimplicit,0) = 0 then imp.contimplicit else coalesce(impo.contimplicit,0) end
            LEFT  JOIN npart         prod  on obj.codproducator = prod.codpart
          ' || gSuplJoins || '
      WHERE cmd.tip = 2 and CMD.CodCOMANDA1 = ' || coalesce(current_setting('PKG_LIST_BASE_PRODCOMP.p_CodComanda1', true),'');

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_prodcomp_processparams</obj_name>
  <obj_hashval>28974d8c4b3bc6eeea8458d8c4d20546</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_prodcomp_processparams()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  V_CFG       RECORD;
  SSQL         varchar;
  ValCamp     numeric;
  vCodProiect numeric;
  Display     varchar;
  ValDisplay   varchar;
BEGIN
  --Adina 14.10.2020
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN
    (
      SELECT   OBJ.CodObiect, OBJ.Denumire, P.Obs, P.Data, C1.Cantacceptat, P.D1, P.D2, P.D3, NUM.Den_UM,
              CASE WHEN  P.TipReteta = 1 THEN 'Agregare' ELSE 'Dezagregare' END  TIPRETETA,
              P.CantUM1, P.Coefindirecte, P.Pret,
              c1.cantacceptat / p.cant * COALESCE(P.ValMat, 0) VALMAT,
              c1.cantacceptat / p.cant * COALESCE(P.ValMan, 0) VALMAN,
              c1.cantacceptat / p.cant * COALESCE(P.ValRegie, 0) VALREGIE,
              OBJ.CODINTERN, OBJ.CODEXTERN, to_char(P.DATA, 'dd.mm.yyyy') DATAI, P.Arhiva, coalesce(PE.NUME,'') || ' ' || coalesce(PE.PRENUME,'') NUME_PRENUME
      FROM   COMANDA1 C1
            INNER JOIN PRODCOMP P   ON  C1.CODRETETA   = P.CODPRODCOMP
            INNER JOIN NARTOBJ  OBJ ON  P.CodObiect    = OBJ.CodObiect
            INNER JOIN NART     ART ON  OBJ.CodArticol = ART.CodArticol
            INNER JOIN NUM          ON  ART.UM         = NUM.CodUM
            LEFT  JOIN NPERS    PE  ON  PE.CodPers     = P.PROIECTANT
      WHERE C1.CodComanda1 = current_setting('PKG_LIST_BASE_PRODCOMP.p_CodComanda1', true)::numeric
    )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DenArt',                           v_rec.Denumire);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CodObiect',                       v_rec.CodObiect::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Obs',                             v_rec.Obs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Cantitati pe',                     v_rec.Cantacceptat::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Data',                             to_char(v_rec.DATA,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('D1',                               v_rec.D1::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('D2',                               v_rec.D2::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('D3',                               v_rec.D3::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('UM',                               v_rec.Den_UM);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Tip reteta',                       v_rec.TipReteta);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Cant UM specifica',               v_rec.CantUM1::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Indice cheltuieli indirecte',     v_rec.Coefindirecte::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Pret',                             v_rec.Pret::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Valoare materiale pe UM produs',   v_rec.ValMat::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Valoare manopera pe UM produs',   v_rec.ValMan::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Valoare regie pe UM produs',       v_rec.ValRegie::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Cod extern produs finit',         v_rec.CodExtern);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Cod intern produs finit',         v_rec.CodIntern);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Numar desen/iso',                 v_rec.Obs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Data intocmirii retetei',         v_rec.DataI);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Nr arhiva',                       v_rec.Arhiva);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit nume si prenume',         v_rec.Nume_Prenume);
    EXIT ;
  END LOOP;

  BEGIN
    SELECT COALESCE(cc1.codproiect, 0)
    INTO vCodProiect
    FROM   COMANDA1 C1
          INNER JOIN CMDLINK  CMDL ON  CMDL.CODCOMANDA1 = C1.CODCOMANDA1
          INNER JOIN COMANDA1 CC1  ON  CC1.CODCOMANDA1  = CMDL.CODLINIECOMANDA
    WHERE c1.codcomanda1 = current_setting('PKG_LIST_BASE_PRODCOMP.p_CodComanda1', true)::numeric;
  EXCEPTION WHEN others THEN
    vCodProiect := 0;
  END;

  IF  vCodProiect &gt; 0 THEN
    IF  (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists(NULL,'PROIECTEXT')) = 1 THEN
      FOR V_CFG IN
        (
          SELECT CFG1.NUMECAMP, COALESCE(CFG1.NOMLINK, 0) NOMLINK, CFG1.LOOKUPDISPLAY
          FROM   CFGTABLES1 CFG1
                INNER JOIN CFGTABLES CFG ON  CFG.CODCFGTABLE = CFG1.CODCFGTABLE
          WHERE CFG.NUMETABELA = 'PROIECTEXT'
        )
      LOOP
        IF  V_CFG.NOMLINK = 0 THEN
          SSQL := 'DO LANGUAGE PLPGSQL $$
                   DECLARE
                       V_REC record;
                   BEGIN
                     FOR V_REC IN (SELECT PEXT.' || coalesce(V_CFG.NUMECAMP,'') || '::varchar
                                   FROM COMANDA1 C1
                                        INNER JOIN CMDLINK    CMDL ON CMDL.CODCOMANDA1 = C1.CODCOMANDA1
                                        INNER JOIN COMANDA1   CC1  ON CC1.CODCOMANDA1  = CMDL.CODLINIECOMANDA
                                        INNER JOIN PROIECTEXT PEXT ON CC1.CODPROIECT   = PEXT.CODPROIECT
                                   WHERE C1.CODCOMANDA1 = ' || coalesce(current_setting('PKG_LIST_BASE_PRODCOMP.p_CodComanda1', true),'') || '
                                   )
                     LOOP
                       PERFORM pkg_list_Struct_ADAUGA_PARAM(''' || coalesce(V_CFG.NUMECAMP,'') || ''', v_rec.' || coalesce(V_CFG.NUMECAMP,'') || ');
                       EXIT;
                     END LOOP;
                   END $$;';
          EXECUTE SSQL;
        ELSE
          BEGIN
            EXECUTE 'select PEXT.' || coalesce(V_CFG.NUMECAMP,'') || '
                     FROM COMANDA1 C1
                          INNER JOIN CMDLINK    CMDL ON CMDL.CODCOMANDA1 = C1.CODCOMANDA1
                          INNER JOIN COMANDA1   CC1  ON CC1.CODCOMANDA1  = CMDL.CODLINIECOMANDA
                          INNER JOIN PROIECTEXT PEXT ON CC1.CODPROIECT   = PEXT.CODPROIECT
                     WHERE C1.CODCOMANDA1 = ' || coalesce(current_setting('PKG_LIST_BASE_PRODCOMP.p_CodComanda1', true),'') INTO ValCamp;
          EXCEPTION WHEN others THEN
            ValCamp := 0;
          END;

          IF  ValCamp &gt; 0 THEN
            Display := REPLACE(v_cfg.lookupdisplay, ';', '||'';''||');

            IF  V_CFG.NOMLINK = 1 THEN
              BEGIN
                EXECUTE 'select ' || coalesce(Display,'') || ' from nartobj where codobiect = ' || coalesce(ValCamp::varchar,'') INTO ValDisplay;
              EXCEPTION WHEN others THEN
                ValDisplay := '';
              END;
            ELSE IF  V_CFG.NOMLINK = 2 THEN
              BEGIN
                EXECUTE 'select ' || coalesce(Display,'') || ' from npart where codpart = ' || coalesce(ValCamp::varchar,'') INTO ValDisplay;
              EXCEPTION WHEN others THEN
                ValDisplay := '';
              END;
            ELSE IF  V_CFG.NOMLINK = 3 THEN
              BEGIN
                EXECUTE 'select ' || coalesce(Display,'') || ' from npers where codpers = ' || coalesce(ValCamp::varchar,'') INTO ValDisplay;
              EXCEPTION WHEN others THEN
                ValDisplay := '';
              END;
            ELSE IF  V_CFG.NOMLINK = 4 THEN
              BEGIN
                EXECUTE 'select ' || coalesce(Display,'') || ' from contract where codcontract = ' || coalesce(ValCamp::varchar,'') INTO ValDisplay;
              EXCEPTION WHEN others THEN
                ValDisplay := '';
              END;
            ELSE IF  V_CFG.NOMLINK = 5 THEN
              BEGIN
                EXECUTE 'select ' || coalesce(Display,'') || ' from nagenda where codagenda = ' || coalesce(ValCamp::varchar,'') INTO ValDisplay;
              EXCEPTION WHEN others THEN
                ValDisplay := '';
              END;
            END IF; END IF; END IF; END IF; END IF;

            PERFORM pkg_list_Struct_ADAUGA_PARAM(V_CFG.NUMECAMP, ValDisplay);
          END IF;
        END IF;
      END LOOP;
    END IF;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_prodcomp_processparamsret</obj_name>
  <obj_hashval>78ca5009e9e2245837e298499475fb45</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_prodcomp_processparamsret()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Adina 14.10.2020
  --Florin 15.02.2021 - fixat 43211
  --Florin 14.01.2022 - fixat 52618
  PERFORM pkg_list_Struct_GOLESTE_PARAM();
  FOR v_rec IN
      (
        SELECT   OBJ.CodObiect, OBJ.Denumire, P.Obs, P.Data, P.Cant, P.D1, P.D2, P.D3, NUM.Den_UM,
                CASE WHEN  P.TipReteta = 1 THEN 'Agregare' ELSE 'Dezagregare' END  TIPRETETA,
                P.Den_UMSpec, P.CantUM1, P.Coefindirecte, P.Pret,
                COALESCE(P.ValMat, 0) VALMAT, COALESCE(P.ValMan, 0) VALMAN, COALESCE(P.ValRegie, 0) VALREGIE, OBJ.CODINTERN, OBJ.CODEXTERN,
                to_char(P.DATA, 'dd.mm.yyyy') DATAI, P.Arhiva, coalesce(PE.NUME,'') || ' ' || coalesce(PE.PRENUME,'') NUME_PRENUME,
                (
                  SELECT max(l.data)
                  FROM winmadmin.Log l
                  WHERE l.tabela = 'PRODCOMP' AND  l.operatie = 'M' and  l.coddoc = p.codprodcomp
                ) DATAU,
                P.Descriere, P.OBS1, P.OBS2, P.OBS3, P.OBS4, P.OBS5, P.OBS6, CLS.DEN_CLASEPROD
        FROM   TMP_PRODCOMP P
              INNER JOIN NARTOBJ   OBJ ON  P.CodObiect      = OBJ.CodObiect
              INNER JOIN NART      ART ON  OBJ.CodArticol   = ART.CodArticol
              INNER JOIN NUM           ON  ART.UM           = NUM.CodUM
              LEFT JOIN NPERS      PE  ON  PE.CodPers       = P.PROIECTANT
              LEFT JOIN NCLASEPROD CLS ON  CLS.CODCLASEPROD = P.CODCLASAPROD
        WHERE P.CodProdComp = current_setting('PKG_LIST_BASE_PRODCOMP.p_CodProdComp', true)::numeric
      )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DenArt',                             v_rec.Denumire);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('CodObiect',                         v_rec.CodObiect::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Obs',                               v_rec.Obs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Observatii1',                       v_rec.Obs1);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Observatii2',                       v_rec.Obs2);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Observatii3',                       v_rec.Obs3);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Observatii4',                       v_rec.Obs4);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Observatii5',                       v_rec.Obs5);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Observatii6',                       v_rec.Obs6);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Clasa',                             v_rec.den_claseprod);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Descriere',                         v_rec.Descriere);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Cantitati pe',                       trunc(v_rec.Cant)::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Data',                               to_char(v_rec.DATA,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('D1',                                 v_rec.D1::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('D2',                                 v_rec.D2::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('D3',                                 v_rec.D3::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('UM',                                 v_rec.Den_UM);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Tip reteta',                         v_rec.TipReteta);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('UM specifica',                       v_rec.Den_UMSpec);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Cant UM specifica',                 v_rec.CantUM1::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Indice cheltuieli indirecte',       v_rec.Coefindirecte::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Pret',                               v_rec.Pret::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Valoare materiale pe UM produs',     v_rec.ValMat::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Valoare manopera pe UM produs',     v_rec.ValMan::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Valoare regie pe UM produs',         v_rec.ValRegie::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Cod extern produs finit',           v_rec.CodExtern);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Cod intern produs finit',           v_rec.CodIntern);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Numar desen/iso',                   v_rec.Obs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Data intocmirii retetei',           v_rec.DataI);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Data ultimei modificari a retetei', to_char(v_rec.DataU,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Nr arhiva',                         v_rec.Arhiva);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Intocmit nume si prenume',           v_rec.Nume_Prenume);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_prodcomp_setjoinuri</obj_name>
  <obj_hashval>52424e351722b4848f172411d7d93643</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_prodcomp_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_PRODCOMP.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_prodcomp_setparams</obj_name>
  <obj_hashval>7ef732e4cd6522ea408d8cf51b32e2aa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_prodcomp_setparams(v_codprodcomp numeric, v_codcomanda1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.10.2020
  perform set_config('PKG_LIST_BASE_PRODCOMP.p_CodProdComp',(v_CodProdComp)::varchar,false);
  perform set_config('PKG_LIST_BASE_PRODCOMP.p_CodComanda1',(v_CodComanda1)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_prodnetman_processlist</obj_name>
  <obj_hashval>7747ebe193170eaf5970347bdfdd1b79</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_prodnetman_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR :=   'prodnet pn, prodnet1 pn1, comanda1 c1, nartobj obj, comanda c, noper op, centrecost cc, prodcomp pc';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 06.01.2021 - tichet 41964
  --Florin 05.01.2021 - nvl -&gt; coalesce

  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_PRODNETMAN.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
   'INSERT INTO ' || coalesce(tmpname,'') || '
    (OBSERVATII, SECTIE, EXPLICATII, VALMAN, DIFCANT, CANTREAL, PRET, CANT, NRDOC, DATADOC, DENUMIRE, OPERATIE, CENTRU, SUBUNITATEA ' || gUserFields || ')
    SELECT PN.Obs, G.DEN_GEST, 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, S.DEN_SUBUNIT ' || gUserAlias || '
    FROM PRODNET            PN
      INNER JOIN NGEST      G   ON PN.CODGEST        = G.CODGEST
      INNER JOIN PRODNET1   PN1 ON PN1.CODPRODNET    = PN.CODPRODNET
      INNER join comanda1   c1  on pn1.coddoc1       = c1.codcomanda1
      INNER join prodcomp   pc  on c1.codreteta      = pc.codprodcomp
      INNER join nartobj    obj on c1.codobiect      = obj.codobiect
      INNER join comanda    c   on c1.codcomanda     = c.codcomanda
      INNER JOIN NSUBUNIT   S   ON S.CODSUBUNIT      = PN.SUBUNITATEA
      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.AN*12+PN.LUNA = GetANLUCRU()*12+GetLUNALUCRU() AND coalesce(PN1.Tip,0) = 1';

  IF getSUBUNITATE() &gt; 1 THEN
    sInsert := sInsert || ' AND PN.SUBUNITATEA = GETSUBUNITATE()';
  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_prodnetmat_processlist</obj_name>
  <obj_hashval>454a7f56753a0da2fa1c3dc0241cd1a1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_prodnetmat_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'prodnet pn, prodnet1 pn1, comanda1 c1, nartobj obj, comanda c, iesiri1 i1, nartobj objmat, centrecost cc,prodcomp pc';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 14 septembrie 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_PRODNETMAT.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || tmpname || ' (OBSERVATII, SECTIE, EXPLICATII, VALMAT, DIFCANT, CANTREAL, PRET, CANT, NRDOC, DATADOC, DENUMIRE, MATERIAL, CENTRU, SUBUNITATEA ' || gUserFields || ')
  SELECT PN.Obs, G.DEN_GEST, 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, S.DEN_SUBUNIT ' || gUserAlias || '
  FROM PRODNET PN
    INNER JOIN NGEST      G      ON PN.CODGEST                = G.CODGEST
    INNER JOIN PRODNET1   PN1    ON PN1.CODPRODNET            = PN.CODPRODNET
    INNER join comanda1   c1     on pn1.coddoc1               = c1.codcomanda1
    INNER join nartobj    obj    on c1.codobiect              = obj.codobiect
    INNER join comanda    c      on c1.codcomanda             = c.codcomanda
    INNER JOIN NSUBUNIT   S      ON S.CODSUBUNIT              = PN.SUBUNITATEA
    INNER join prodcomp   pc     on c1.codreteta              = pc.codprodcomp
    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.AN*12+PN.LUNA = GetANLUCRU()*12+GetLUNALUCRU() AND coalesce(PN1.Tip,0) = 0';

  IF  getSUBUNITATE() &gt; 1 THEN
    sInsert := sInsert || ' AND PN.SUBUNITATEA = GETSUBUNITATE()';
  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_prodnetmat_setjoinuri</obj_name>
  <obj_hashval>685b98bce3acb76fdd59fa347d15e888</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_prodnetmat_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14 septembrie 2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_PRODNETMAT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_profit_getteries</obj_name>
  <obj_hashval>415d30aef755fcfb82df09294434d6bf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_profit_getteries(vcodies numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aAVG  numeric;
  aData date;
BEGIN
  --Adina 15.12.2020 tichet 41622
  --Florin 31.08.2020
  IF COALESCE(vCodIes, 0) = 0 THEN
    RETURN 0;
  ELSE
    SELECT I.Datadoc INTO aData FROM iesiri i WHERE i.codies = vCodIes;

    BEGIN
      SELECT round((COALESCE(AVG(O.Termen::date - I.DataDoc::date), 0))::numeric, 0)
      INTO aAVG
      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
      WHERE i.codies = vCodIes;
    EXCEPTION WHEN others THEN
      aAVG := 0;
    END;

    RETURN aAVG;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_profit_getterin</obj_name>
  <obj_hashval>e6adf5115998a62d45dae2e2acba94ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_profit_getterin(vcodintr numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aAVG  numeric;
  aData date;
BEGIN
  --Florin 31.08.2020
  IF COALESCE(vCodIntr, 0) = 0 THEN
    RETURN 0;
  ELSE
    SELECT I.Datadoc
    INTO aData
    FROM intrari i
    WHERE i.codintr = vCodIntr;

    SELECT round((COALESCE(AVG(O.Termen - I.DataDoc), 0))::numeric, 0)
    INTO aAVG
    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
    WHERE i.codintr = vCodIntr;

    RETURN aAVG;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_profit_getvalnc</obj_name>
  <obj_hashval>f63d26d5f1970cd16420bb8795c19a11</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_profit_getvalnc(acodintr1 numeric, atip numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTipDoc   numeric;
  vCodIntr1 numeric;
  vDisc     numeric;
BEGIN
  --Florin 31.08.2020
  vDisc := 0;
  BEGIN
    SELECT i.tipdoc
    INTO vTipDoc
    FROM intrari i INNER JOIN intrari1 i1 ON  i1.codintr = i.codintr
    WHERE i1.codintr1 = aCodIntr1;
  EXCEPTION WHEN OTHERS THEN
    vTipDoc := 0;
  END;

  IF vTipDoc = 2 THEN
    SELECT COALESCE(SUM(NC1.VALOARE), 0)
    INTO vDisc
    FROM NOTECREDIT NC
        INNER JOIN NOTECREDIT1 NC1 ON  NC.CODNCREDIT = NC1.CODNCREDIT
        INNER JOIN intrari1    i1  ON  nc1.coddoc    = i1.codintr1
        INNER JOIN intrari     i   ON  i1.codintr    = i.codintr and  nc1.tipdoc = i.tipdoc
        INNER JOIN intrlink    l   ON  l.codintr1    = i1.codintr1
    WHERE NC.TIPDOC = 59 AND  NC1.TIP = aTip and  l.codlinieaviz = aCodIntr1;
  ELSIF vTipDoc &gt; 0 THEN
    SELECT COALESCE(SUM(NC1.VALOARE), 0)
    INTO vDisc
    FROM NOTECREDIT NC
        INNER JOIN NOTECREDIT1 NC1 ON  NC.CODNCREDIT = NC1.CODNCREDIT
        INNER JOIN intrari1    i1  ON  nc1.coddoc    = i1.codintr1
        INNER JOIN intrari     i   ON  i1.codintr    = i.codintr and  nc1.tipdoc = i.tipdoc
    WHERE NC.TIPDOC = 59 AND  NC1.TIP = aTip and  i1.codintr1 = aCodIntr1;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_profit_setjoinuri</obj_name>
  <obj_hashval>47bf1e8ba28d3df0c31d9b2a21e12802</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_profit_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 31.08.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_PROFIT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_proglunfab_setparams</obj_name>
  <obj_hashval>f0a279af990bce30f7c722a403e422dc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_proglunfab_setparams(pcentralizare numeric, pneoperate numeric, pziuaini character varying, pziuafin character varying, plunar numeric, v_codjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
BEGIN
  --Florin 14.09.2020
  PERFORM set_config('PKG_LIST_BASE_PROGLUNFAB.vCentralizare', (COALESCE(pCentralizare, 0) = 1)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_PROGLUNFAB.vNeoperate'   , (COALESCE(pNeoperate, 0) = 1)   ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_PROGLUNFAB.vLunar'       , (COALESCE(pLunar,0) = 1)        ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_PROGLUNFAB.vZiuaIni', pZiuaIni  , FALSE);
  PERFORM set_config('PKG_LIST_BASE_PROGLUNFAB.vZiuaFin', pZiuaFin  , FALSE);

  IF COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, current_setting('PKG_LIST_BASE_PROGLUNFAB.vZiuaIni', true), current_setting('PKG_LIST_BASE_PROGLUNFAB.vZiuaFin', true), xLunaAnIni, xLunaAnFin);
  END IF;

  PERFORM PKG_ORA_LISTS_SET_INTERVAL_LISTARE(to_date(current_setting('PKG_LIST_BASE_PROGLUNFAB.vZiuaIni', true), 'dd.mm.yyyy'),
    to_date(current_setting('PKG_LIST_BASE_PROGLUNFAB.vZiuaFin', true), 'dd.mm.yyyy'));
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_proiect_setjoinuri</obj_name>
  <obj_hashval>ed46fc77880f25844ab25389810fef17</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_proiect_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_PROIECT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_proiect_setparams</obj_name>
  <obj_hashval>a3d71017b6404a17dcbbaa64a52d0d76</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_proiect_setparams(acodproiect numeric, acodcomanda1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  perform set_config('PKG_LIST_BASE_PROIECT.p_CodProiect' ,(aCodProiect)::varchar ,false);
  perform set_config('PKG_LIST_BASE_PROIECT.p_CodComanda1',(aCodComanda1)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_proiecte_processlist</obj_name>
  <obj_hashval>d0188793371d570df6586e2596bbf4e1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_proiecte_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;
  sSelect0    varchar;
  sSelect1    varchar;
  gStocField  varchar;
  gStocAlias  varchar;
  gJoinStoc   varchar;
  gUserId     numeric;
  AnLunaLucru NUMERIC;
BEGIN
  --Laura 08.12.2021 - sinc. Oracle (07.12.2021)
  --Adina 27.04.2021 - alstart,alstop
  --Adina 20.04.2021 - sinc.Oracle
  --Bogdan 14.09.2020
  perform set_config ('PKG_LIST_BASE_PROIECTE.p_flgAllArt' , (pkg_list_base_consum_prod_GetAllArt())  ::varchar,false);
  perform set_config ('PKG_LIST_BASE_PROIECTE.p_Sursa'     , (pkg_list_base_consum_prod_GetSursa())   ::varchar,false);
  perform set_config ('PKG_LIST_BASE_PROIECTE.p_Tip'       , (pkg_list_base_consum_prod_GetTip())     ::varchar,false);
  perform set_config ('PKG_LIST_BASE_PROIECTE.p_Stoc'      , (pkg_list_base_consum_prod_GetStoc())    ::varchar,false);
  perform set_config ('PKG_LIST_BASE_PROIECTE.p_flgAllGest', (pkg_list_base_consum_prod_GetAllGest()) ::varchar,false);
  gUserID    := current_setting ('PKG_GLOBALS.USERID', true) ::numeric;
  gStocField := ' ';
  gStocAlias := ' ';
  gJoinStoc  := ' ';

  CALL PRC_AL_CHECK('nartobj1', 0);
  AnLunaLucru := getAnLucru() * 12 + getLunaLucru();

  IF current_setting ('PKG_LIST_BASE_PROIECTE.p_Stoc', true) ::numeric = 1 THEN
    gStocAlias := ' ,Stoc ';
    gStocField := ' ,coalesce(tmpp.Cant,0) ';
    gJoinStoc  := '
                 left join tmp_planifstoc tmpp on tmpp.codobiect = mat.codobiect ';
  END IF;

  gSuplCols := 'NARTOBJ OBJP, NARTOBJ OBJC, NARTOBJSUBUNIT OBJCS, NARTOBJSUBUNIT OBJPS, PRODCOMP PC, PRODMAT MAT, NCLASEA CLSCOMP, NGEST SECTIE, PROIECTNOD PN, PROIECT P';

  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_PROIECTE.gSuplCols',gSuplCols,false);

  IF current_setting ('PKG_LIST_BASE_PROIECTE.p_flgAllArt', true) ::numeric = 1 THEN
    DELETE FROM tmp_proiectnod_man WHERE userid = gUserID;

    INSERT INTO TMP_PROIECTNOD_MAN (CodProiect, CodObiect, Cant, necesar, UserID)
    SELECT pn.codproiect, pn.codobiect, pn.cant, pc.pret, gUserID
    FROM proiectnod pn INNER JOIN prodcomp pc ON pc.codprodcomp = pn.codreteta
    WHERE nodoriginal = 0;
  END IF;

  DELETE FROM tmp_planifstoc;

  IF current_setting ('PKG_LIST_BASE_PROIECTE.p_Stoc', true) ::numeric = 1 THEN
    IF current_setting ('PKG_LIST_BASE_PROIECTE.p_flgAllGest', true) ::numeric = 1 THEN
      INSERT INTO TMP_PLANIFSTOC (CODOBIECT, CANT)
      SELECT CODOBIECT, sum (REST)
      FROM (SELECT NS.CODOBIECT, CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.REST ELSE NSE.REST END REST
            FROM NIRSTOC                NS
              INNER JOIN IOART1      io  ON io.codioart = ns.codioart and AnLunaLucru between io.ALStart and io.ALStop
              INNER JOIN NIR            N   ON N.CODNIR    = NS.CODNIR
              INNER JOIN NGEST          G   ON G.CODGEST   = N.GEST and (G.CODSUBUNIT = current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric
                                                                        OR current_setting ('PKG_GLOBALS.SUBUNITATE', true) ::numeric = 1)
              LEFT JOIN NIRSER          NSE ON NS.CODNIRSTOC = NSE.CODNIRSTOC
            WHERE IO.MG &lt;&gt; 5
           ) A_PG
      GROUP BY CODOBIECT;
    ELSE
      INSERT INTO TMP_PLANIFSTOC (CODOBIECT, CANT)
      SELECT CODOBIECT, sum (REST)
      FROM (SELECT NS.CODOBIECT, CASE WHEN COALESCE (NSE.CODNIRSER, 0) = 0 THEN NS.REST ELSE NSE.REST END REST
            FROM NIRSTOC       NS
              INNER JOIN NIR   N   ON N.CODNIR      = NS.CODNIR
              INNER JOIN NGEST G   ON G.CODGEST     = N.GEST
              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)
           ) B_PG
      GROUP BY CODOBIECT;
    END IF;
  END IF;

  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,
              PR_PRET_IMP,
              NOD,
              LotOptim,
              PretAchizU,
              Ordine'
              || coalesce (gStocAlias,'')
              || coalesce (gUserFields ,'')
              || ')
            ';

  sSelect0 := '
          WITH PMin As
            ( 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) / U1.PARITATE) END
                                     ) * coalesce (u1.Paritate,0)
                                   ) , 0) Pret,
                     NS.CODOBIECT
              FROM NIRSTOC NS
                INNER JOIN NIR       ON NS.CODNIR = NIR.CODNIR
                INNER JOIN NGEST  G  ON G.CODGEST = NIR.GEST
                LEFT  JOIN NUM1   U1 ON NS.Umsec  = U1.Codum1
              WHERE
                G.Tip &lt;&gt; 4
                and NS.Rest &gt; 0
                AND G.CODSUBUNIT = (case when getsubunitate() = 1 then 2 else getsubunitate() end)
              GROUP BY NS.CODOBIECT
            )
            ,
            PMin0 as
            (   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) / U1.PARITATE) END
                                       ) * coalesce (u1.Paritate,0)
                                     ) , 0) Pret,
                       NS.CODOBIECT
              FROM NIRSTOC NS
                INNER JOIN NIR       ON NS.CODNIR = NIR.CODNIR
                INNER JOIN NGEST  G  ON G.CODGEST = NIR.GEST
                LEFT  JOIN NUM1   U1 ON NS.Umsec  = U1.Codum1
              WHERE
                G.Tip &lt;&gt; 4
                and NS.Rest &lt;= 0
                AND G.CODSUBUNIT = (case when getsubunitate() = 1 then 2 else getsubunitate() end)
              GROUP BY NS.CODOBIECT
            )
            ,
            PMax as
            (   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) / U1.PARITATE) END
                                       ) * coalesce (u1.Paritate,0)
                                     ) , 0) Pret,
                       NS.CODOBIECT
              FROM NIRSTOC NS
                INNER JOIN NIR       ON NS.CODNIR = NIR.CODNIR
                INNER JOIN NGEST  G  ON G.CODGEST = NIR.GEST
                LEFT  JOIN NUM1   U1 ON NS.Umsec  = U1.Codum1
              WHERE
                G.Tip &lt;&gt; 4
                and NS.Rest &gt; 0
                AND G.CODSUBUNIT = (case when getsubunitate() = 1 then 2 else getsubunitate() end)
              GROUP BY NS.CODOBIECT
            )
            ,
            PMax0 as
            (   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) / U1.PARITATE) END
                                       ) * coalesce (u1.Paritate,0)
                                     ) , 0) Pret,
                       NS.CODOBIECT
              FROM NIRSTOC NS
                INNER JOIN NIR       ON NS.CODNIR = NIR.CODNIR
                INNER JOIN NGEST  G  ON G.CODGEST = NIR.GEST
                LEFT  JOIN NUM1   U1 ON NS.Umsec  = U1.Codum1
              WHERE
                G.Tip &lt;&gt; 4
                and NS.Rest &lt;= 0
                AND G.CODSUBUNIT = (case when getsubunitate() = 1 then 2 else getsubunitate() end)
              GROUP BY NS.CODOBIECT
            )
          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.Pret,0) = 0 then coalesce (PMin0.Pret,0) else coalesce (PMin.Pret,0) end,
            MAT.Cant * case when coalesce (PMin.Pret,0) = 0 then coalesce (PMin0.Pret,0) else coalesce (PMin.Pret,0) end,
            case when coalesce (PMax.Pret,0) = 0 then coalesce (PMax0.Pret,0) else coalesce (PMax.Pret,0) end,
            MAT.Cant * case when coalesce (PMax.Pret,0) = 0 then coalesce (PMax0.Pret,0) else coalesce (PMax.Pret,0) end,
            (case when coalesce (PMax.Pret,0) = 0 then coalesce (PMax0.Pret,0) else coalesce (PMax.Pret,0) end
             +
             case when coalesce (PMin.Pret,0) = 0 then coalesce (PMin0.Pret,0) else coalesce (PMin.Pret,0) end
            ) / 2,
            MAT.Cant * (case when coalesce (PMax.Pret,0) = 0 then coalesce (PMax0.Pret,0) else coalesce (PMax.Pret,0) end
                         +
                        case when coalesce (PMin.Pret,0) = 0 then coalesce (PMin0.Pret,0) else coalesce (PMin.Pret,0) end
                       ) / 2,
            ( select wme_result from PKG_PMP_GET_PMP_LAST (null, Mat.CodObiect,  (case when getsubunitate() = 1 then 2 else getsubunitate() end)) ),
            MAT.Cant * (select wme_result from PKG_PMP_GET_PMP_LAST (null,Mat.CodObiect,  ( case when getsubunitate() = 1 then 2 else getsubunitate() end))) ,
            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) ,
            PM.Lei,
            X.IND,
            PCP.CANT,
            pkg_list_base_consum_prod_getlastpretachiz (objc.codobiect) ,
            substr (x.ind,5, length (x.ind) -3) ' || coalesce (gStocField,'') || coalesce (gUserAlias ,'') || '
          FROM PROIECT                    P
            INNER JOIN TMP_PROIECTNOD_MAN TMP     ON P.CodProiect    = TMP.CodProiect and tmp.userid = ' || coalesce (gUserID::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 = getsubunitate()
            left join NARTOBJSUBUNIT      OBJPS   on objp.codobiect  = objps.codobiect and (OBJPS.codgest is null or OBJPS.codgest = 0) and objps.subunitate = getsubunitate()
            LEFT JOIN pretm               pm      ON pm.codobiect    = OBJP.codobiect AND pm.implicit = 1 AND pm.subunitatea =  (case when getsubunitate() = 1 then 2 else getsubunitate() end)
            LEFT JOIN PROIECTNOD          PNP     ON PN.NODORIGINAL  = PNP.CODPROIECTNOD
            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 NARTOBJ1            P1      ON P1.CodObiect    = OBJP.CodObiect AND '||AnLunaLucru||' BETWEEN P1.ALStart and P1.ALStop
            LEFT JOIN NARTOBJ1            C1      ON C1.CodObiect    = OBJC.CodObiect AND '||AnLunaLucru||' BETWEEN C1.ALStart and C1.ALStop
            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 PMin                        on PMin.COdObiect  = Mat.CodObiect
            LEFT JOIN PMin0                       on PMin0.COdObiect = Mat.CodObiect
            LEFT JOIN PMax                        on PMax.COdObiect  = Mat.CodObiect
            LEFT JOIN PMax0                       on PMax0.COdObiect = Mat.CodObiect '
              || coalesce (gJoinStoc,'')
              || coalesce (gSuplJoins ,'') ;

  sSelect1 := '
          WITH PretMin As
            ( SELECT Min (O1.PRET) pret,
                O1.CodObiect
              FROM OFERTA1        O1
                INNER JOIN OFERTA O ON O1.CODOFERTA = O.CODOFERTA
              WHERE
                (getAnLucru()     * 12 + getLunaLucru() &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 (getAnLucru() * 12 + getLunaLucru() &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 getsubunitate() = 1 then 2 else getsubunitate() end)
              GROUP BY O1.CodObiect
            )
            ,
            PretMax as
            ( SELECT Min (O1.PRET) pret,
                O1.CodObiect
              FROM OFERTA1          O1
                INNER JOIN OFERTA O ON O1.CODOFERTA = O.CODOFERTA
              WHERE
                (getAnLucru()     * 12 + getLunaLucru() &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 (getAnLucru() * 12 + getLunaLucru() &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 getsubunitate() = 1 then 2 else getsubunitate() end)
              GROUP BY O1.CodObiect
            )
          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.Pret,0) ,
            MAT.Cant * coalesce (PretMin.Pret,0) ,
            coalesce (PretMax.Pret,0) ,
            MAT.Cant * coalesce (PretMax.Pret,0) ,
            (coalesce (PretMax.Pret,0) + coalesce (PretMin.Pret,0)) /            2,
            MAT.Cant * (coalesce (PretMax.Pret,0) + coalesce (PretMin.Pret,0)) / 2,
            (select wme_Result from PKG_PMP_GET_PMP_LAST (null,Mat.CodObiect, (case when getsubunitate() = 1 then 2 else getsubunitate() end))) ,
            MAT.Cant * (select wme_result from PKG_PMP_GET_PMP_LAST (null,Mat.CodObiect, (case when getsubunitate() = 1 then 2 else getsubunitate() end))) ,
            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) ,
            Lei,
            X.IND,
            PCP.CANT,
            pkg_list_base_consum_prod_getlastpretachiz (objc.codobiect) ,
            substr (x.ind,5, length (x.ind) -3) ' || coalesce (gStocField,'') || coalesce (gUserAlias ,'') || '
          FROM PROIECT                    P
            INNER JOIN TMP_PROIECTNOD_MAN TMP     ON P.CodProiect    = TMP.CodProiect and tmp.userid = '|| coalesce (gUserID::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 = getsubunitate()
            left join NARTOBJSUBUNIT      OBJPS   on objp.codobiect  = objps.codobiect
                                                    and (OBJPS.codgest is null or OBJPS.codgest = 0)
                                                    and objps.subunitate = getsubunitate()
            LEFT JOIN pretm               pm      ON pm.codobiect    = OBJP.codobiect AND pm.implicit = 1 AND pm.subunitatea =  (case when getsubunitate() = 1 then 2 else getsubunitate() end)
            LEFT JOIN PROIECTNOD          PNP     ON PN.NODORIGINAL  = PNP.CODPROIECTNOD
            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 NARTOBJ1            P1      ON P1.CodObiect = OBJP.CodObiect AND '||AnLunaLucru||' BETWEEN P1.ALStart and P1.ALStop
            LEFT JOIN NARTOBJ1            C1      ON C1.CodObiect = OBJC.CodObiect AND '||AnLunaLucru||' BETWEEN C1.ALStart and C1.ALStop
            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 PretMin                                           on PretMin.COdObiect = Mat.CodObiect
            LEFT JOIN PretMax                                           on PretMax.COdObiect = Mat.CodObiect '
              || coalesce (gJoinStoc,'') || coalesce (gSuplJoins ,'');

  IF current_setting ('PKG_LIST_BASE_PROIECTE.p_Sursa', true) ::numeric = 0 THEN
    sSelect := sSelect0;
  ELSE
    sSelect := sSelect1;
  END IF;

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

  DELETE    FROM tmp_proiectnod_man WHERE userid = gUserID;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_proiecte_setjoinuri</obj_name>
  <obj_hashval>84241dbc7e1c731169a24b4a4fb1602c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_proiecte_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 14.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec (current_setting ('PKG_LIST_BASE_PROIECTE.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_promo_setjoinuri</obj_name>
  <obj_hashval>32e14c4417c69e983b23ec8e8530b1be</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_promo_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  PERFORM pkg_list_struct_SetTableSpec (current_setting ('PKG_LIST_BASE_PROMO.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_promo_setparams</obj_name>
  <obj_hashval>fc1d67fe03c386d6e196c04f3d1a4046</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_promo_setparams(pdataini character varying, pdatafin character varying, ptotipart numeric DEFAULT 1, pgruppart numeric DEFAULT 1, v_codjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sDataIni varchar(10);
  sDataFin varchar(10);

  vDataIni date;
  vDataFin date;

  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
begin
  --Florin 11.10.2021 - sinc. Oracle (50704)
  --Bogdan 10.09.2020
  perform set_config ('PKG_LIST_BASE_PROMO.vTotiPart',Coalesce(pTotiPart,1)::varchar,false);
  perform set_config ('PKG_LIST_BASE_PROMO.vGrupPart',Coalesce(pGrupPart,1)::varchar,false);

      vDataIni  := To_Date(pDataIni,'dd.mm.yyyy');
    vDataFin  := To_Date(pDataFin,'dd.mm.yyyy');


  IF COALESCE (v_CodJob1, 0) &gt; 0 THEN
    select PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.adataini, PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.adatafin
    from PKG_ORA_LISTS_SET_INTERVAL_DINAMIC (V_CODJOB1, vDataIni , vDataFin , xLunaAnIni, xLunaAnFin) into vDataIni , vDataFin;
  END IF;

  sDataIni := to_char(vDataIni,'dd.mm.yyyy');
  sDataFin := to_char(vDataFin,'dd.mm.yyyy');

  perform set_config ('PKG_LIST_BASE_PROMO.vDataIni',sDataIni,false);
  perform set_config ('PKG_LIST_BASE_PROMO.vDataFin',sDataFin,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_promodoc_processlist</obj_name>
  <obj_hashval>b3081d196ea0cc574011dece94a8eb51</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_promodoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols       varchar := 'PROMO P, PROMO1 P1, NARTOBJ O, NART A, NUM1 UM, NCLASEA CA';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodPromo        varchar := current_setting('PKG_LIST_BASE_PROMODOC.vCodPromo', true);
BEGIN
  --Florin 04.01.2022 - fixat 52472/52475/52476
  --Adina 01 octombrie 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_addsupltabs(gSuplCols, 'PROMO1CADOU', 'PC'  , 'PC.CODCADOU = TMP.CODCADOU'  , 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'PROMOPRAG'  , 'PP'  , 'PP.CODPRAG = TMP.CODPRAG'    , 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJ'    , 'OC'  , 'OC.CODOBIECT = PC.CODOBIECT' , 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'PROMOSUB'   , 'PS'  , 'PS.CODPROMO = P.CODPROMO AND PS.SUBUNITATEA = COALESCE(P.SUBUNITATEA,GETSUBUNITATE())', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'PRETM'      , 'PM'  , 'PM.CODOBIECT = O.CODOBIECT AND PM.SUBUNITATEA = Coalesce(P.SUBUNITATEA,GETSUBUNITATE()) AND PM.IMPLICIT = 1', 1);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_PROMODOC.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, PRETAMANUNT, DISC, ZILEC,
    TIPLIMITA,
    TG_MAX, ZILE_EXP, SERII,
    CADOU,
    ORDINE' || gUserFields || ')
  WITH TMP AS (
    SELECT
            P1.CODPROMO, P1.CODPROMO1, 0 CODCADOU, Coalesce(PP.CODPRAG, 0) CODPRAG,
            0 ORD1, CASE WHEN Coalesce(PP.CODPRAG, 0) = 0 THEN P1.CODPROMO1 ELSE PP.CODPRAG END ORD2,
            COALESCE(P1.CodObiect,0) CodObiect, Coalesce(P1.UMSec, 0) UMSec, P1.Cant, P1.Pret, P1.PretAmanunt,
            Coalesce(PP.ProcDisc, P1.ProcDisc) ProcDisc, P1.ZileC, P1.TipLimita, P1.TG_Max, P1.Zile_Exp,
            (  SELECT string_agg(s.serie,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' order by s.serie) serii
              FROM PROMO1SER S WHERE S.CodPROMO1 = P1.CodPROMO1
            ) Serii
    FROM   PROMO P
          INNER JOIN PROMO1 P1     ON P1.CodPROMO = P.CodPROMO
          LEFT  JOIN PROMOPRAG PP ON PP.CodPROMO = P.CodPROMO
    WHERE P.CodPROMO = ' || coalesce(vCodPromo,'') || '
    UNION ALL
    SELECT
            P1.CODPROMO, P1.CODPROMO1, PC.CODCADOU, 0 CODPRAG,
            0 ORD1, P1.CODPROMO1 ORD2,
            PC.CodObiect, Coalesce(PC.UMSec, 0) UMSec, PC.Cant, 0 Pret, 0 PretAmanunt,
            NULL ProcDisc, NULL ZileC, PC.TipLimita, PC.TG_Max, PC.Zile_Exp,
            (  SELECT string_agg(s.serie,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' order by s.serie) serii
              FROM PROMO1CADOUSER S WHERE S.CodCADOU = PC.CodCADOU
            ) Serii
    FROM   PROMO P
          INNER JOIN PROMO1 P1       ON P1.CodPROMO = P.CodPROMO
          INNER JOIN PROMO1CADOU PC ON PC.CodPromo = P.CodPROMO AND PC.CodPROMO1 = P1.CodPROMO1
    WHERE P.CodPROMO = ' || coalesce(vCodPromo,'') || '
          AND P.DEMANA IN (0,3)
    UNION ALL
    SELECT
            P.CODPROMO, 0 CODPROMO1, PC.CODCADOU, 0 CODPRAG,
            1 ORD1, 0 ORD2,
            PC.CodObiect, Coalesce(PC.UMSec, 0) UMSec, PC.Cant, 0 Pret, 0 PretAmanunt,
            NULL ProcDisc, NULL ZileC, PC.TipLimita, PC.TG_Max, PC.Zile_Exp,
            (  SELECT string_agg(s.serie,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' order by s.serie) serii
              FROM PROMO1CADOUSER S WHERE S.CodCADOU = PC.CodCADOU
            ) Serii
    FROM   PROMO P
          INNER JOIN PROMO1CADOU PC ON PC.CodPromo = P.CodPROMO
    WHERE P.CodPROMO = ' || coalesce(vCodPromo,'') || '
          AND NOT P.DEMANA IN (0,3)
  )
  SELECT
          CASE
              WHEN P.DeMana = 3 AND TMP.CodCadou = 0 THEN CA.DEN_CLASEA
              WHEN P.DeMana = 4 AND TMP.CodCadou = 0 THEN ''Toate articolele''
              ELSE O.Denumire
          END ART,
          UM.Den_UM1, TMP.Cant / UM.Paritate CANT,
          TMP.Pret * UM.Paritate PRET,
          TMP.PretAmanunt * UM.Paritate PRETAMANUNT,
          TMP.ProcDisc, TMP.ZileC,
          CASE TMP.TipLimita
              WHEN 3 THEN ''Serie''
              WHEN 2 THEN ''Zile expirare &lt;= ''||TMP.Zile_Exp
              WHEN 1 THEN ''Data expirare &lt;= ''||To_Char(TMP.TG_Max,''dd.mm.yyyy'')
              ELSE ''Stoc disponibil''
          END TIPLIMITA,
          TMP.TG_Max, TMP.Zile_Exp, TMP.Serii,
          CASE WHEN TMP.CodCadou = 0 THEN ''Nu'' ELSE ''Da'' END CADOU,
          DENSE_RANK() OVER (PARTITION BY TMP.CodPromo ORDER BY TMP.ORD1, TMP.ORD2, TMP.CodCadou) ORDINE' || gUserAlias || '
  FROM   TMP
        LEFT JOIN PROMO P    ON P.CodPromo   = TMP.CodPromo
        LEFT JOIN PROMO1 P1  ON P1.CodPromo1 = TMP.CodPromo1
        LEFT JOIN NARTOBJ O  ON O.CodObiect  = TMP.CodObiect
        LEFT JOIN NART A     ON A.CodArticol = O.CodArticol
        LEFT JOIN NUM1 UM    ON UM.CodUM1    = TMP.UMSec
        LEFT JOIN NCLASEA CA ON CA.CodClaseA = CASE P.DeMana WHEN 3 THEN P1.CODCLASEA ELSE A.Clasa END' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  PERFORM pkg_list_base_promodoc_ADD_LIST_PARAMS();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_promodoc_setjoinuri</obj_name>
  <obj_hashval>0b5057fd51c6b776aad91087f602eb11</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_promodoc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01 octombrie 2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_PROMODOC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_promodoc_setparams</obj_name>
  <obj_hashval>3dbc25117385ab95430d9b08f4c9b676</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_promodoc_setparams(pcodpromo numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01 octombrie 2020
  perform set_config('PKG_LIST_BASE_PROMODOC.vCodPROMO',(pCodPROMO)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rac_dashman_doc_processlist</obj_name>
  <obj_hashval>e87da79d50f395bdc9ee9a3608073ca2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rac_dashman_doc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
BEGIN
  --Florin 17.03.2023 - to_char
  --Adina 15.10.2020
  sInsert :=
  'INSERT INTO ' || tmpName || '(
     Cod,gest, data, Analiza, Cantitate, ZileRez, DurataMedie, RPD, VenitTotal)
  SELECT
     Cod,gest, data, Analiza,
    (case when Cantitate  =''0'' then ''0.0'' else Cantitate::varchar end),
    (case when ZileRez    =''0'' then ''0.0'' else ZileRez::varchar end),
     (case when DurataMedie=''0'' then ''0.0'' else DurataMedie::varchar end),
    (case when RPD        =''0'' then ''0.0'' else RPD::varchar end),
    (case when VenitTotal =''0'' then ''0.0'' else VenitTotal::varchar end)
  FROM RACDASHMAN_DOC ORDER BY COD asc';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rac_dashman_doc_setparams</obj_name>
  <obj_hashval>347b4d4330bee58e08b021de55ac6af2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rac_dashman_doc_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  perform set_config('PKG_LIST_BASE_RAC_DASHMAN_DOC.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rac_dashop_doc_processlist</obj_name>
  <obj_hashval>322cc3f20243c0296d584dff9a65ee4c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rac_dashop_doc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
BEGIN
  --Florin 08.03.2023 - corectie to_char
  --Adina 15.10.2020
  sInsert :=
  'INSERT INTO ' || tmpName || '(Cod,Gest,Data,Detaliu,Valoare)
   SELECT Cod,Gest,Data,Detaliu, (case when Valoare=''0'' then ''0.0'' else Valoare::varchar end)
   FROM RACDASHOP_DOC ORDER BY COD asc';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rac_dashop_doc_setparams</obj_name>
  <obj_hashval>5b693c641f8c66b18b725d92cdf21092</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rac_dashop_doc_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  perform set_config('PKG_LIST_BASE_RAC_DASHOP_DOC.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rac_detinfo_processlist</obj_name>
  <obj_hashval>afb103541ecae3fcdd3c6621aca40f5e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rac_detinfo_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
BEGIN
  --Adina 14.08.2021 - sinc.Oracle
  --Adina 15.10.2020
  sInsert :=
  'INSERT INTO ' || tmpName || '(Cod,Subunitate, Gestiune, Locatie, Clasa, NRAuto,Marca,Model,AnFab,KmBord,Comb,DataBord,Status)
   SELECT Cod,Subunitate, Gestiune, Locatie, Clasa, NRAuto,Marca,Model,AnFab,KmBord,Comb,DataBord,Status
   FROM TMP_RACDetaliereInfo ORDER BY COD asc';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rac_detinfo_setparams</obj_name>
  <obj_hashval>20ec45adb454d70bddef7948d33fa830</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rac_detinfo_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  perform set_config('PKG_LIST_BASE_RAC_DETINFO.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rac_detinfog_processlist</obj_name>
  <obj_hashval>9250b4c705f625d6c7fb0dd33e545b38</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rac_detinfog_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
BEGIN
  --Adina 14.08.2021 - sinc.Oracle din 14.08.2021
  --Adina 15.10.2020
  sInsert :=
  'INSERT INTO ' || tmpName || '(Cod,Subunitate, Gestiune, Locatie, Clasa, NRAuto,Marca,Model,DataSosire,Status)
   SELECT Cod,Subunitate, Gestiune, Locatie, Clasa, NRAuto,Marca,Model,DataSosire,Status
   FROM TMP_RACDetaliereInfoG ORDER BY COD asc';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rac_masinilibere_processlist</obj_name>
  <obj_hashval>5dfcf094d07f8a94d27efad13b6fc1e2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rac_masinilibere_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar;
  sSelect varchar;
  gDataS  varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true);
  gDataF  varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true);
BEGIN
  --Florin 10.07.2023 - fixat 58825
  --Florin 07.07.2023 - fixat 58814
  --Florin 15.02.2023 - fixat 57202
  --Florin 10.02.2023 - fixat 57081
  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(
            GESTCURENTA ,
            GESTINITIALA,
            NRMASINA    ,
            MARCA       ,
            MODEL       ,
            GRECHIV     , judet
  )';
  sSelect := '  Select
          VA.DEN_GEST,
          VP.DEN_GEST,
          VP.NRINREG,
          VP.MARCAAUTO,
          VP.MODELAUTO,
          GE.Denumire,
          coalesce(J.SIMBAUTO,''?'') Judet
      from v_nparcaut VP
      inner join GrEchiv GE  on GE.CODGRECHIV = VP.CodGrupa
      inner join (Select NG.DEN_GEST, X.CODGEST, X.CodAuto, X.Q
                  from (Select CodAuto, CodGest, Sum(Q) Q from V_AUTO group by CodAuto, CodGest) X
                       INNER JOIN NGest NG on NG.CODGEST = coalesce(X.CODGEST,0)
                  where Q &gt; 0
                 ) VA on VP.codnparcaut = VA.CodAuto
      left join NAGENDA  Ax on coalesce(Ax.CodGest,0) = VA.CODGEST
      left join NLocalit Lx on Lx.CodLocalit          = Ax.Codlocalit
      left join NJudet   J  on J.CodJudet             = Lx.CodJudet
    where coalesce(VP.Generic, 0) = 0 and VP.Inactiv=0
      and VA.codAuto &gt; 0
      and not VA.codAuto in
            ( select Cod from
              ( select coalesce(C.MijlTransp, 0) Cod, R.DataStart::date DataStart,
                       (Case when coalesce(R.Predat,0) = 0 then R.DataStop else Least(R.DataPred, R.DataStop) end)::date  DataStop
                from Comanda c
                  inner join RAC_REZ R on R.codcomanda = c.codcomanda
                  where c.tipdoc = 94
                    and coalesce(C.MijlTransp, 0) &gt; 0
                    and coalesce(C.Operat, 0) = 1
                    and coalesce(C.Inchisa, 0) = 0
              ) a_pg where ((to_date(''' || gDataS || ''', ''dd.mm.yyyy'') between DataStart and DataStop)
                  or to_date(''' || gDataF || ''', ''dd.mm.yyyy'') between DataStart and DataStop)
                  or DataStart between to_date(''' || gDataS || ''', ''dd.mm.yyyy'') and to_date(''' || gDataS || ''', ''dd.mm.yyyy'')
                  or DataStop  between to_date(''' || gDataS || ''', ''dd.mm.yyyy'') and to_date(''' || gDataS || ''', ''dd.mm.yyyy''))';
  PERFORM PKG_RAC_REZ_SET_RAC_DATASTART(gDataS);
  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_rac_masinilibere_setparams</obj_name>
  <obj_hashval>390a729dc8b75519b9beb64c94c7fc14</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rac_masinilibere_setparams(zi1 date, zi2 date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gDataS  varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true);
  gDataF  varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true);
BEGIN
  --Adina 15.10.2020
  perform set_config('PKG_LIST_BASE_RAC_MASINILIBERE.sZi1',gDataS,false);
  perform set_config('PKG_LIST_BASE_RAC_MASINILIBERE.sZi2',gDataF,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rac_masinioc_ce_setparams</obj_name>
  <obj_hashval>71bfd2e506d90736b45658b0072b64e9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rac_masinioc_ce_setparams(zi1 date, zi2 date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gDataS  varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true);
  gDataF  varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true);
BEGIN
  --Adina 15.10.2020
  perform set_config('PKG_LIST_BASE_RAC_MASINIOC_CE.sZi1',gDataS,false);
  perform set_config('PKG_LIST_BASE_RAC_MASINIOC_CE.sZi2',gDataF,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rac_masinioc_setparams</obj_name>
  <obj_hashval>5c33650153181825b0f8d1454ba19647</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rac_masinioc_setparams(zi1 date, zi2 date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gDataS  varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true);
  gDataF  varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true);
BEGIN
  --Adina 15.10.2020
  perform set_config('PKG_LIST_BASE_RAC_MASINIOC.sZi1',gDataS,false);
  perform set_config('PKG_LIST_BASE_RAC_MASINIOC.sZi2',gDataF,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rapconsprod_bagamatretsemi</obj_name>
  <obj_hashval>ed4000030ef910facec86c8aa033428e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rapconsprod_bagamatretsemi(aprodus numeric, acodsemif numeric, acant numeric, aidx character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  N     RECORD;
BEGIN
  --Adina 15 septembrie 2020
  FOR v_rec IN (SELECT   pmat.codobiect MATERIAL, pmat.cant / pc.cant * aCant CANTRET, pmat.cant / pc.cant * aCant * pmat.pret VALRET,
                        pmat.tip, coalesce(aIDX,'') || '.' || coalesce(LPAD((pmat.IndexLocal)::varchar, 2, '0'),'') S_IDX
                FROM   prodcomp pc
                      INNER JOIN prodmat pmat ON  pmat.codprodcomp = pc.codprodcomp
                WHERE pc.codobiect = aCodSemif and  pc.implicit = 1
               )
  LOOP
    IF  v_rec.tip &lt; 3 THEN
      PERFORM BagaMatRetSemi(aprodus, v_rec.material, v_rec.cantret, v_rec.S_idx);
    ELSE
      FOR N IN (SELECT V_REC.MATERIAL MATERIAL, V_REC.CANTRET CANTRET, V_REC.VALRET VALRET, aIDX S_IDX)
      LOOP
        UPDATE  MANEVRA_CONSUM C
           SET CANTRET = COALESCE(C.CANTRET, 0) + N.CANTRET,
               VALRET  = COALESCE(C.VALRET , 0) + N.VALRET,
               S_IDX   = N.S_IDX
        WHERE C.CODOBIECT = N.MATERIAL and  C.NODPARINTE = aCodSemif and  C.PRODUS = aPRODUS;

        IF NOT FOUND THEN
          INSERT INTO MANEVRA_CONSUM AS C (CODOBIECT, VALRET, CANTRET, NODPARINTE, PRODUS, S_IDX) VALUES (N.MATERIAL, N.VALRET, N.CANTRET, aCodSemif, aPRODUS, N.S_IDX) ;
        END IF;
      END LOOP;
    END IF;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rapconsprod_creazastructteoretica</obj_name>
  <obj_hashval>5e2d830804066e75e7b9c5195f236305</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rapconsprod_creazastructteoretica()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  N RECORD;
BEGIN
  --Adina 06.01.2021 tichet 41966
  --Adina 15 septembrie 2020
  FOR v_rec IN (SELECT   pc.codobiect PRODUS, pmat.codobiect MATERIAL, pmat.cant / pc.cant CANTRET, pmat.cant / pc.cant * pmat.pret VALRET,
                        pmat.tip, coalesce('00' || '.','') || coalesce(LPAD((pmat.IndexLocal)::varchar, 2, '0'),'') S_IDX
                FROM   prodcomp pc
                      INNER JOIN prodmat                                       pmat ON  pmat.codprodcomp = pc.codprodcomp
                      INNER JOIN (SELECT  DISTINCT produs FROM manevra_consum) sel  ON  sel.produs       = pc.codobiect
                WHERE pc.implicit = 1
                ORDER BY pc.codobiect , pmat.indexlocal
               )
  LOOP
    IF  v_rec.tip &lt; 3 THEN
      PERFORM pkg_list_base_rapconsprod_BagaMatRetSemi(v_rec.produs, v_rec.material, v_rec.cantret, v_rec.S_IDX);
    ELSE
      FOR N IN (SELECT V_REC.PRODUS PRODUS, V_REC.MATERIAL MATERIAL, V_REC.CANTRET CANTRET, V_REC.VALRET VALRET, '00' S_IDX)
      LOOP
        UPDATE  MANEVRA_CONSUM C
           SET CANTRET = COALESCE(C.CANTRET, 0) + N.CANTRET, VALRET = COALESCE(C.VALRET, 0) + N.VALRET, S_IDX = N.S_IDX
        WHERE C.CODOBIECT = N.MATERIAL and  C.NODPARINTE = N.PRODUS and  C.PRODUS = N.PRODUS;

        IF NOT FOUND THEN
          INSERT INTO MANEVRA_CONSUM AS C (CODOBIECT, VALRET, CANTRET, NODPARINTE, PRODUS, S_IDX) VALUES (N.MATERIAL, N.VALRET, N.CANTRET, N.PRODUS, N.PRODUS, N.S_IDX) ;
        END IF;
      END LOOP;
    END IF;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rapconsprod_processlist</obj_name>
  <obj_hashval>c4e94752cac7323e7ecb32b1b91190ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rapconsprod_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  N               RECORD;
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'NARTOBJ PROD, NART APROD, NUM UM, NARTOBJ SEMIF, NARTOBJ MAT, NART AMAT, NUM UMM';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodComanda      NUMERIC := current_setting('PKG_LIST_BASE_RAPCONSPROD.vCodComanda', true)::numeric;
  vAllArt          NUMERIC := current_setting('PKG_LIST_BASE_RAPCONSPROD.vAllArt', true)::numeric;
  vAnLuna          NUMERIC := current_setting('PKG_LIST_BASE_RAPCONSPROD.vAnLuna', true)::numeric;
BEGIN
  --Adina 15 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_RAPCONSPROD.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  DELETE FROM MANEVRA_CONSUM;
  PERFORM PKG_LIST_BASE_RAPCONSPROD_UmplePredariSiConsumuri();
  PERFORM PKG_LIST_BASE_RAPCONSPROD_CreazaStructTeoretica();

  IF  vCodComanda &gt; 0 THEN
    FOR N IN (SELECT i1.codobiect PRODUS, sum(i1.cant) CANT_PROD
              FROM   nartobj prod
                    INNER JOIN intrari1 i1 ON  i1.codobiect = prod.codobiect
                    INNER JOIN intrari  i  ON  i1.codintr   = i.codintr
              WHERE i1.codcmdint1 IN (SELECT codcomanda1 FROM comanda1 WHERE codcomanda = vCodComanda)
              GROUP BY i1.codobiect
             )
    LOOP
      UPDATE  MANEVRA_CONSUM C
         SET CANT_PROD = COALESCE(C.CANT_PROD, 0) + N.CANT_PROD
      WHERE C.PRODUS = N.PRODUS;
    END LOOP;
  ELSE
    FOR N IN (SELECT i1.codobiect PRODUS, sum(i1.cant) CANT_PROD
              FROM   nartobj prod
                    INNER JOIN intrari1 i1 ON  i1.codobiect = prod.codobiect
                    INNER JOIN intrari  i  ON  i1.codintr   = i.codintr
              WHERE ( EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE valoare = prod.codobiect::varchar and  filtru = 'CODOBIECT')
                      OR (vAllArt = 1 and  prod.produspropriu = 2)
                    )  and  i.tipdoc = 7 and  COALESCE(i.anulat, 0) = 0 and  i.operat = 1 and  i.an * 12 + i.luna = vAnLuna
              GROUP BY i1.codobiect
             )
    LOOP
      UPDATE  MANEVRA_CONSUM C
         SET CANT_PROD = COALESCE(C.CANT_PROD, 0) + N.CANT_PROD
      WHERE C.PRODUS = N.PRODUS;
    END LOOP;
  END IF;

  DELETE FROM manevra_consum WHERE COALESCE(cant_prod, 0) = 0;

  sInsert :=
    'INSERT INTO ' || tmpName || '
     (
      PRODUS,
      P_CODEXTERN,
      UM_AMB,
      COEF_UM_AMB,
      SEMIF,
      S_CODEXTERN,
      MATERIAL,
      M_CODEXTERN,
      UM_MAT,
      CANT_MAT,
      PRET_MAT,
      VAL_MAT,
      CANT_PROD,
      CONSUM_MAT,
      MEDIE_MAT,
      PRET_REAL_MAT,
      VAL_REAL_MAT,
      S_IDX ' || gUserFields || ')
      select
        PROD.DENUMIRE,
        PROD.CODEXTERN,
        UM.DEN_UM UM_AMB,
        UM.COEF COEF_UM_AMB,
        SEMIF.DENUMIRE SEMIF,
        SEMIF.CODEXTERN S_CODEXTERN,
        MAT.DENUMIRE MATERIAL,
        MAT.CODEXTERN M_CODEXTERN,
        UMM.DEN_UM UM_MAT,
        MC.CANTRET CANT_MAT,
        MC.VALRET / MC.CANTRET PRET_MAT,
        MC.VALRET VAL_MAT,
        MC.CANT_PROD,
        MC.CANT CONSUM_MAT,
        MC.CANT / MC.CANT_PROD MEDIE_MAT,
        CASE WHEN MC.CANT = 0 THEN 0 ELSE MC.VALOARE / MC.CANT END PRET_REAL_MAT,
        MC.VALOARE VAL_REAL_MAT,
        MC.S_IDX ' || gUserAlias || '
      FROM MANEVRA_CONSUM MC
           INNER JOIN NARTOBJ PROD  ON MC.PRODUS        = PROD.CODOBIECT
           INNER JOIN NART    APROD ON APROD.CODARTICOL = PROD.CODARTICOL
           INNER JOIN NUM     UM    ON UM.CODUM         = APROD.UM
           INNER JOIN NARTOBJ SEMIF ON MC.NODPARINTE    = SEMIF.CODOBIECT
           INNER JOIN NARTOBJ MAT   ON MAT.CODOBIECT    = MC.CODOBIECT
           INNER JOIN NART    AMAT  ON MAT.CODARTICOL   = AMAT.CODARTICOL
           INNER JOIN NUM     UMM   ON UMM.CODUM        = AMAT.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_rapconsumprod_processlist</obj_name>
  <obj_hashval>4690ac1733f281d7bad94e66d15d06cb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rapconsumprod_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, nart a, COMANDA1 C1';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 15.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_RAPCONSUMPROD.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || tmpName || ' (
       DENUMIRE,
       CODEXTERN,
       UMSEC,
       TOTAL,
       PROGRAMAT,
       CANTUNITAR,
       REALIZAT,
       CONSUMAT,
       UMSpec,
       D1,
       D2,
       D3,
       RAPORTAT,
       RAPORTATUM1,
       Pret,
       STOC';

  IF  NOT current_setting('PKG_LIST_BASE_RAPCONSUMPROD.vTouch', true)::boolean THEN
    sInsert := coalesce(sInsert,'') || ',
       STOCT ';
  END IF;

  sInsert := sInsert || gUserFields || ' )
    SELECT
       TMP.DENUMIRE,
       TMP.CODEXTERN,
       TMP.DEN_UM1,
       TMP.TOTAL,
       TMP.PROGRAMAT,
       TMP.UNITAR,
       TMP.REALIZAT,
       TMP.CONSUMAT,
       NUM1.DEN_UM1,
       TMP.D1,
       TMP.D2,
       TMP.D3,
       TMP.RAPORTAT,
       TMP.RAPORTATUM1,
       TMP.Pret,
       TMP.STOC';

  IF  NOT current_setting('PKG_LIST_BASE_RAPCONSUMPROD.vTouch', true)::boolean THEN
    sInsert := sInsert || ',
       TMP.STOCT ';
  END IF;

  sInsert := sInsert || gUserAlias || '
    FROM   TMP_RAPORTARE_CONSUM TMP
          inner join NARTOBJ OBJ ON TMP.codobiect   = OBJ.codObiect
          INNER JOIN NART A      ON OBJ.codarticol  = A.codarticol
          INNER JOIN COMANDA1 C1 ON TMP.CODCOMANDA1 = C1.CODCOMANDA1
          LEFT  join num1        on num1.codum1     = TMP.um1 ' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  PERFORM PKG_LIST_BASE_RAPCONSUMPROD_PROCESSPARAMS();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rapcreditcli_setjoinuri</obj_name>
  <obj_hashval>3b6854509298927ba8dee3241f2b9069</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rapcreditcli_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  PERFORM PKG_LIST_STRUCT_SetTableSpec (current_setting ('PKG_LIST_BASE_RAPCREDITCLI.gSuplCols', true));
  PERFORM PKG_LIST_STRUCT_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rapgesttvaval_jointmp</obj_name>
  <obj_hashval>500c319f22eb18bd08c0fb875a25fca4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rapgesttvaval_jointmp(vcamp character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Stef  20.11.2020
  IF (SELECT PKG_LIST_SELECTGEST2_ToateGest.WME_RESULT FROM PKG_LIST_SELECTGEST2_ToateGest(NULL,NULL))
  THEN
    RETURN '';
  ELSE
    RETURN '
        INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = ' || coalesce(vcamp,'') ||'::varchar ' || ' AND TMP.FILTRU = ''CODGEST''';
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rapgesttvaval_setjoinuri</obj_name>
  <obj_hashval>88e8d28dddb4ff6b9cc111ac5391b5e9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rapgesttvaval_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Adina iulie 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_rapincplatiart_processlist</obj_name>
  <obj_hashval>486b35cc0755240a03e6b0215c8a8ccf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rapincplatiart_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sSelect1    varchar;
  sSelect2    varchar;
  sTipJoin    varchar := 'INNER';
  sAnS        numeric := EXTRACT(YEAR  FROM to_date(current_setting('pkg_list_alegperioada.gDataS', TRUE), 'dd.mm.yyyy'))::NUMERIC;
  sLunaS      numeric := EXTRACT(MONTH FROM to_date(current_setting('pkg_list_alegperioada.gDataS', TRUE), 'dd.mm.yyyy'))::NUMERIC;
  sDataS      varchar := current_setting('pkg_list_alegperioada.gDataS', TRUE);
  sDataF      varchar := current_setting('pkg_list_alegperioada.gDataF', TRUE);
  AnLunaLucru numeric;
  AnLunaIni   numeric;
  sCurs       varchar := ', 1, 1, 1, 1';
  aBancaV     NUMERIC;
  aMonedaV    numeric;
  gSuplCols   varchar := 'nartobj o, npers ag_doc, npers ag_sting, npart npart, nclasep clsp, nagenda ag, nlocalit loc, njudet jud, nmonede mon, nmonede monprest, pretm pm, nsubunit SubSting, nsubunit SubStins, ' || 'npart prod, nart a, nclasea ca, nartcli ac, ncont c, nbankcont bc, nbank b, ngest g1 ';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 17.06.2022 - sinc. Oracle
  --Florin 11.05.2022 - sinc. Oracle
  --Adina 27.04.2021 - prc_al_check
  --Adina 06.04.2021 - alstart,alstop
  --Adina 19.02.2021 - GETCURSREFERINTA cast to_char la date
  --Adina 18.12.2020 pus fnc_GET_CONT_CONTABIL_OBLIG
  --Adina 15.12.2020 tichet 41618
  --Florin 31.08.2020
  --Florin 19.11.2020 - sters PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG cu 3 parametri
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'  , 'PD'  , 'PD.CODPART     = NPART.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_RAPINCPLATIART.gSuplCols', gSuplCols, FALSE);

  CALL PRC_AL_CHECK('nartobj1',0);
  CALL PRC_AL_CHECK('nbankcont1',0);
  CALL PRC_AL_CHECK('iobank1',0);
  CALL PRC_AL_CHECK('ioart1',0);

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

  aBancaV := fnc_getvalconstantalucru('BancaCursPUV')::NUMERIC;
  aMonedaV := (SELECT pkg_list_base_utils_GET_Cod_MonedaFactInValuta.WME_RESULT FROM pkg_list_base_utils_GET_Cod_MonedaFactInValuta(NULL, getanlucru(), getlunalucru()))::NUMERIC;

  IF COALESCE(aMonedaV, 0) &lt;&gt; 0 AND COALESCE(aBancaV, 0) &lt;&gt; 0 THEN
    sCurs := ',
        (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.wme_result FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, ' || coalesce(aMonedaV,0) || ',' || coalesce(aBancaV,0) || ', to_char(un.dstinsdata, ''dd.mm.yyyy''))),
        (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.wme_result FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, ' || coalesce(aMonedaV,0) || ',' || coalesce(aBancaV,0) || ', to_char(un.dstingdata, ''dd.mm.yyyy'')))';
  ELSE
    sCurs := ',1, 1';
  END IF;

  IF COALESCE(aBancaV, 0) &lt;&gt; 0 THEN
    sCurs := coalesce(sCurs,'') || ',
        (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.wme_result FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, N1.CODMONEDA,' || coalesce(aBancaV,0) || ', to_char(un.dstinsdata, ''dd.mm.yyyy''))),
        (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.wme_result FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, N1.CODMONEDA,' || coalesce(aBancaV,0) || ', to_char(un.dstingdata, ''dd.mm.yyyy'')))';
  ELSE
    sCurs := coalesce(sCurs,'') || ',1, 1';
  END IF;

  IF current_setting('pkg_list_alegperioada.gOpt1', TRUE)::BOOLEAN THEN
    sTipJoin := 'LEFT';
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(
        NAV_CodDoc, NAV_CodDoc1, NAV_TipDoc, TipStingere,
        DSTINSPR, DSTINSNR, DSTINSDATA, TOTAL_LIN, TOTAL_LINFTVA, REST_LIN, REST_LINFTVA, VAL_STINGATOR, VAL_STINGFTVA,
        DSTINGPR, DSTINGNR, DSTINGDATA, PARTENER, LOCATIE,
        SOLD_LIN, SOLD_LINF, SOLD_DOC, SOLD_DOCF,
        DATADECONT, DATAPLATA, ORDINE, ORDDOC, TERMEN, MONEDA, SUBUNIT, SUBUNIT_ST,
        SCADENTA, DIFZILE, DEPZILE, DEPZILEDEC, DEPZILEPLATA, CONT, CONTART, CONTCB, ARTICOL, CODEXTERN, CODINTERN, PRODUCATOR, CLASAARTICOL,
        DSTINSCURS, DSTINSAN, DSTINSLUNA, DSTINGCURS, DSTINGAN, DSTINGLUNA, GESTDEN, GESTSIMB,
        NRCONT,
        DSTINSCURS_REF, DSTINGCURS_REF, DSTINSCURS_PREST, DSTINGCURS_PREST' || gUserFields || ')';
  sSelect1 := '
      WITH crs_sold as
      (
        SELECT
          ol.codobligpif codobligpif,
          (ol.rest - (
                      SELECT COALESCE(sum(s.valoare), 0)
                      FROM stingere s
                           INNER JOIN obligpif os ON os.codobligpif = s.codstingatorpif
                           INNER JOIN general  gs ON gs.codgeneral  = os.codgeneral
                           LEFT  JOIN trezor1  t1 on gs.coddoc = t1.codtrezor1 AND gs.tipdoc &lt;&gt; 28 AND t1.luna = ' || coalesce(sLunaS,0) || ' AND t1.an = ' || coalesce(sAnS,0) || ' AND t1.datadoc &lt; TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'')
                           LEFT  JOIN compens  c  ON gs.coddoc = c.codcompens  AND gs.tipdoc = 28  AND c.luna  = ' || coalesce(sLunaS,0) || ' AND c.an  = ' || coalesce(sAnS,0) || ' AND c.datadoc  &lt; TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'')
                      WHERE s.codstinspif = ol.codobligpif
                            AND COALESCE(t1.codtrezor,c.codcompens) IS NOT NULL
                     )
          ) * (Case When g.semnificatie=310 then -1 else 1 end) rest
        FROM obligpifluna ol
             INNER JOIN obligpif op on ol.codobligpif = op.codobligpif
             INNER JOIN general  g  on op.codgeneral  = g.codgeneral
        WHERE (g.tipdoc BETWEEN 1 AND 7 OR g.tipdoc = 35)
              AND ol.luna + ol.an*12 = ' || coalesce((sAnS * 12 + sLunaS - 1)::varchar,'') || '
      ),
      stinsi as
      (
        SELECT
          i1.codintr1 coddoc1, i1.indexlocal, i.codintr coddoc, i.tipdoc, i1.codobiect, o.codgeneral, i.prefixdoc, i.nrdoc, i.datadoc, i.subunitatea, (Case  When g.curs=NULL then 1 When g.curs=0 then 1 else g.curs end) curs, COALESCE(g.moneda,0) moneda, o.codobligpif,
          CASE
            WHEN o.valoare = 0 THEN 0
            WHEN (i1.pu * i1.cant+(Case When i.tipdoc=3 then 0 else i1.tva end)) * COALESCE(i1.coefdiscmaj, 1) * (Case When i1.pu=i1.pretorig then 1 When i1.pu=0 then 0 else i1.pretorig/i1.pu end) = 0 THEN 0
            WHEN Sum((i1.pu * i1.cant+(Case When i.tipdoc=3 then 0 else i1.tva end)) * COALESCE(i1.coefdiscmaj, 1) * (Case When i1.pu=i1.pretorig then 1 When i1.pu=0 then 0 else i1.pretorig/i1.pu end)) over (PARTITION BY g.codgeneral, COALESCE(i1.codcentru,0)) = 0 THEN 0
            ELSE o.valoare*((i1.pu * i1.cant+(Case When i.tipdoc=3 then 0 else i1.tva end)) * COALESCE(i1.coefdiscmaj, 1) * (Case  When i1.pu=i1.pretorig then 1 When i1.pu=0 then 0 else i1.pretorig/i1.pu end))/ Sum((i1.pu * i1.cant+(Case When i.tipdoc=3 then 0 else i1.tva end)) * COALESCE(i1.coefdiscmaj, 1) * (Case  When i1.pu=i1.pretorig then 1 When i1.pu=0 then 0 else i1.pretorig/i1.pu end)) over (PARTITION BY g.codgeneral, COALESCE(i1.codcentru,0))
          END valoarelinie,
          CASE
            WHEN i.tipdoc = 3 and I1.PU * I1.CANT &lt;&gt; 0 THEN (I1.PU * I1.CANT-I1.TVA)/(I1.PU * I1.CANT)
            WHEN i.tipdoc &lt;&gt; 3 AND I1.PU * I1.CANT+I1.TVA &lt;&gt; 0 THEN (I1.PU * I1.CANT)/(I1.PU * I1.CANT+I1.TVA)
            ELSE 1
          END COEFTVA,
          o.valoare, o.codpart, i.codlocatie, o.termen, 0 agent, i.an, i.luna, PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont,o.codpart,i.an*12+i.luna,o.semnificatie) codcont, 0 codbanca,
          i1.contserv,
          NULL::NUMERIC contbanca
        FROM intrari i
             INNER JOIN intrari1 i1  ON i.codintr    = i1.codintr
             INNER JOIN nartobj  obj ON i1.codobiect = obj.codobiect
             INNER JOIN general  g   ON g.coddoc     = i.codintr    and g.tipdoc = i.tipdoc and g.semnificatie &lt;&gt; 600
             INNER JOIN obligpif o   ON g.codgeneral = o.codgeneral AND COALESCE(o.codcentru,0) = COALESCE(i1.codcentru,0)
        WHERE COALESCE(i.anulat, 0) = 0 and COALESCE(i.initializari, 0) = 0 AND COALESCE(i1.codobiect,0) &lt;&gt; 0 AND i.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
        UNION ALL
        SELECT
          0 coddoc1, 0 indexlocal, i.codintr coddoc, i.tipdoc, -1 codobiect, o.codgeneral, ''sold initial '' prefixdoc, i.nrdoc, i.datadoc, i.subunitatea, (Case When g.curs=NULL then 1 When g.curs=0 then 1 else g.curs end) curs, COALESCE(g.moneda,0) moneda, o.codobligpif,
          o.valoare valoarelinie,
          1 COEFTVA,
          o.valoare, o.codpart, i.codlocatie, o.termen, 0 agent, i.an, i.luna, PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont,o.codpart,' || coalesce(AnLunaIni,0) || ',o.semnificatie) codcont, 0 codbanca,
          NULL contserv,
          NULL::NUMERIC contbanca
        FROM intrari i
             INNER JOIN general  g ON g.coddoc     = i.codintr and g.tipdoc = i.tipdoc and g.semnificatie &lt;&gt; 600 and g.semnificatie &lt;&gt; 140
             INNER JOIN obligpif o ON g.codgeneral = o.codgeneral
        WHERE COALESCE(i.anulat, 0) = 0 and COALESCE(i.initializari, 0) = 1 AND i.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
        UNION ALL
        SELECT
          t1.CodTrezor1 CodDoc1, t1.indexlocal, t.CodTrezor CodDoc, t.TipDoc, (Case  When g.tipdoc=33 then -3 else -2 end) codobiect, o.codgeneral, t1.doc prefixdoc, t1.nrdoc, t1.datadoc, t.subunitatea, (Case When g.curs=NULL then 1 When g.curs=0 then 1 else g.curs end) curs, COALESCE(g.moneda,0) moneda, o.codobligpif,
          -o.valoare valoarelinie,
          CASE WHEN COALESCE(o.valoare,0) = 0 THEN 1 ELSE (o.valoare-COALESCE(g.tva,0))/o.valoare END COEFTVA,
          -o.valoare, o.codpart, t1.codlocatie, o.termen, t1.agent, t.An, t.Luna, PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont,o.codpart,t1.an*12+t1.luna,o.semnificatie) codcont, t.codbanca,
          CASE WHEN g.semnificatie = 900 THEN o.icont ELSE (fnc_GET_CONT_CONTABIL_OBLIG(o.semnificatie, o.icont, PKG_NOMPART_GET_PART_COD_CARACT_LUNA(t1.codpart,t.an,t.luna))) END contserv,
          CASE WHEN g.tipdoc = 33 THEN (fnc_GET_CONT_CONTABIL_OBLIG(1100, t.icontpers, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(t.codbanca, t.an,t.luna))) END contbanca
        FROM trezor1 t1
             INNER JOIN general  g ON g.coddoc     = t1.codtrezor1 AND g.semnificatie IN (310, 900)
             INNER JOIN obligpif o ON g.codgeneral = o.codgeneral
             INNER JOIN trezor   t ON t1.codtrezor = t.codtrezor
        WHERE COALESCE(t1.anulat, 0) = 0 AND t1.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('t',NULL,NULL,NULL),'') || '
      ),
      stingatori as
      (
        SELECT
          o.CodObligPIF, o.Codgeneral, t.codtrezor CodDoc, t1.codtrezor1 CodDoc1, g.TipDoc, t1.doc PrefixDoc, t1.nrdoc, t1.datadoc, t1.DATADECONT, COALESCE(t1x.datadoc, t1.datadecont, t1.datadoc) DATAPLATA,
          t1.agent, t.Subunitatea, s.codstinspif, s.valoare s_valoare, s.valoare-COALESCE(g.tva,0) s_valftva, (Case When t1.curs=NULL then 1 When t1.curs=0 then 1 else t1.curs end) curs, COALESCE(t.monedapers, bc.codmoneda, 0) moneda, t.an, t.luna, t.codbanca,
          CASE WHEN g.tipdoc = 33 THEN (fnc_GET_CONT_CONTABIL_OBLIG(1100, t.icontpers, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(t.codbanca, t.an,t.luna))) END contbanca
        FROM trezor1 t1
          INNER JOIN trezor    t   ON t1.codtrezor      = t.codtrezor
          INNER JOIN general   g   ON t1.codtrezor1     = g.coddoc and g.tipdoc = t.tipdoc
          INNER JOIN obligpif  o   ON o.codgeneral      = g.codgeneral
          INNER JOIN stingere  s   ON s.codstingatorpif = o.codobligpif
          LEFT  JOIN nbankcont bc  ON bc.codbankcont    = t.codbanca
          LEFT  JOIN general   gc  ON gc.coddoc         = g.coddoc AND gc.semnificatie = 600 AND gc.semnificatie &lt;&gt; g.semnificatie
          LEFT  JOIN obligpif  oc  ON oc.codgeneral     = gc.codgeneral
          LEFT  JOIN stingere  sx  ON sx.codstinspif    = COALESCE(oc.codobligpif, o.codobligpif)
          LEFT  JOIN obligpif  ox  ON ox.codobligpif    = sx.codstingatorpif
          LEFT  JOIN general   gx  ON gx.codgeneral     = ox.codgeneral
          LEFT  JOIN trezor1   t1x ON t1x.codtrezor1    = gx.coddoc
        WHERE T1.DATADOC BETWEEN TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
          AND ((G.TipDoc IN (29, 30, 31, 33) AND t1.TipTranz = 0) OR (t1.TipTranz = 0 AND t1.ObiectTranz = 1)) AND g.semnificatie &lt;&gt; 800' || coalesce(CASE
   WHEN NOT current_setting('pkg_list_alegperioada.gOpt3', TRUE)::BOOLEAN THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL)
   ELSE NULL
   END ,'') || '
        UNION ALL
        SELECT
          o.CodObligPIF, o.Codgeneral, c.codcompens CodDoc, NULL CodDoc1, g.TipDoc, ''PV'', c.nrdoc, c.datadoc, null DATADECONT, c.datadoc DATAPLATA,
          0 Agent, c.Subunitatea, s.codstinspif, s.valoare s_valoare, s.valoare-COALESCE(g.tva,0) s_valftva, (Case When g.curs=NULL then 1 When g.curs=0 then 1 else g.curs end) curs, COALESCE(g.moneda,0) moneda, c.an, c.luna, 0 codbanca,
          NULL contbanca
        FROM compens c
          INNER JOIN general  g ON g.coddoc          = c.codcompens
          INNER JOIN obligpif o ON o.codgeneral      = g.codgeneral
          INNER JOIN stingere s ON s.codstingatorpif = o.codobligpif
        WHERE C.DATADOC BETWEEN TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
          AND G.TipDoc = 28 ' || coalesce(CASE
   WHEN NOT current_setting('pkg_list_alegperioada.gOpt3', TRUE)::BOOLEAN THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL)
   ELSE NULL
   END ,'') || '
      ),
      UN AS
      (
        SELECT
          stingatori.coddoc NAV_CodDoc, stingatori.coddoc1 NAV_CodDoc1, stingatori.tipdoc NAV_TipDoc, x.prefixdoc DSTINSPR, x.nrdoc DSTINSNR, x.datadoc DSTINSDATA, x.valoarelinie TOTAL_LIN,
          sign(x.valoare)*COALESCE(stingatori.s_valoare,0)*x.valoarelinie/(Case When COALESCE(x.valoare, 0)= 0 then  1 else x.valoare end) VAL_STINGATOR,
          sign(x.valoare)*COALESCE(stingatori.s_valftva,0)*x.valoarelinie/(Case When COALESCE(x.valoare, 0)= 0 then  1 else x.valoare end) VAL_STINGFTVA,
          x.rest_lin - COALESCE(SUM(sign(x.valoare)*COALESCE(stingatori.s_valoare,0)*x.valoarelinie/(Case When COALESCE(x.valoare, 0)= 0 then  1 else x.valoare end)) OVER (PARTITION BY x.coddoc1, x.codobligpif),0) REST,
          x.coeftva,
          x.rest_lin - COALESCE(SUM(sign(x.valoare)*COALESCE(stingatori.s_valoare,0)*x.valoarelinie/(Case When COALESCE(x.valoare, 0)= 0 then  1 else x.valoare end)) OVER (PARTITION BY x.coddoc1, x.codobligpif ORDER BY stingatori.codgeneral ROWS BETWEEN unbounded preceding AND CURRENT ROW),0) SOLD_LIN,
          x.rest_doc - COALESCE(SUM(sign(x.valoare)*COALESCE(stingatori.s_valoare,0)*x.valoarelinie/(Case When COALESCE(x.valoare, 0)= 0 then  1 else x.valoare end)) OVER (PARTITION BY x.codobligpif ORDER BY x.indexlocal, stingatori.codgeneral ROWS BETWEEN unbounded preceding AND CURRENT ROW),0) SOLD_DOC,
          ROW_NUMBER() OVER (PARTITION BY x.codobligpif, x.coddoc1 ORDER BY stingatori.codgeneral) ORDINE, COUNT(1) OVER (PARTITION BY x.codobligpif, x.coddoc1) ORDINEMAX,
          ROW_NUMBER() OVER (PARTITION BY x.codobligpif ORDER BY x.indexlocal, stingatori.codgeneral) ORDDOC, COUNT(1) OVER (PARTITION BY x.codobligpif) ORDDOCMAX,
          stingatori.prefixdoc DSTINGPR, stingatori.nrdoc DSTINGNR, stingatori.datadoc DSTINGDATA, stingatori.DATADECONT, stingatori.DATAPLATA, x.TERMEN, x.termen SCADENTA, trunc(stingatori.datadoc - x.datadoc::date) DIFZILE,
          case when trunc(stingatori.datadoc - x.termen) &gt; 0 then trunc(stingatori.datadoc - x.termen) else 0 end DEPZILE,
          case when trunc(COALESCE(stingatori.datadecont,stingatori.datadoc) - x.termen) &gt; 0 then trunc(COALESCE(stingatori.datadecont,stingatori.datadoc) - x.termen) else 0 end DEPZILEDEC,
          case when trunc(stingatori.dataplata - x.termen) &gt; 0 then trunc(stingatori.dataplata - x.termen) else 0 end DEPZILEPLATA,
          x.codpart, COALESCE(x.agent,0) agent, COALESCE(stingatori.agent,0) agent_sting, x.codcont, COALESCE(x.codlocatie,0) codlocatie,
          x.curs dstinscurs, x.moneda, x.subunitatea dstinssub, stingatori.subunitatea dstingsub,
          x.coddoc, x.coddoc1, x.tipdoc, x.codobiect, x.an dstinsan, x.luna dstinsluna, stingatori.an dstingan, stingatori.luna dstingluna, stingatori.an * 12 + stingatori.luna dstinganluna, stingatori.curs dstingcurs,
          CASE WHEN x.codobiect &lt;= -2 THEN x.codbanca ELSE stingatori.codbanca END codbanca, x.contserv, COALESCE(stingatori.contbanca,x.contbanca) contbanca
        FROM (
              SELECT
                stinsi.*,
                CASE WHEN COALESCE(crs_sold.rest, 0) = 0 THEN COALESCE(stinsi.valoarelinie,0) ELSE COALESCE(crs_sold.rest,0) END rest_lin,
                SUM(CASE WHEN COALESCE(crs_sold.rest, 0) = 0 THEN COALESCE(stinsi.valoarelinie,0) ELSE COALESCE(crs_sold.rest,0) END) OVER (PARTITION BY stinsi.codobligpif) rest_doc
              FROM stinsi LEFT JOIN crs_sold ON crs_sold.codobligpif = stinsi.codobligpif
              WHERE (COALESCE(crs_sold.rest,0) &lt;&gt; 0 OR crs_sold.rest IS NULL) AND stinsi.valoarelinie &lt;&gt; 0
             ) x ' || coalesce(sTipJoin,'') || ' JOIN stingatori ON stingatori.codstinspif = x.codobligpif
      )
      SELECT
        (Case  When ts.codsubunit IS NULL then NULL else UN.NAV_CodDoc end) NAV_CodDoc, (Case  When ts.codsubunit IS NULL then NULL else UN.NAV_CodDoc1 end) NAV_CodDoc1, (Case  When ts.codsubunit IS NULL then NULL else UN.NAV_TipDoc end) NAV_TipDoc, ''Plata'',
        UN.DSTINSPR, UN.DSTINSNR, UN.DSTINSDATA, -UN.TOTAL_LIN, -UN.TOTAL_LIN * UN.COEFTVA, -UN.REST, -UN.REST * UN.COEFTVA, -UN.VAL_STINGATOR, -UN.VAL_STINGATOR * UN.COEFTVA,
        UN.DSTINGPR, UN.DSTINGNR, UN.DSTINGDATA, NPART.DEN_PART, AG.OBS,
        -UN.SOLD_LIN, -(CASE WHEN UN.ORDINE = UN.ORDINEMAX THEN UN.SOLD_LIN END), -UN.SOLD_DOC, -(CASE WHEN UN.ORDDOC = UN.ORDDOCMAX THEN UN.SOLD_DOC END),
        UN.DATADECONT, UN.DATAPLATA, UN.ORDINE, UN.ORDDOC, UN.TERMEN, mon.den_moneda, SubStins.den_subunit, SubSting.den_subunit,
        UN.SCADENTA, UN.DIFZILE, UN.DEPZILE, UN.DEPZILEDEC, UN.DEPZILEPLATA, C.SIMBOL, COALESCE(XC.CONTART, CS.SIMBOL), CB.SIMBOL, (CASE WHEN un.codobiect = -1 THEN ''INITIALIZARE'' WHEN un.codobiect = -2 THEN ''AVANS TREZORERIE''
        WHEN un.codobiect = -3 THEN ''DECONT CASA/BANCA'' ELSE o.denumire END) ARTICOL, O.CODEXTERN, O.CODINTERN, PROD.DEN_PART, CA.SIMBOL,
        UN.DSTINSCURS, UN.DSTINSAN, UN.DSTINSLUNA, UN.DSTINGCURS, UN.DSTINGAN, UN.DSTINGLUNA, (Case When I1.TIPLINIE=''='' then G2.DEN else G1.DEN_GEST end), (Case When I1.TIPLINIE=''='' then G2.SIMB else G1.SIMBOL end),
        (Case When UN.NAV_TipDoc=33 then ''DECONT CASA/BANCA'' else BC.NRCONT end) ' || coalesce(sCurs,'') || gUserAlias || '
      FROM UN
        LEFT JOIN intrari             i        on i.codintr           = un.coddoc AND i.tipdoc = un.tipdoc
        LEFT JOIN intrari1            i1       on i1.codintr1         = un.coddoc1 AND i1.codintr = i.codintr
        LEFT JOIN nartobj             o        ON o.codobiect         = un.codobiect
        LEFT JOIN npers               ag_doc   on ag_doc.codpers       = UN.agent
        LEFT JOIN npers               ag_sting ON ag_sting.codpers     = UN.agent_sting
        LEFT JOIN npart               npart    ON npart.codpart       = un.codpart
        LEFT JOIN nclasep             clsp     on COALESCE(npart.codclasa, 0) = clsp.codclasep
        LEFT JOIN nagenda             ag       ON UN.codlocatie       = ag.codagenda
        LEFT JOIN nlocalit            loc      on ag.codlocalit       = loc.codlocalit
        LEFT JOIN njudet              jud      on loc.codjudet         = jud.codjudet
        LEFT JOIN nmonede             mon      ON mon.codmoneda       = COALESCE(UN.moneda,0)
        LEFT JOIN pretm               pm       on pm.codobiect         = o.CodObiect and pm.implicit = 1 and pm.subunitatea = ' || getsubunitate() || '
        LEFT JOIN nsubunit            SubSting ON SubSting.codsubunit = UN.dstingsub
        LEFT JOIN nsubunit            SubStins ON SubStins.codsubunit = UN.dstinssub
        LEFT JOIN tmp_subunitdedicate ts       ON ts.codsubunit       = UN.dstingsub
        LEFT JOIN npart               prod     ON prod.codpart         = o.codproducator
        LEFT JOIN nart                a        ON a.codarticol         = o.codarticol
        LEFT JOIN nclasea             ca       ON ca.codclasea         = a.clasa
        LEFT JOIN nartobj1            n1       on n1.codobiect        = o.codobiect AND ' || coalesce(AnLunaLucru,0) || ' BETWEEN n1.ALStart and n1.ALStop
        LEFT JOIN nmonede             monprest ON monprest.codmoneda   = COALESCE(n1.codmoneda,0)
        LEFT JOIN nartcli             ac       ON ac.codobiect         = un.codobiect AND ac.codpart = un.codpart
        LEFT JOIN ncont               c        ON c.codcont           = un.codcont
        LEFT JOIN ncont               cs       ON cs.codcont           = un.contserv
        LEFT JOIN nbankcont           bc       ON bc.codbankcont       = un.codbanca
        LEFT JOIN nbank               b        ON b.codbank           = bc.codbank
        LEFT JOIN NBANKCONT1          nbc1     ON nbc1.codbankcont     = un.codbanca     AND un.dstinganluna BETWEEN nbc1.ALStart and nbc1.ALStop
        LEFT JOIN IOBANK1             iob1     ON iob1.codiobank       = nbc1.codiobanca AND un.dstinganluna BETWEEN iob1.ALStart and iob1.ALStop
        LEFT JOIN ncont               cb       ON cb.codcont           = COALESCE(un.contbanca,iob1.cont)
        LEFT JOIN ngest               g1       ON g1.codgest           = i1.gestact
        LEFT JOIN (
                    SELECT ns.codintr1, n.codintr, n.tipnir, string_agg(DISTINCT ng.den_gest, '''') DEN, string_agg(DISTINCT ng.simbol, '''') SIMB
                    FROM nirstoc ns
                      INNER JOIN nir   n  ON n.codnir   = ns.codnir
                      INNER JOIN ngest ng On ng.codgest = n.gest
                    WHERE ng.codgest &lt;&gt; 0
                    GROUP BY ns.codintr1, n.codintr, n.tipnir
                  ) g2 ON g2.codintr1 = i1.codintr1 AND g2.codintr = i.codintr AND g2.tipnir = i.tipdoc
        LEFT JOIN (
                    SELECT
                           i1.codintr1,
                           string_agg(DISTINCT c.simbol, '''') contart
                    FROM intrari i
                         INNER JOIN intrari1       i1   ON i.codintr    = i1.codintr
                         LEFT  JOIN intrlink       il   ON il.codintr1  = i1.codintr1 AND il.codlinieaviz IS NOT NULL
                         LEFT  JOIN intrasteptlink ila  ON ila.codliniefactura = i1.codintr1 AND COALESCE(i.tipfactura, 0) = 9
                         LEFT  JOIN intrari1       ae1  ON ae1.codintr1 = COALESCE( ila.codintr1, il.codlinieaviz )
                         LEFT  JOIN intrari        ae   ON ae.codintr   = ae1.codintr
                         LEFT  JOIN dvi                 ON dvi.codintr  = i.codintr
                         LEFT  JOIN dvi1                ON dvi1.coddvi  = dvi.coddvi AND dvi1.codintr1 = i1.codintr1
                         LEFT  JOIN livr1          l1   ON l1.codintr1  = i1.codintr1
                         LEFT  JOIN livrval        lv   ON lv.codlivr1  = l1.codlivr1
                         LEFT  JOIN nirstoc        ns   ON ns.codobiect = i1.codobiect
                           AND ( ((l1.codlivr1 IS NOT NULL) AND (ns.codnirstoc = l1.codnirstoc)) OR
                                 ((l1.codlivr1 IS NULL) AND ((ns.codintr1 = COALESCE(ae1.codintr1,i1.codintr1)) OR (ns.coddvi1 = dvi1.coddvi1))))
                         INNER JOIN ioart1         ioa1 ON ioa1.codioart = COALESCE(lv.codioart,ns.codioart) AND (i.an*12+i.luna) BETWEEN ioa1.ALStart and ioa1.ALStop
                         INNER JOIN ncont          c    ON c.codcont     = ioa1.cont
                    WHERE COALESCE(i.anulat, 0) = 0 and COALESCE(i.initializari, 0) = 0 AND COALESCE(i1.codobiect,0) &lt;&gt; 0 AND i.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || ' AND i1.tiplinie = ''=''
                    GROUP BY i1.codintr1
                  ) xc ON xc.codintr1 = i1.codintr1' || gSuplJoins;
  sSelect2 := '
      WITH crs_sold as (
        SELECT
          ol.codobligpif codobligpif,
          (ol.rest - (
                      SELECT COALESCE(sum(s.valoare), 0)
                      FROM stingere s
                        INNER JOIN obligpif os ON os.codobligpif = s.codstingatorpif
                        INNER JOIN general  gs ON gs.codgeneral = os.codgeneral
                        LEFT  JOIN trezor1  t1 on gs.coddoc = t1.codtrezor1 AND gs.tipdoc &lt;&gt; 28 AND t1.luna = ' || coalesce(sLunaS,0) || ' AND t1.an = ' || coalesce(sAnS,0) || ' AND t1.datadoc &lt; TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'')
                        LEFT  JOIN compens  c  ON gs.coddoc = c.codcompens AND gs.tipdoc = 28 AND c.luna = ' || coalesce(sLunaS,0) || ' AND c.an = ' || coalesce(sAnS,0) || ' AND c.datadoc &lt; TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'')
                      WHERE s.codstinspif = ol.codobligpif
                        AND COALESCE(t1.codtrezor,c.codcompens) IS NOT NULL
                     )
         ) * (Case  When g.semnificatie=410 then -1 else 1 end) rest
        FROM obligpifluna ol
             INNER JOIN obligpif op on ol.codobligpif = op.codobligpif
             INNER JOIN general  g  on op.codgeneral  = g.codgeneral
        WHERE (g.tipdoc BETWEEN 19 AND 26 OR g.tipdoc = 35)
              AND ol.luna + ol.an*12 = ' || coalesce((sAnS * 12 + sLunaS - 1)::varchar,'') || '
      ),
      stinsi as (
        SELECT
          i1.codies1 coddoc1, i1.indexlocal, i.codies coddoc, i.tipdoc, o.codgeneral, i1.codobiect, i.prefixdoc, i.nrdoc, i.datadoc, i.subunitatea, (Case When g.curs=NULL then 1 When g.curs=0 then 1 else g.curs end) curs, COALESCE(g.moneda,0) moneda, o.codobligpif,
          CASE
            WHEN o.valoare = 0 THEN 0
            WHEN (i1.pu * i1.cant+(Case When i.tipdoc=21 then 0 else i1.tva end)) * COALESCE(i1.coefdiscmaj, 1) * (Case When i1.pu=i1.pretorig then 1 When i1.pu=0 then 0 else i1.pretorig/i1.pu end) = 0 THEN 0
            WHEN Sum((i1.pu * i1.cant+(Case When i.tipdoc=21 then 0 else i1.tva end)) * COALESCE(i1.coefdiscmaj, 1) * (Case When i1.pu=i1.pretorig then 1 When i1.pu=0 then 0 else i1.pretorig/i1.pu end)) over (PARTITION BY o.codobligpif, COALESCE(i1.codcentru,0)) = 0 THEN 0
            ELSE o.valoare * (i1.pu * i1.cant+(Case When i.tipdoc=21 then 0 else i1.tva end)) * COALESCE(i1.coefdiscmaj, 1) * (Case When i1.pu=i1.pretorig then 1 When i1.pu=0 then 0 else i1.pretorig/i1.pu end)/Sum((i1.pu * i1.cant+(Case  When i.tipdoc=21 then 0 else i1.tva end)) * COALESCE(i1.coefdiscmaj, 1) * (Case When i1.pu=i1.pretorig then 1 When i1.pu=0 then 0 else i1.pretorig/i1.pu end)) over (PARTITION BY o.codobligpif, COALESCE(i1.codcentru,0))
          END valoarelinie,
          CASE
            WHEN i.tipdoc = 21 and I1.PU * I1.CANT &lt;&gt; 0 THEN (I1.PU * I1.CANT-I1.TVA)/(I1.PU * I1.CANT)
            WHEN i.tipdoc &lt;&gt; 21 AND I1.PU * I1.CANT+I1.TVA &lt;&gt; 0 THEN (I1.PU * I1.CANT)/(I1.PU * I1.CANT+I1.TVA)
            ELSE 1
          END COEFTVA,
          o.valoare, o.codpart, i.codlocatie, o.termen, i.agent, PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont,o.codpart,i.an*12+i.luna,o.semnificatie) codcont, i.an, i.luna, 0 codbanca,
          i1.contserv,
          NULL contbanca
        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
             INNER JOIN obligpif o  ON g.codgeneral = o.codgeneral AND COALESCE(o.codcentru,0) = COALESCE(i1.codcentru,0)
        WHERE COALESCE(i.anulat, 0) = 0 AND COALESCE(i.initializari, 0) = 0 AND COALESCE(i1.codobiect,0) &lt;&gt; 0 AND i.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')'
        || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
        UNION ALL
        SELECT
          0 coddoc1, 0 indexlocal, i.codies coddoc, i.tipdoc, o.codgeneral, -1 codobiect, ''sold initial '' prefixdoc, i.nrdoc, i.datadoc, i.subunitatea, (Case  When g.curs=NULL then 1 When g.curs=0 then 1 else g.curs end) curs, COALESCE(g.moneda,0) moneda, o.codobligpif,
          o.valoare valoarelinie,
          1 COEFTVA,
          o.valoare, o.codpart, i.codlocatie, o.termen, i.agent, PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont,o.codpart,' || coalesce(AnLunaIni,0) || ',o.semnificatie) codcont, i.an, i.luna, 0 codbanca,
          NULL contserv,
          NULL::NUMERIC contbanca
        FROM iesiri i
             LEFT JOIN general  g ON g.coddoc     = i.codies and g.tipdoc = i.tipdoc and g.semnificatie &lt;&gt; 500 and g.semnificatie &lt;&gt; 240
             LEFT JOIN obligpif o ON g.codgeneral = o.codgeneral
        WHERE COALESCE(i.anulat, 0) = 0 and COALESCE(i.initializari, 0) = 1 AND i.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')'
        || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
        UNION ALL
        SELECT
          t1.CodTrezor1 CodDoc1, t1.indexlocal, t.CodTrezor CodDoc, t.TipDoc, o.codgeneral, (Case When g.tipdoc=33 then -3 else -2 end) codobiect, t1.doc prefixdoc, t1.nrdoc, t1.datadoc, t.subunitatea, (Case When g.curs=NULL then 1 When g.curs=0 then 1 else g.curs end) curs, COALESCE(g.moneda,0) moneda, o.codobligpif,
          -o.valoare valoarelinie,
          CASE WHEN COALESCE(o.valoare,0) = 0 THEN 1 ELSE (o.valoare-COALESCE(g.tva,0))/o.valoare END COEFTVA,
          -o.valoare, o.codpart, t1.codlocatie, o.termen, t1.agent, PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont,o.codpart,t1.an*12+t1.luna,o.semnificatie) codcont, t.An, t.Luna, t.codbanca,
          CASE WHEN g.semnificatie = 901 THEN o.icont ELSE (fnc_GET_CONT_CONTABIL_OBLIG(o.semnificatie, o.icont, PKG_NOMPART_GET_PART_COD_CARACT_LUNA(t1.codpart,t.an,t.luna))) END contserv,
          CASE WHEN g.tipdoc = 33 THEN (fnc_GET_CONT_CONTABIL_OBLIG(1100, t.icontpers, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(t.codbanca, t.an,t.luna))) END contbanca
        FROM trezor1 t1
             INNER JOIN general  g ON g.coddoc     = t1.codtrezor1 AND g.semnificatie IN (410,901)
             INNER JOIN obligpif o ON g.codgeneral = o.codgeneral
             INNER JOIN trezor   t ON t1.codtrezor = t.codtrezor
        WHERE COALESCE(t1.anulat, 0) = 0 AND t1.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')'
        || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('t',NULL,NULL,NULL),'') || '
      ),
      stingatori as (
        SELECT
          o.CodObligPIF, o.Codgeneral, t.codtrezor CodDoc, t1.codtrezor1 CodDoc1, g.TipDoc, t1.doc prefixdoc, t1.nrdoc, t1.datadoc, t1.datadecont, COALESCE(t1x.datadoc, t1.datadecont, t1.datadoc) DATAINC,
          t1.agent, t.Subunitatea, s.codstinspif, s.valoare s_valoare, s.valoare-COALESCE(g.tva,0) s_valftva, (Case When t1.curs=NULL then 1 When t1.curs=0 then 1 else t1.curs end) curs, COALESCE(t.monedapers, bc.codmoneda, 0) moneda, t.an, t.luna, t.codbanca,
          CASE WHEN g.tipdoc = 33 THEN (fnc_GET_CONT_CONTABIL_OBLIG(1100, t.icontpers, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(t.codbanca, t.an,t.luna))) END contbanca
        FROM  trezor1 t1
              INNER JOIN trezor    t   ON t1.codtrezor   = t.codtrezor
              INNER JOIN general   g   ON t1.codtrezor1  = g.coddoc and g.tipdoc = t.tipdoc
              INNER JOIN obligpif  o   ON o.codgeneral   = g.codgeneral
              INNER JOIN stingere  s   ON s.codstingatorpif = o.codobligpif
              LEFT  JOIN nbankcont bc  ON bc.codbankcont = t.codbanca
              LEFT  JOIN general   gc  ON gc.coddoc      = g.coddoc AND gc.semnificatie = 600 AND gc.semnificatie &lt;&gt; g.semnificatie
              LEFT  JOIN obligpif  oc  ON oc.codgeneral  = gc.codgeneral
              LEFT  JOIN stingere  sx  ON sx.codstinspif = COALESCE(oc.codobligpif, o.codobligpif)
              LEFT  JOIN obligpif  ox  ON ox.codobligpif = sx.codstingatorpif
              LEFT  JOIN general   gx  ON gx.codgeneral  = ox.codgeneral
              LEFT  JOIN trezor1   t1x ON t1x.codtrezor1 = gx.coddoc
        WHERE T1.DATADOC BETWEEN TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
              AND G.TipDoc IN (29, 30, 31, 33)
              AND ((t1.tiptranz = 0) OR (t1.TipTranz = 1))
              AND g.semnificatie NOT IN (410,750,801)' ||
              coalesce(CASE WHEN NOT current_setting('pkg_list_alegperioada.gOpt3', TRUE)::BOOLEAN THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL)
                            ELSE NULL
                       END ,'') || '
        UNION ALL
        SELECT
          o.CodObligPIF, o.Codgeneral, c.codcompens CodDoc, NULL CodDoc1, g.TipDoc, ''PV'' prefixdoc, c.nrdoc, c.datadoc, null DATADECONT, c.datadoc DATAINC,
          0 Agent, c.Subunitatea, s.codstinspif, s.valoare s_valoare, s.valoare-COALESCE(g.tva,0) s_valftva, (Case When g.curs=NULL then 1 When g.curs=0 then 1 else g.curs end) curs, COALESCE(g.moneda,0) moneda, c.an, c.luna, 0 codbanca,
          NULL contbanca
        FROM compens c
             INNER JOIN general  g ON g.coddoc     = c.codcompens
             INNER JOIN obligpif o ON o.codgeneral = g.codgeneral
             INNER JOIN stingere s ON s.codstingatorpif = o.codobligpif
        WHERE C.DATADOC BETWEEN TO_DATE(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
              AND G.TipDoc = 28 ' ||
              coalesce(CASE WHEN NOT current_setting('pkg_list_alegperioada.gOpt3', TRUE)::BOOLEAN THEN PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL)
                            ELSE NULL
                       END ,'') || '
      ),
      UN AS (
        SELECT
          stingatori.coddoc NAV_CodDoc, stingatori.coddoc1 NAV_CodDoc1, stingatori.tipdoc NAV_TipDoc, x.prefixdoc DSTINSPR, x.nrdoc DSTINSNR, x.datadoc DSTINSDATA, x.valoarelinie TOTAL_LIN,
          sign(x.valoare)*COALESCE(stingatori.s_valoare,0)*x.valoarelinie/(Case When COALESCE(x.valoare, 0)= 0 then  1 else x.valoare end) VAL_STINGATOR,
          sign(x.valoare)*COALESCE(stingatori.s_valftva,0)*x.valoarelinie/(Case When COALESCE(x.valoare, 0)= 0 then  1 else x.valoare end) VAL_STINGFTVA,
          x.rest_lin - COALESCE(SUM(sign(x.valoare)*COALESCE(stingatori.s_valoare,0)*x.valoarelinie/(Case When COALESCE(x.valoare, 0)= 0 then  1 else x.valoare end)) OVER (PARTITION BY x.coddoc1, x.codobligpif),0) REST,
          x.coeftva,
          x.rest_lin - COALESCE(SUM(sign(x.valoare)*COALESCE(stingatori.s_valoare,0)*x.valoarelinie/(Case When COALESCE(x.valoare, 0)= 0 then  1 else x.valoare end)) OVER (PARTITION BY x.coddoc1, x.codobligpif ORDER BY stingatori.codgeneral ROWS BETWEEN unbounded preceding AND CURRENT ROW),0) SOLD_LIN,
          x.rest_doc - COALESCE(SUM(sign(x.valoare)*COALESCE(stingatori.s_valoare,0)*x.valoarelinie/(Case When COALESCE(x.valoare, 0)= 0 then  1 else x.valoare end)
                                   ) OVER (PARTITION BY x.codobligpif ORDER BY x.indexlocal, stingatori.codgeneral ROWS BETWEEN unbounded preceding AND CURRENT ROW),0) SOLD_DOC,
          ROW_NUMBER() OVER (PARTITION BY x.codobligpif, x.coddoc1 ORDER BY stingatori.codgeneral) ORDINE, COUNT(1) OVER (PARTITION BY x.codobligpif, x.coddoc1) ORDINEMAX,
          ROW_NUMBER() OVER (PARTITION BY x.codobligpif ORDER BY x.indexlocal, stingatori.codgeneral) ORDDOC, COUNT(1) OVER (PARTITION BY x.codobligpif) ORDDOCMAX,
          stingatori.prefixdoc DSTINGPR, stingatori.nrdoc DSTINGNR, stingatori.datadoc DSTINGDATA, stingatori.DATADECONT, stingatori.DATAINC, x.TERMEN, x.termen SCADENTA, trunc(stingatori.datadoc::date - x.datadoc::date) DIFZILE,
          case when trunc(stingatori.datadoc - x.termen) &gt; 0 then trunc(stingatori.datadoc - x.termen) else 0 end DEPZILE,
          case when trunc(COALESCE(stingatori.datadecont,stingatori.datadoc) - x.termen) &gt; 0 then trunc(COALESCE(stingatori.datadecont,stingatori.datadoc) - x.termen) else 0 end DEPZILEDEC,
          case when trunc(stingatori.datainc - x.termen) &gt; 0 then trunc(stingatori.datainc - x.termen) else 0 end DEPZILEINC,
          x.codpart, COALESCE(x.agent,0) agent, COALESCE(stingatori.agent,0) agent_sting, x.codcont, COALESCE(x.codlocatie,0) codlocatie,
          x.curs dstinscurs, x.moneda, x.subunitatea dstinssub, stingatori.subunitatea dstingsub,
          x.coddoc, x.coddoc1, x.tipdoc, x.codobiect, x.an dstinsan, x.luna dstinsluna, stingatori.an dstingan, stingatori.luna dstingluna, stingatori.an * 12 + stingatori.luna dstinganluna, stingatori.curs dstingcurs,
          CASE WHEN x.codobiect &lt;= -2 THEN x.codbanca ELSE stingatori.codbanca END codbanca, x.contserv, COALESCE(stingatori.contbanca,x.contbanca) contbanca
        FROM (
              SELECT
                stinsi.*,
                CASE WHEN COALESCE(crs_sold.rest, 0) = 0 THEN COALESCE(stinsi.valoarelinie,0) ELSE COALESCE(crs_sold.rest,0) END rest_lin,
                SUM(CASE WHEN COALESCE(crs_sold.rest, 0) = 0 THEN COALESCE(stinsi.valoarelinie,0) ELSE COALESCE(crs_sold.rest,0) END) OVER (PARTITION BY stinsi.codobligpif) rest_doc
              FROM stinsi LEFT JOIN crs_sold ON crs_sold.codobligpif = stinsi.codobligpif
              WHERE (COALESCE(crs_sold.rest,0) &lt;&gt; 0 OR crs_sold.rest IS NULL) AND stinsi.valoarelinie &lt;&gt; 0
             ) x ' || coalesce(sTipJoin,'') || ' JOIN stingatori ON stingatori.codstinspif = x.codobligpif
      )
      SELECT
        (Case  When ts.codsubunit IS NULL then NULL else UN.NAV_CodDoc end) NAV_CodDoc, (Case  When ts.codsubunit IS NULL then NULL else UN.NAV_CodDoc1 end) NAV_CodDoc1, (Case When ts.codsubunit IS NULL then NULL else UN.NAV_TipDoc end) NAV_TipDoc, ''Incasare'',
        UN.DSTINSPR, UN.DSTINSNR, UN.DSTINSDATA, UN.TOTAL_LIN, UN.TOTAL_LIN * UN.COEFTVA, UN.REST, UN.REST * UN.COEFTVA, UN.VAL_STINGATOR, UN.VAL_STINGATOR * UN.COEFTVA,
        UN.DSTINGPR, UN.DSTINGNR, UN.DSTINGDATA, NPART.DEN_PART, AG.OBS,
        UN.SOLD_LIN, (CASE WHEN UN.ORDINE = UN.ORDINEMAX THEN UN.SOLD_LIN END), UN.SOLD_DOC, (CASE WHEN UN.ORDDOC = UN.ORDDOCMAX THEN UN.SOLD_DOC END),
        UN.DATADECONT, UN.DATAINC, UN.ORDINE, UN.ORDDOC, UN.TERMEN, MON.DEN_MONEDA, SubStins.den_subunit, SubSting.den_subunit,
        UN.SCADENTA, UN.DIFZILE, UN.DEPZILE, UN.DEPZILEDEC, UN.DEPZILEINC, C.SIMBOL, COALESCE(XC.CONTART, CS.SIMBOL), CB.SIMBOL, (CASE WHEN un.codobiect = -1 THEN ''INITIALIZARE''  WHEN un.codobiect = -2 THEN ''AVANS TREZORERIE''  WHEN un.codobiect = -3 THEN ''DECONT CASA/BANCA'' ELSE o.denumire END) ARTICOL, O.CODEXTERN, O.CODINTERN, PROD.DEN_PART, CA.SIMBOL,
        UN.DSTINSCURS, UN.DSTINSAN, UN.DSTINSLUNA, UN.DSTINGCURS, UN.DSTINGAN, UN.DSTINGLUNA, (Case When I1.TIPLINIE=''='' then G2.DEN else G1.DEN_GEST end), (Case When I1.TIPLINIE=''='' then G2.SIMB else G1.SIMBOL end),
        (Case When UN.NAV_TipDoc=33 then ''DECONT CASA/BANCA'' else BC.NRCONT end) ' || coalesce(sCurs,'') || gUserAlias || '
      FROM UN
        LEFT JOIN iesiri              i        ON i.codies            = un.coddoc AND i.tipdoc = un.tipdoc
        LEFT JOIN iesiri1             i1       on i1.codies1          = un.coddoc1 AND i1.codies = i.codies
        LEFT JOIN nartobj             o        ON o.codobiect         = un.codobiect
        LEFT JOIN npers               ag_doc   on ag_doc.codpers      = UN.agent
        LEFT JOIN npers               ag_sting ON ag_sting.codpers    = UN.agent_sting
        LEFT JOIN npart               npart    ON npart.codpart       = UN.codpart
        LEFT JOIN nclasep             clsp     on COALESCE(npart.codclasa, 0) = clsp.codclasep
        LEFT JOIN nagenda             ag       on UN.codlocatie       = ag.codagenda
        LEFT JOIN nlocalit            loc      on ag.codlocalit       = loc.codlocalit
        LEFT JOIN njudet              jud      on loc.codjudet        = jud.codjudet
        LEFT JOIN nmonede             mon      ON mon.codmoneda       = COALESCE(UN.moneda,0)
        LEFT JOIN pretm                        on pretm.codobiect     = UN.CodObiect and pretm.implicit = 1 and pretm.subunitatea = ' || getsubunitate() || '
        LEFT JOIN nsubunit            SubSting ON SubSting.codsubunit = UN.dstingsub
        LEFT JOIN nsubunit            SubStins ON SubStins.codsubunit = UN.dstinssub
        LEFT JOIN tmp_subunitdedicate ts       ON ts.codsubunit       = UN.dstingsub
        LEFT JOIN npart               prod     ON prod.codpart        = o.codproducator
        LEFT JOIN nart                a        ON a.codarticol        = o.codarticol
        LEFT JOIN nclasea             ca       ON ca.codclasea        = a.clasa
        LEFT JOIN nartobj1            n1       on n1.codobiect        = un.codobiect AND ' || coalesce(AnLunaLucru,0) || ' BETWEEN n1.ALStart and n1.ALStop
        LEFT JOIN nmonede             monprest ON monprest.codmoneda  = COALESCE(n1.codmoneda,0)
        LEFT JOIN nartcli             ac       ON ac.codobiect        = un.codobiect AND ac.codpart = un.codpart
        LEFT JOIN ncont               c        ON c.codcont           = un.codcont
        LEFT JOIN ncont               cs       ON cs.codcont          = un.contserv
        LEFT JOIN nbankcont           bc       ON bc.codbankcont      = un.codbanca
        LEFT JOIN nbank               b        ON b.codbank           = bc.codbank
        LEFT JOIN NBANKCONT1          nbc1     ON nbc1.codbankcont    = un.codbanca     AND un.dstinganluna BETWEEN nbc1.ALStart and nbc1.ALStop
        LEFT JOIN IOBANK1             iob1     ON iob1.codiobank      = nbc1.codiobanca AND un.dstinganluna BETWEEN iob1.ALStart and iob1.ALStop
        LEFT JOIN ncont               cb       ON cb.codcont          = COALESCE(un.contbanca,iob1.cont)
        LEFT JOIN ngest               g1       ON g1.codgest          = i1.gestact
        LEFT JOIN (
                    SELECT l1.codies1, l.codies, l.tiplivr, string_agg(DISTINCT ng.den_gest, '''') DEN, string_agg(DISTINCT ng.simbol, '''') SIMB
                    FROM livr1 l1
                         INNER JOIN livr    l  ON l.codlivr     = l1.codlivr
                         LEFT  JOIN nirstoc ns ON ns.codnirstoc = l1.codnirstoc
                         LEFT  JOIN nir     n  ON n.codnir      = ns.codnir
                         LEFT  JOIN livrval lv ON lv.codlivr1   = l1.codlivr1
                         LEFT  JOIN ngest   ng On ng.codgest    = coalesce(lv.gest, n.gest, 0)
                    WHERE ng.codgest &lt;&gt; 0
                    GROUP BY l1.codies1, l.codies, l.tiplivr
                  ) g2 ON g2.codies1 = i1.codies1 AND g2.codies = i.codies AND g2.tiplivr = i.tipdoc
        LEFT JOIN (
                    SELECT
                      i1.codies1,
                      string_agg(DISTINCT c.simbol, '''') contart
                    FROM  iesiri i
                          INNER JOIN iesiri1 i1   ON i.codies      = i1.codies
                          LEFT  JOIN ieslink ilae ON ilae.codies1  = i1.codies1
                          LEFT  JOIN iesiri1 ae1  ON ae1.codies1   = ilae.codlinieaviz
                          LEFT  JOIN iesiri  ae   ON ae.codies     = ae1.codies
                          LEFT  JOIN livr    l    ON l.codies      = COALESCE(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
                          LEFT  JOIN livrval lv   ON lv.codlivr1   = l1.codlivr1
                          LEFT  JOIN nirstoc ns   ON ns.codnirstoc = l1.codnirstoc
                          INNER JOIN ioart1  ioa1 ON ioa1.codioart = COALESCE(lv.codioart,ns.codioart) AND (i.an*12+i.luna) BETWEEN ioa1.ALStart and ioa1.ALStop
                          INNER JOIN ncont   c    ON c.codcont     = ioa1.cont
                    WHERE COALESCE(i.anulat, 0) = 0 and COALESCE(i.initializari, 0) = 0 AND COALESCE(i1.codobiect,0) &lt;&gt; 0 AND i.datadoc &lt;= TO_DATE(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')'
                    || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || ' AND i1.tiplinie = ''=''
                    GROUP BY i1.codies1
                  ) xc ON xc.codies1 = i1.codies1 ' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect1,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect2,''), aListID, aListVer);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_raportagenti_setparams</obj_name>
  <obj_hashval>20f51ae61864682946ca78cc92ca6f28</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportagenti_setparams(ptipdata numeric, pinceput character varying, psfarsit character varying, v_codjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
  dDataS date;
  dDataF date;
BEGIN
  --Adina 11 septembrie 2020
  perform set_config('PKG_LIST_BASE_RAPORTAGENTI.vTipData',( trunc(COALESCE(pTipData,0)) = 1)::varchar,false);

  IF current_setting('PKG_LIST_BASE_RAPORTAGENTI.vTipData', true)::boolean THEN
    dDataS := To_Date(pInceput, 'dd.mm.yyyy');
    dDataF := To_Date(pSfarsit, 'dd.mm.yyyy');
    xLunaAnIni := (extract( year FROM dDataS) * 12 + extract( month FROM dDataS))::numeric;
    xLunaAnFin := (extract( year FROM dDataF) * 12 + extract( month FROM dDataF))::numeric;
  ELSE
    dDataS := To_Date('01.' || coalesce(to_char(pInceput::NUMERIC,'00'),'') || '.' || coalesce(getANLUCRU()::varchar,''), 'dd.mm.yyyy');
    dDataF := Last_Day(To_Date(coalesce(to_char(pSfarsit::NUMERIC,'00'),'') || '.' || coalesce(getANLUCRU()::varchar,''), 'mm.yyyy'));
    xLunaAnIni := getANLUCRU() * 12 + pInceput::numeric;
    xLunaAnIni := getANLUCRU() * 12 + pSfarsit::numeric;
  END IF;

  IF  COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, dDataS, dDataF, xLunaAnIni, xLunaAnFin);
  END IF;

  IF current_setting('PKG_LIST_BASE_RAPORTAGENTI.vTipData', true)::boolean THEN
    perform set_config('PKG_LIST_BASE_RAPORTAGENTI.vInceput',('To_Date(''' || coalesce(To_Char(dDataS, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')')::varchar,false);
    perform set_config('PKG_LIST_BASE_RAPORTAGENTI.vSfarsit',('To_Date(''' || coalesce(To_Char(dDataF, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')')::varchar,false);
  ELSE
    perform set_config('PKG_LIST_BASE_RAPORTAGENTI.vInceput',(xLunaAnIni)::varchar,false);
    perform set_config('PKG_LIST_BASE_RAPORTAGENTI.vSfarsit',(xLunaAnIni)::varchar,false);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_raportcumparari_processlist</obj_name>
  <obj_hashval>dee8813f190ebe2c27c91b65da3602b3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportcumparari_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert      varchar;
  sSelect      varchar;
  sWhereP      varchar;
  sCurs        varchar;
  sInsertUMA   varchar;
  sSelectUMA   varchar;
  sSelectIG    varchar;
  sFiltruPart  varchar := '';
  sFromIG      varchar;
  sJoinIG      varchar;
  sWhereIG     varchar;
  sGroupIG     varchar;
  sWith        varchar;
  sJoin        varchar;
  aSitV        numeric;
  aBancaV      numeric;
  aMonedaV     numeric;
  sCondCatPret varchar;
  gSuplCols    varchar :=  'nartobj nao, nart na, num num, npers ag, nclasea nca, nclaseas ncs, npart prod, npart np, nclasep ncp, nagenda sed, nlocalit sedl, pretm p';
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplJoins   VARCHAR := '';
  wmeRes       boolean;
BEGIN
  --Florin 09.04.2024 - fixat 61622
  --Adina 19.02.2021 - GetInfoSitValuta si PKG_LIST_BASE_UTILS_UMA_UTILS
  --Adina 11.02.2021 - corectat PKG_LIST_BASE_UTILS_GETCURSREFERINTA in loc de PKG_LIST_BASE_UTILS.GETCURSREFERINTA
  --Florin 31.08.20250
  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_RAPORTCUMPARARI.gSuplCols',gSuplCols,false);

  sWhereP := ' AND ';
  IF current_setting('PKG_LIST_BASE_RAPORTCUMPARARI.vTipData', true) THEN
    sWhereP := coalesce(sWhereP,'') || 'I.DATADOC';
  ELSE
    sWhereP := coalesce(sWhereP,'') || 'I.An = ' || coalesce(getanlucru(), 0) || ' AND I.LUNA';
  END IF;

  IF  current_setting('PKG_LIST_BASE_RAPORTCUMPARARI.vInceput', true) = current_setting('PKG_LIST_BASE_RAPORTCUMPARARI.vSfarsit', true) THEN
    sWhereP := coalesce(sWhereP,'') || ' = ' || coalesce(current_setting('PKG_LIST_BASE_RAPORTCUMPARARI.vInceput', true),'');
  ELSE
    sWhereP := coalesce(sWhereP,'') || ' BETWEEN ' || coalesce(current_setting('PKG_LIST_BASE_RAPORTCUMPARARI.vInceput', true),'') || ' AND ' || coalesce(current_setting('PKG_LIST_BASE_RAPORTCUMPARARI.vSfarsit', true),'');
  END IF;

  IF  current_setting('PKG_LIST_BASE_RAPORTCUMPARARI.vAllPart', true)::numeric = 1 THEN
    sFiltruPart := ' IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPART'')';
  END IF;

  IF  current_setting('PKG_LIST_BASE_RAPORTCUMPARARI.vAllPart', true)::numeric = 2 THEN
    sFiltruPart := ' NOT IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPART'')';
  END IF;

  IF sFiltruPart IS NOT NULL AND sFiltruPart &lt;&gt; '' THEN
    sWhereP := coalesce(sWhereP,'') || '
            AND I.PARTENER::varchar' || coalesce(sFiltruPart,'');
  END IF;

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

  IF current_setting('PKG_LIST_BASE_RAPORTCUMPARARI.vValuta', true)::boolean AND wmeRes  --(SELECT FNC_GetInfoSitValuta.wme_result FROM FNC_GetInfoSitValuta())
  THEN
    --SELECT FNC_GetInfoSitValuta.pBancaValuta, FNC_GetInfoSitValuta.pMonedaValuta INTO aBancaV, aMonedaV FROM FNC_GetInfoSitValuta();
    sCurs := ' / PKG_LIST_BASE_UTILS_GETCURSREFERINTA(' || coalesce(aMonedaV::varchar,'0') || ',' || coalesce(aBancaV::varchar,'0') || ', to_char(i1.datadoc,''dd.mm.yyyy'') )';
  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   sInsertUMA, sSelectUMA, sJoin
  FROM PKG_LIST_BASE_UTILS_UMA_UTILS('ig.cant', 'ig.codobiect', sInsertUMA, sSelectUMA, sJoin,NULL);
  --PERFORM PKG_LIST_BASE_UTILS_UMA_UTILS('ig.cant', 'ig.codobiect', sInsertUMA, sSelectUMA, sJoin,NULL);

  IF current_setting('PKG_LIST_BASE_RAPORTCUMPARARI.vTipTarget', true)::numeric = 1 THEN
    sSelectIG := '
            0 AGENT, T.FURNIZOR PARTENER, 0 CODLOCATIE,
            CASE T.TIPTARGET WHEN 3 THEN T.CLASASBAZA WHEN 0 THEN A.CLASASTATIST ELSE 0 END CLASAS,
            CASE T.TIPTARGET WHEN 2 THEN T.CLASABAZA  WHEN 0 THEN A.CLASA        ELSE 0 END CLASA,
            CASE T.TIPTARGET WHEN 0 THEN O.CODOBIECT  WHEN 2 THEN O.CODOBIECT    ELSE 0 END CODOBIECT,
            T.CANTTARGET, T.VALTARGET, T.MASATARGET, T.VOLUMTARGET, T.TIPTARGET, 1 CountFurn,';
    sFromIG := 'TARGET T
            LEFT JOIN I1 ON T.FURNIZOR = I1.PARTENER AND I1.DATADOC BETWEEN T.DATASTART AND T.DATASTOP AND I1.CANT &lt;&gt; 0
              AND CASE T.TIPTARGET WHEN 0 THEN T.CODOBIECT ELSE I1.CODOBIECT END = I1.CODOBIECT
              AND CASE T.TIPTARGET WHEN 2 THEN T.CLASA     ELSE I1.CLASA     END = I1.CLASA
              AND CASE T.TIPTARGET WHEN 3 THEN T.CLASAS    ELSE I1.CLASAS    END = I1.CLASAS
            LEFT JOIN NARTOBJ O ON O.CODOBIECT = Coalesce(I1.CODOBIECT, T.CODOBIECT)
            LEFT JOIN NART A ON A.CODARTICOL = O.CODOBIECT';
    sJoinIG := '';
    sGroupIG := 'T.FURNIZOR,
            CASE T.TIPTARGET WHEN 3 THEN T.CLASASBAZA WHEN 0 THEN A.CLASASTATIST ELSE 0 END,
            CASE T.TIPTARGET WHEN 2 THEN T.CLASABAZA  WHEN 0 THEN A.CLASA        ELSE 0 END,
            CASE T.TIPTARGET WHEN 0 THEN O.CODOBIECT  WHEN 2 THEN O.CODOBIECT    ELSE 0 END,
            T.CANTTARGET, T.VALTARGET, T.MASATARGET, T.VOLUMTARGET, T.TIPTARGET';
    sWith := coalesce(sWith,'') || 'TARGET AS (
        SELECT
          T.CLIENT FURNIZOR, T.DATASTART, T.DATASTOP, Coalesce(T.TIPTARGET,0) TIPTARGET,
          T1.CODOBIECT, C.CLASABAZA, C.CLASA, CS.CLASASBAZA, CS.CLASAS,
          Coalesce(T1.CANT,0) CANTTARGET, Coalesce(T1.VALOARE,0) VALTARGET, Coalesce(T1.MASA,0) MASATARGET, Coalesce(T1.Volum,0) VOLUMTARGET
        FROM TARGETAG T
          INNER JOIN TARGETAG1 T1 ON T1.CODTARGETAG = T.CODTARGETAG
           LEFT JOIN (
            WITH recursive cl(clasabaza, codclasea, rootclasabaza) AS(
              SELECT codclasea clasabaza, codclasea, codclasea rootclasasbaza
            FROM nclasea
              UNION ALL
               SELECT n.codclasea clasabaza, n.codclasea clasa, cl.rootclasabaza
            FROM nclasea n INNER JOIN cl ON cl.codclasea = n.codparinte
            )
            SELECT rootclasabaza CLASABAZA, codclasea CLASA FROM cl
          ) C ON C.CLASABAZA = CASE T.TIPTARGET WHEN 2 THEN T1.CODCLASA ELSE 0 END
          LEFT JOIN (
            WITH recursive cl1(clasasbaza, codclaseas, rootclasasbaza) AS (
              SELECT codclaseas clasasbaza, codclaseas, codclaseas rootclasasbaza
            FROM nclaseas
              UNION ALL
               SELECT n.codclaseas clasasbaza, n.codclaseas clasas, cl1.rootclasasbaza
            FROM nclaseas n INNER JOIN cl1 ON cl1.codclaseas = n.codparinte
             )
            SELECT rootclasasbaza CLASASBAZA, codclaseas CLASAS FROM cl1
          ) CS ON CS.CLASASBAZA = CASE T.TIPTARGET WHEN 3 THEN T1.CODCLASAS ELSE 0 END
        WHERE T.TIPDOC = 98
          AND T.DATASTART &lt;= ' || coalesce(current_setting('PKG_LIST_BASE_RAPORTCUMPARARI.xSfarsit', true),'') || '
          AND T.DATASTOP &gt;= ' || coalesce(current_setting('PKG_LIST_BASE_RAPORTCUMPARARI.xInceput', true),'') || '
          AND T.ANULAT = 0 AND T.OPERAT = 1 AND T.ACTIV = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL),'') || coalesce(CASE
      WHEN sFiltruPart IS NOT NULL AND sFiltruPart &lt;&gt; '' THEN '
          AND T.CLIENT::varchar' || coalesce(sFiltruPart,'')
     END ,'') || '),';
  ELSE
    sSelectIG := '
            I1.AGENT, I1.PARTENER, I1.CODLOCATIE,
            I1.CLASA,
            I1.CLASAS,
            I1.CODOBIECT,
            0 CANTTARGET, 0 VALTARGET, 0 MASATARGET, 0 VOLUMTARGET, 0 TIPTARGET, COUNT(DISTINCT I1.PARTENER||'' ''||I1.CODLOCATIE) CountFurn,';
    sFromIG := 'I1
            LEFT JOIN NARTOBJ O ON O.CODOBIECT = I1.CODOBIECT';
    sWhereIG := '
          WHERE i1.cant &lt;&gt; 0';
    sGroupIG := 'I1.AGENT, I1.PARTENER, I1.CODLOCATIE, I1.CLASA, I1.CLASAS, I1.CODOBIECT';
  END IF;

  sCondCatPret := ' AND P.Subunitatea = ' || coalesce(current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, 0);
  IF Coalesce(current_setting('PKG_LIST_BASE_RAPORTCUMPARARI.vCatPret', true)::numeric, 0) = 0 THEN
    sCondCatPret := coalesce(sCondCatPret,'') || ' AND p.implicit = 1 ';
  ELSE
    sCondCatPret := coalesce(sCondCatPret,'') || ' AND p.codcatpret = ' || coalesce(current_setting('PKG_LIST_BASE_RAPORTCUMPARARI.vCatPret', true)::numeric, 0);
  END IF;

  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(
        Art,
        UM, Cant, Val, ValCuTva, VU, Masa, Volum,
        DenClasaA, CodInt, CodExt, Prod, PretVinz, PretValuta,
        Agent, NrFurn,
        Furnizor, DenClasaF, SedFurn, AdrSedFurn, NrUtilaje,
        TarTip,
        TarCant, TarVal, TarMasa, TarVolum' || coalesce(sInsertUMA,'') || gUserFields || '
      )';
  sSelect := '
      WITH ' || coalesce(sWith,'') || '
      I1 AS (
        SELECT
          I.CODINTR, I1.CODINTR1, I.DATADOC, Coalesce(NULLIF(I.CURS,0),1) CURS, Coalesce(I.AGENT,0) AGENT, I.PARTENER, Coalesce(I.CODLOCATIE,0) CODLOCATIE,
          I1.CODOBIECT, Coalesce(A.CLASA,0) CLASA, Coalesce(A.CLASASTATIST,0) CLASAS, I1.CANT, I1.PU, I.VALDOC-I.TVADOC VALDOC, I.VALDOC VALTDOC,
          CASE WHEN i1.cant*i1.pu = 0 THEN 0 ELSE i1.cant*i1.pretorig*Coalesce(i1.coefdiscmaj,1)*(1-CASE WHEN i.tipdoc = 3 THEN Coalesce(i1.tva,0)/(i1.cant*i1.pu) ELSE 0 END) END vallin,
          CASE WHEN i1.cant*i1.pu = 0 THEN 0 ELSE i1.cant*i1.pretorig*Coalesce(i1.coefdiscmaj,1)*(1+CASE WHEN i.tipdoc = 3 THEN 0 ELSE Coalesce(i1.tva,0)/(i1.cant*i1.pu) END) END valtlin,
          SUM(CASE WHEN i1.cant*i1.pu = 0 THEN 0 ELSE i1.cant*i1.pretorig*Coalesce(i1.coefdiscmaj,1)*(1-CASE WHEN i.tipdoc = 3 THEN Coalesce(i1.tva,0)/(i1.cant*i1.pu) ELSE 0 END) END) OVER (PARTITION BY I.CODINTR) VALINTR,
          SUM(CASE WHEN i1.cant*i1.pu = 0 THEN 0 ELSE i1.cant*i1.pretorig*Coalesce(i1.coefdiscmaj,1)*(1+CASE WHEN i.tipdoc = 3 THEN 0 ELSE Coalesce(i1.tva,0)/(i1.cant*i1.pu) END) END) OVER (PARTITION BY I.CODINTR) VALTINTR,
          ROW_NUMBER() OVER (PARTITION BY I.CODINTR ORDER BY I1.CODINTR1) IDX
        FROM INTRARI I
          INNER JOIN INTRARI1 I1 ON I1.CODINTR = I.CODINTR
          INNER JOIN NARTOBJ O ON O.CODOBIECT = I1.CODOBIECT
          INNER JOIN NART A ON A.CODARTICOL = O.CODARTICOL
        WHERE I.TIPDOC::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''TIPDOC'') AND I.ANULAT = 0 AND I.OPERAT = 1 ' || coalesce(sWhereP,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '),
      IG AS (
        SELECT ' || coalesce(sSelectIG,'') || '
          SUM(CASE WHEN Coalesce(AE1.CANT,0) &lt;&gt; 0 AND Coalesce(NS.CANTNIR,0) &lt;&gt; 0 THEN NS.CANTNIR*I1.CANT/AE1.CANT ELSE COALESCE(NS.CANTNIR,I1.CANT,0) END) CANT,
          SUM(CASE WHEN Coalesce(AE1.CANT,0) &lt;&gt; 0 AND Coalesce(NS.CANTNIR,0) &lt;&gt; 0 THEN NS.CANTNIR*I1.CANT/AE1.CANT ELSE COALESCE(NS.CANTNIR,I1.CANT,0) END*Coalesce(O.MASA,0)) MASA,
          SUM(CASE WHEN Coalesce(AE1.CANT,0) &lt;&gt; 0 AND Coalesce(NS.CANTNIR,0) &lt;&gt; 0 THEN NS.CANTNIR*I1.CANT/AE1.CANT ELSE COALESCE(NS.CANTNIR,I1.CANT,0) END*Coalesce(O.VOLUM,0)) VOLUM,
          Coalesce(SUM(i1.pu*i1.cant*i1.curs' || coalesce(sCurs,'') || '),0) vu,
          Coalesce(SUM(i1.vallin *CASE WHEN i1.valintr  = 0 THEN 1 ELSE i1.valdoc /i1.valintr  END*i1.curs' || coalesce(sCurs,'') || '),0) val,
          Coalesce(SUM(i1.valtlin*CASE WHEN i1.valtintr = 0 THEN 1 ELSE i1.valtdoc/i1.valtintr END*i1.curs' || coalesce(sCurs,'') || '),0) valcutva
        FROM ' || coalesce(sFromIG,'') || '
          LEFT JOIN INTRLINK IL  ON IL.CODINTR1  = I1.CODINTR1
          LEFT JOIN INTRARI1 AE1 ON AE1.CODINTR1 = IL.CODLINIEAVIZ
          LEFT JOIN NIR      N   ON N.CODINTR    = Coalesce(AE1.CODINTR,I1.CODINTR)
          LEFT JOIN NIRSTOC  NS  ON NS.CODINTR1  = Coalesce(IL.CODLINIEAVIZ,I1.CODINTR1) AND NS.CODNIR = N.CODNIR' || coalesce(sJoinIG,'') || coalesce(sWhereIG,'') || '
        GROUP BY ' || coalesce(sGroupIG,'') || ' )
      SELECT
        CASE
          WHEN Coalesce(NAO.CODOBIECT, 0) &lt;&gt; 0 THEN NAO.DENUMIRE
          WHEN Coalesce(NCA.CODCLASEA, 0) &lt;&gt; 0 THEN NCA.DEN_CLASEA
          WHEN Coalesce(NCS.CODCLASEAS,0) &lt;&gt; 0 THEN NCS.DEN_CLASEAS
          ELSE ''...''
        END,
        Coalesce(NUM.DEN_UM,''...''), CASE WHEN IG.CODOBIECT = 0 THEN 0 ELSE IG.CANT END, IG.VAL, IG.VALCUTVA, IG.VU, IG.MASA, IG.VOLUM,
        NCA.DEN_CLASEA, NAO.CODINTERN, NAO.CODEXTERN, PROD.DEN_PART, P.LEI PRETVANZ, P.VALUTA,
        (SELECT NUMEPRENUME.WME_RESULT FROM NUMEPRENUME(NULL, AG.NUME,AG.PRENUME)) Agent, IG.CountFurn NrFurn,
        NP.DEN_PART Furnizor, NCP.DEN_CLASEP DenClasaF, SED.OBS SedFurn, SEDL.DEN_LOCALIT||'' ''||fnc_GETADRESA(SED.SECTOR,SED.STRADA,SED.NR1,SED.NR2,SED.BLOC,SED.SCARA,SED.ETAJ,SED.APART,SED.CODPOSTAL) AdrSedFurn, SED.COEFUTILAJE NrUtilaje,
        CASE IG.TIPTARGET
          WHEN NULL THEN '' ''
          WHEN    3 THEN ''Pe clase statistice de articole''
          WHEN    2 THEN ''Pe clase de articole''
          WHEN    1 THEN ''Toate Articolele''
          WHEN    0 THEN ''Pe articole''
        END TarTip,
        IG.CANTTARGET TarCant, IG.VALTARGET TarVal, IG.MASATARGET TarMasa, IG.VOLUMTARGET TarVolum ' || coalesce(sSelectUMA,'') || gUserAlias || '
      FROM IG
        LEFT JOIN NARTOBJ  NAO  ON NAO.CODOBIECT   = IG.CODOBIECT
        LEFT JOIN NART     NA   ON NA.CODARTICOL   = NAO.CODARTICOL
        LEFT JOIN NUM           ON NUM.CODUM       = NA.UM
        LEFT JOIN NCLASEA  NCA  ON NCA.CODCLASEA   = IG.CLASA
        LEFT JOIN NCLASEAS NCS  ON NCS.CODCLASEAS  = IG.CLASAS
        LEFT JOIN NPART    PROD ON PROD.CODPART    = NAO.CODPRODUCATOR
        LEFT JOIN NPART    NP   ON NP.CODPART      = IG.PARTENER
        LEFT JOIN NCLASEP  NCP  ON NCP.CODCLASEP   = NP.CODCLASA
        LEFT JOIN NAGENDA  SED  ON SED.CODAGENDA   = IG.CODLOCATIE
        LEFT JOIN NLOCALIT SEDL ON SEDL.CODLOCALIT = SED.CODLOCALIT
        LEFT JOIN NPERS    AG   ON AG.CODPERS      = IG.AGENT
        LEFT JOIN PRETM    P    ON P.CODOBIECT     = IG.CODOBIECT ' || coalesce(sCondCatPret,'') || coalesce(sJoin,'') || gSuplJoins;
--    INSERT INTO x (view_name, test) VALUES ('raportcump', 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_raportcumparari_setjoinuri</obj_name>
  <obj_hashval>8a193aa06f66249a688d06966117ec47</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportcumparari_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 29.08.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_RAPORTCUMPARARI.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_raportgestcval_jointmp</obj_name>
  <obj_hashval>d229f8e39518ffb66384ad82068e6e4d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportgestcval_jointmp(INOUT wme_result character varying, INOUT vcamp character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Adina iulie 2020
  IF (SELECT PKG_LIST_SELECTGEST2_ToateGest.WME_RESULT FROM PKG_LIST_SELECTGEST2_ToateGest(NULL,NULL)) THEN
    WME_Result :=  NULL;
    RETURN;
  ELSE
    WME_Result :=  '
          INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = ' || coalesce(vcamp,'') ||':: character varying ' || ' AND TMP.FILTRU = ''CODGEST''';
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_raportgestcval_setjoinuri</obj_name>
  <obj_hashval>e307d0f3feb1c81ee0ae83cd8e28698f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportgestcval_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Adina iulie 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_RAPORTGESTCVAL.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_raportgestpmp_jointmp</obj_name>
  <obj_hashval>4e5976827c99ae9825661fa6b48747c9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportgestpmp_jointmp(INOUT wme_result character varying, INOUT vcamp character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Adina iulie 2020
  IF (SELECT PKG_LIST_SELECTGEST2_ToateGest.WME_RESULT FROM PKG_LIST_SELECTGEST2_ToateGest(NULL,NULL)) THEN
    WME_Result :=  NULL;
    RETURN;
  ELSE
    WME_Result :=  '
          INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = ' || coalesce(vcamp,'')||':: character varying ' || ' AND TMP.FILTRU = ''CODGEST''';
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_raportgestval_jointmp</obj_name>
  <obj_hashval>724c5211ef32d7117ebfe4953ae13200</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportgestval_jointmp(INOUT wme_result character varying, INOUT vcamp character varying)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Adina iulie 2020
  IF (SELECT PKG_LIST_SELECTGEST2_ToateGest.WME_RESULT FROM PKG_LIST_SELECTGEST2_ToateGest(NULL,NULL)) THEN
    WME_Result :=  NULL;
    RETURN;
  ELSE
    WME_Result :=  '
          INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = ' || coalesce(vcamp,'') ||':: character varying ' || ' AND TMP.FILTRU = ''CODGEST''';
    RETURN;
  END IF;
end;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_raportp_m_setparams</obj_name>
  <obj_hashval>e2e73c5db9fdf7049437d7ff7e3998fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportp_m_setparams(pcodraportp numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16 septembrie 2020
  perform set_config('PKG_LIST_BASE_RAPORTP_M.vCodRaportP',(pCodRaportP)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_raportp_setjoinuri</obj_name>
  <obj_hashval>17245467cd80a7c5fc261d2b2929b6cb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportp_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 15.09.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_RAPORTP.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_raportp_setparams</obj_name>
  <obj_hashval>b54f3159b3cf4303e482e33c16f06dd9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportp_setparams(pcodraportp numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06.01.2021
  perform set_config('PKG_LIST_BASE_RAPORTP.vCodRaportP',(pCodRaportP)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_raportpdoc_processlist</obj_name>
  <obj_hashval>3af067d1a95551a80e447455d8991e23</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportpdoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'RaportP P, RaportP1 P1, RaportP2 P2, NPERS A, NartObj Ob, ProdMan PM, NOper Op, Comanda1 C1, Comanda C';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  sAnLunaLucru    varchar := coalesce(getAnLunalucru()::varchar,'0');
BEGIN
  --Adina 11.05.2021 - alstart, alstop, sAnLunaLucru
  --Adina 15.02.2021 tichet 43166
  --Adina 15.10.2020
  CALL PRC_AL_CHECK('tarifeman1', 0);

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

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    Ang,
    Ord,
    Com, Art, Oper,
    Realizat, TNorma, TValoare' || gUserFields || ')
  SELECT
    (case when P1.Angajat=0 then A.NUME else coalesce(A.NUME,'''')||'' ''||coalesce(A.PRENUME,'''') end),
    ROW_NUMBER() OVER (PARTITION BY P2.CodRaportP1 ORDER BY P2.CODRAPORTP2 ASC),
    coalesce(C.PREFIXDOC,'''')||coalesce(C.NRDOC::varchar,'''')||''/''||coalesce(to_char(C.DATADOC,''dd.mm.yyyy''),''''),
    coalesce(OB.DENUMIRE,''''),
    coalesce(PM.NROP::varchar,'''')||''/''|| coalesce(OP.DENUMIRE,''''),
    P2.REALIZAT, P2.TU * P2.REALIZAT, T1.Tarif * coalesce(P2.TU, pm.tu) * P2.REALIZAT / 60' || gUserAlias || '
  FROM   RaportP P
        INNER JOIN RaportP0   P0 ON P0.CodRaportP  = P.CodRaportP
        INNER JOIN RaportP1   P1 ON P1.CodRaportP0 = P0.CodRaportP0
        INNER JOIN RaportP2   P2 ON P2.CodRaportP1 = P1.CodRaportP1
        LEFT  JOIN ProdMan    PM ON PM.CodMan      = P2.CodMan
        LEFT  JOIN Tarifeman1 T1 ON T1.CodTarif    = coalesce(P2.CodTarif,PM.CodTarif) AND '||sAnLunaLucru||' BETWEEN T1.ALSTART and T1.ALSTOP
        LEFT  JOIN NPERS      A  ON A.CodPers      = P1.Angajat
        LEFT  JOIN NartObj    Ob ON Ob.CodObiect   = P2.CodObiect
        LEFT  JOIN NOper      Op ON Op.CodOp       = coalesce(P2.CODOP,PM.CodOp)
        LEFT  JOIN Comanda1   C1 ON C1.CodComanda1 = P2.CodComanda1
        LEFT  JOIN Comanda    C  ON C.CodComanda   = C1.CodComanda' || gSuplJoins || '
  WHERE P.CodRaportP = ' || coalesce(current_setting('PKG_LIST_BASE_RAPORTPDOC.vCodRaportP', true),'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_raportpdoc_setparams</obj_name>
  <obj_hashval>d1d96ce1c951481dfc85f6d51350e438</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportpdoc_setparams(pcodraportp numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  perform set_config('PKG_LIST_BASE_RAPORTPDOC.vCodRaportP',(pCodRaportP)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_raportschimb_processlist</obj_name>
  <obj_hashval>6bea4d2fbd8cd761895485cd948a403f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportschimb_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sSelect     varchar;
  gSuplCols   VARCHAR := 'comanda c,comanda1 c1,nartobj objprod,nart artprod,nartobj objmat,nart artmat,prodnorme nor,normemat nmat,' || 'prodcomp pc';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 14.09.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_RAPORTSCHIMB.gSuplCols', gSuplCols, FALSE);

  sInsert := 'insert into ' || tmpName || '(
       NAV_CodDoc,
       NAV_TipDoc,
       NrDoc,
       DataDoc,
       Schimb,
       Formatie,
       Sectie,
       DenProd,
       Prod_UM,
       Prod_Cant,
       Prod_CodExtern,
       DenComp,
       Comp_UM,
       Comp_UM1,
       Comp_CantN,
       Comp_CantN_UM1,
       Comp_CodIntern,
       Comp_Claseas,
       Comp_Clasea,
       Norma,
       Comp_CantNormata,
       Comp_CantNormataUMs ' || gUserFields || ')' || coalesce(chr(13),'');
  sSelect := 'select
      c.codcomanda NAV_CodDoc,
      c.tipdoc NAV_TipDoc,
      c.NrDoc,
      c.DataDoc,
      c.Schimb,
      f.den_formatie Formatie,
      s.den_gest Sectie,
      objprod.denumire DenProd,
      umprod.den_um Prod_UM,
      prod.cant Prod_Cant,
      objprod.codextern Prod_CodExtern,
      objmat.denumire DenComp,
      ummat.den_um Comp_UM,
      um1mat.den_um Comp_UM1,
      nmat.cant/(CASE WHEN COALESCE(pc.cant,0) = 0 THEN 1 ELSE pc.cant END) Comp_CantN,
      nmat.cantum1/(CASE WHEN COALESCE(pc.cant,0) = 0 THEN 1 ELSE pc.cant END) Comp_CantN_UM1,
      objmat.codintern Comp_CodIntern,
      clsasmat.den_claseas Comp_Claseas,
      clsamat.den_clasea Comp_Clasea,
      nor.Norma,
      COALESCE(nmat.cant,0)*c1.cantacceptat/(CASE WHEN COALESCE(pc.cant,0) = 0 THEN 1 ELSE pc.cant END),
      COALESCE(nmat.cantum1,0)*c1.cantacceptat/(CASE WHEN COALESCE(pc.cant,0) = 0 THEN 1 ELSE pc.cant END) ' || gUserAlias || '
    from comanda c
         inner join comanda1   c1       on c1.codcomanda       = c.codcomanda
         inner join prodcomp   pc       on pc.codprodcomp      = c1.codreteta
         inner join ngest      s        on s.codgest           = c.codgest
         inner join cmdprodmat prod     on c1.codcomanda1      = prod.codcomanda1 and prod.tip = 0
         inner join nartobj    objprod  on objprod.codobiect   = prod.codobiect
         inner join nart       artprod  on objprod.codarticol  = artprod.codarticol
         inner join num        umprod   on umprod.codum        = artprod.um
         inner join prodnorme  nor      on c1.codnorma         = nor.codnorma
         inner join normemat   nmat     on nor.codnorma        = nmat.codnorma
         inner join nartobj    objmat   on objmat.codobiect    = nmat.codobiect
         inner join nart       artmat   on objmat.codarticol   = artmat.codarticol
         inner join num        ummat    on ummat.codum         = artmat.um
         left  join nclasea    clsamat  on clsamat.codclasea   = artmat.clasa
         left  join nclaseas   clsasmat on clsasmat.codclaseas = artmat.clasastatist
         left  join num        um1mat   on um1mat.codum        = artmat.um1
         left  join formatii   f        on f.codformatie       = c.codformatie' || gSuplJoins || '
    where c.datadoc between to_date(''' || coalesce(current_setting('PKG_LIST_BASE_RAPORTSCHIMB.vDataIni', true),'') || ''', ''dd.mm.yyyy'')
      and to_date(''' || coalesce(current_setting('PKG_LIST_BASE_RAPORTSCHIMB.vDataFin', true),'') || ''', ''dd.mm.yyyy'')
      and c.tipdoc = 53
      and COALESCE(c.anulat,0) = 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_raportschimb_setjoinuri</obj_name>
  <obj_hashval>0d55de40f160a9125299595cd3b9186a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportschimb_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 15.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_RAPORTSCHIMB.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_raportschimb_setparams</obj_name>
  <obj_hashval>2ada8364c4cb3e7ed15707504ab73d02</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportschimb_setparams(adataini character varying, adatafin character varying, v_codjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
BEGIN
  --Florin 14.09.2020
  PERFORM set_config('PKG_LIST_BASE_RAPORTSCHIMB.vDataIni', aDataIni, FALSE);
  PERFORM set_config('PKG_LIST_BASE_RAPORTSCHIMB.vDataFin', aDataFin, FALSE);
  IF COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, current_setting('PKG_LIST_BASE_RAPORTSCHIMB.vDataIni', true), current_setting('PKG_LIST_BASE_RAPORTSCHIMB.vDataFin', true), xLunaAnIni, xLunaAnFin);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_raportvanzari_setjoinuri</obj_name>
  <obj_hashval>db5332f4f2327fadf706a708a70519df</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportvanzari_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 29.08.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_RAPORTVANZARI.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_raportvanzari_setparams</obj_name>
  <obj_hashval>5e71919a7d0ed9b89ae2ba9e811f05d6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportvanzari_setparams(ptipdata numeric, pinceput character varying, psfarsit character varying, ptiptarget numeric, pvaluta numeric, pcatpret numeric, pallpart numeric, v_codjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAuxData   date;
  vAuxData1  date;
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
  sDataS     varchar;
  sDataF     varchar;
BEGIN
  --Florin 26.01.2022 - fixat 52778
  --Florin 31.08.2020
  PERFORM set_config('PKG_LIST_BASE_RAPORTVANZARI.vTipTarget', pTipTarget::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_RAPORTVANZARI.vValuta'   , ((COALESCE(pValuta, 0) = 1)::varchar), FALSE);
  PERFORM set_config('PKG_LIST_BASE_RAPORTVANZARI.vCatPret'  , pCatPret::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_RAPORTVANZARI.vAllPart'  , pAllPart::varchar, FALSE);
  sDataS := pInceput;
  sDataF := pSfarsit;
  PERFORM set_config('PKG_LIST_BASE_RAPORTVANZARI.vTipData', (COALESCE(pTipData, 0) = 1)::varchar,false);
  IF COALESCE(pTipData, 0) = 1 THEN
    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'));
    PERFORM set_config('PKG_LIST_BASE_RAPORTVANZARI.vInceput', 'To_Date(''' || sDataS || ''', ''dd.mm.yyyy'')', FALSE);
    PERFORM set_config('PKG_LIST_BASE_RAPORTVANZARI.vSfarsit', 'To_Date(''' || sDataF || ''', ''dd.mm.yyyy'')', FALSE);
    IF COALESCE(v_CodJob1, 0) &gt; 0 THEN
      PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, current_setting('PKG_LIST_BASE_RAPORTVANZARI.vInceput', true), current_setting('PKG_LIST_BASE_RAPORTVANZARI.vSfarsit', true), xLunaAnIni, xLunaAnFin);
    END IF;
    PERFORM set_config('PKG_LIST_BASE_RAPORTVANZARI.xInceput', current_setting('PKG_LIST_BASE_RAPORTVANZARI.vInceput', TRUE), FALSE);
    PERFORM set_config('PKG_LIST_BASE_RAPORTVANZARI.xSfarsit', current_setting('PKG_LIST_BASE_RAPORTVANZARI.vSfarsit', TRUE), FALSE);
  ELSE
    xLunaAnIni := getanlucru() * 12 + sDataS::NUMERIC;
    xLunaAnFin := getanlucru() * 12 + sDataF::NUMERIC;
    PERFORM set_config('PKG_LIST_BASE_RAPORTVANZARI.vInceput', sDataS, FALSE);
    PERFORM set_config('PKG_LIST_BASE_RAPORTVANZARI.vSfarsit', sDataF, FALSE);
    vAuxData := DATE_TRUNC('MONTH',To_Date(coalesce(getanlucru(), 0) || '.' || coalesce(sDataS,''), 'yyyy.mm'));
    vAuxData1 := TO_DATE(TO_CHAR(DATE_TRUNC('MONTH',To_Date(COALESCE(getanlucru(), 0)::varchar || '.' || coalesce(sDataF,''), 'yyyy.mm')), 'dd.mm.yyyy'), 'dd.mm.yyyy');
    IF COALESCE(v_CodJob1, 0) &gt; 0 THEN
      PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, vAuxData, vAuxData1, xLunaAnIni, xLunaAnFin);
    END IF;
    PERFORM set_config('PKG_LIST_BASE_RAPORTVANZARI.xInceput', 'To_Date(''' || vAuxData::varchar ||''',''dd-mm-yyyy'')', FALSE);
    PERFORM set_config('PKG_LIST_BASE_RAPORTVANZARI.xSfarsit', 'To_Date(''' || vAuxData1::varchar ||''',''dd-mm-yyyy'')', FALSE);
  END IF;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rapstoc_setparams</obj_name>
  <obj_hashval>670e658201998679c9cdd9ab9ce0bb8b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rapstoc_setparams(pdataini character varying DEFAULT NULL::character varying, pdatafin character varying DEFAULT NULL::character varying, ppromoseparat numeric DEFAULT 0, ptoategest numeric DEFAULT 1, ptoateioart numeric DEFAULT 1, v_codjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
BEGIN
  --Adina 10 septembrie 2020
  perform set_config('PKG_LIST_BASE_RAPSTOC.vPromoSeparat',(trunc(COALESCE(pPromoSeparat,0)) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_RAPSTOC.vToateGest'   ,(trunc(COALESCE(pToateGest,0))    = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_RAPSTOC.vToateIOArt'  ,(trunc(COALESCE(pToateIOArt,0))   = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_RAPSTOC.dDataIni'     ,pDataIni                                       ,false);
  perform set_config('PKG_LIST_BASE_RAPSTOC.dDataFin'     ,pDataFin                                       ,false);

  IF COALESCE(v_CodJob1,0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1,current_setting('PKG_LIST_BASE_RAPSTOC.dDataIni', true),current_setting('PKG_LIST_BASE_RAPSTOC.dDataFin', true),xLunaAnIni,xLunaAnFin);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest_getanlunafin</obj_name>
  <obj_hashval>dda0b5e32808af1b2e5b1599a9aee733</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest_getanlunafin()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --BogdanL 28.07.2020
  return current_setting('PKG_LIST_BASE_REALGEST.AnLunafin', true)::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest_getanlunaini</obj_name>
  <obj_hashval>f1ff96d40c3055239970c2789c8120e1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest_getanlunaini()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --BogdanL 28.07.2020
  return  current_setting('PKG_LIST_BASE_REALGEST.AnLunaIni', true)::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest_getccinactive</obj_name>
  <obj_hashval>6d8f6fa4564067c290f2c3d70c80b8f9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest_getccinactive()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --BogdanL 29.07.2020
  return current_setting('PKG_LIST_BASE_REALGEST.vCCInactive', true)::numeric = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest_getcuconturi</obj_name>
  <obj_hashval>a9c4aa9e191d8f4d552f8040805415d2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest_getcuconturi()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  -- BogdanL 29.07.2020
  return current_setting('PKG_LIST_BASE_REALGEST.CuConturi', true)::numeric = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest_getcudoc</obj_name>
  <obj_hashval>617dc54b2bc8264ef1ccb2a7c8ebf689</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest_getcudoc()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --BogdanL 29.07.2020
  return current_setting('PKG_LIST_BASE_REALGEST.vDoc', true)::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest_getdetccost</obj_name>
  <obj_hashval>6d7eb1a90ef75afbb8801fcd47fc7e61</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest_getdetccost()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --BogdanL 29.07.2020
  return current_setting('PKG_LIST_BASE_REALGEST.DetCCost', true)::numeric=1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest_getdetlunara</obj_name>
  <obj_hashval>b6bae6036a1307b7bdf8e3b5ec964a06</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest_getdetlunara()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --BogdanL 29.07.2020
  return current_setting('PKG_LIST_BASE_REALGEST.DetLunara', true)::numeric = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest_getextra</obj_name>
  <obj_hashval>af5db68d1f20fe10781e0a3f387e2f02</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest_getextra()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --BogdanL
  return current_setting('PKG_LIST_BASE_REALGEST.vExtra', true)::numeric = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest_getfaramiscari</obj_name>
  <obj_hashval>ee8dd953e77ffc1d7ff3549e0a3046dd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest_getfaramiscari()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --BogdanL 29.07.2020
  return  current_setting('PKG_LIST_BASE_REALGEST.FaraMiscari', true)::numeric = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest_getplan</obj_name>
  <obj_hashval>c7b5c1a2939172b1bf9b9a55b38c80bc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest_getplan()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --BogdanL 28.07.2020
  return  current_setting('PKG_LIST_BASE_REALGEST.p_Plan', true)::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest_getsubunit</obj_name>
  <obj_hashval>32b7b3a284e4ffa769b2dd1cb30f35fe</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest_getsubunit()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  --BogdanL 28.07.2020
  return  current_setting('PKG_LIST_BASE_REALGEST.Subunit', true)::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest_setjoinuri</obj_name>
  <obj_hashval>9c7b6473b498070b94eddb23579262f5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --BogdanL 28.07.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_REALGEST.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest_setparams</obj_name>
  <obj_hashval>60d59bee690f8ee20f5047f50d727b39</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest_setparams(vanlunaini numeric, vanlunafin numeric, vplan numeric, vfaramiscari numeric, vcuconturi numeric, vdetlunara numeric, vdetccost numeric, vpefirma numeric, pcodjob1 numeric, pallcc numeric, pccinactive numeric, pdoc numeric, pextra numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  --BogdanL 28.07.2020
  vDataS date;
  vDataF date;
begin
  perform set_config('PKG_LIST_BASE_REALGEST.p_plan'     ,vPlan::varchar       ,false);
  perform set_config('PKG_LIST_BASE_REALGEST.AnLunaIni'  ,vAnLunaIni::varchar  ,false);
  perform set_config('PKG_LIST_BASE_REALGEST.AnLunaFin'  ,vAnLunaFin::varchar  ,false);
  perform set_config('PKG_LIST_BASE_REALGEST.FaraMiscari',vFaraMiscari::varchar,false);
  perform set_config('PKG_LIST_BASE_REALGEST.CuConturi'  ,vCuConturi::varchar  ,false);
  perform set_config('PKG_LIST_BASE_REALGEST.DetCCost'   ,vDetCCost::varchar   ,false);
  perform set_config('PKG_LIST_BASE_REALGEST.DetLunara'  ,vDetLunara::varchar  ,false);
  perform set_config('PKG_LIST_BASE_REALGEST.Subunit'    ,CASE  WHEN  NOT (vPeFirma = 1)  THEN current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric
                                                                WHEN  pCodJob1 = 0 THEN 1
                                                                ELSE 0
                                                          END ::varchar,false);

  IF  pCodJob1 &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1, vDataS, vDataF, current_setting('PKG_LIST_BASE_REALGEST.AnLunaIni', true)::numeric, current_setting('PKG_LIST_BASE_REALGEST.AnLunaFin', true)::numeric);
  END IF;

  perform set_config('PKG_LIST_BASE_REALGEST.NiveleANod',(SELECT pkg_list_base_utils_NIVELE_ANALIZA.WME_RESULT FROM pkg_list_base_utils_NIVELE_ANALIZA(NULL,NULL))::varchar,false);
  perform set_config('PKG_LIST_BASE_REALGEST.vAllCC',pAllCC::varchar,false);
  IF  NOT (   vDetCCost = 1)  THEN
      perform set_config('PKG_LIST_BASE_REALGEST.vAllCC','1',false);
  END IF;
  perform set_config('PKG_LIST_BASE_REALGEST.vCCInactive',pCCInactive::varchar,false);
  perform set_config('PKG_LIST_BASE_REALGEST.vDoc'       ,pDoc::varchar       ,false);
  perform set_config('PKG_LIST_BASE_REALGEST.vExtra'     ,pExtra::varchar     ,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest2_baga_dinamic_cols</obj_name>
  <obj_hashval>a3a9849e833edca13b397d2c5ed24a7b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest2_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnLunaIni numeric := pkg_list_base_realgest_GetAnLunaIni();
  vAnLunaFin numeric := pkg_list_base_realgest_GetAnLunaFin();
  vNrLuni    numeric := vAnLunaFin - vAnLunaIni + 1;
BEGIN
  --Florin 20.02.2023 - fixat 57275
  --Florin 25.01.2023 - sinc. Oracle
  --BogdanL 30.07.2020
  delete from tmp_dinamic_cols;
  IF pkg_list_base_realgest_GetDetLunara() AND pkg_list_base_realgest_GetDetCCost() THEN
    if pkg_list_base_realgest_getallcc() then
      if pkg_list_base_realgest_getccinactive() then
        INSERT INTO tmp_dinamic_cols(
          fieldname,
          display,
          indexlocal)
          with recursive vRec(fieldname, LEVEL, display) as (
            SELECT 'D'||1 fieldname, 1 AS LEVEL, 'Val./'||To_Char(Trunc((1+1-2)/12),'fm0000')||'.'||To_Char(Mod(1+1-2,12)+1 ,'fm00') display
            UNION ALL
             SELECT 'D'||level fieldname, LEVEL+ 1 AS LEVEL, 'Val./'||To_Char(Trunc((vAnLunaIni+LEVEL-2)/12),'fm0000')||'.'||To_Char(Mod(vAnLunaIni+LEVEL-2,12)+1 ,'fm00') display
           FROM vrec v where v.LEVEL &lt; vNrLuni
          )
          SELECT c.fieldname||'_'||v.fieldname,
            c.display||'_'||v.display,
            row_number() over (order by c.fieldname||'_'||v.fieldname)
          FROM
          (
             SELECT CODCENTRU, 'C'||to_char(CODCENTRU) fieldname, DENUMIRE display
             FROM CENTRECOST
             WHERE CODCENTRU &gt; 0
             UNION ALL
             SELECT 0 CODCENTRU, 'C0' fieldname, 'nedefinit' display
             ORDER BY CODCENTRU
            ) c, vrec v;
      else
        INSERT INTO tmp_dinamic_cols(
          fieldname,
          display,
          indexlocal)
          with recursive vRec(fieldname, LEVEL, display) as (
            SELECT 'D'||1 fieldname, 1 AS LEVEL, 'Val./'||To_Char(Trunc((1+1-2)/12),'fm0000')||'.'||To_Char(Mod(1+1-2,12)+1 ,'fm00') display
            UNION ALL
             SELECT 'D'||level fieldname, LEVEL+ 1 AS LEVEL, 'Val./'||To_Char(Trunc((vAnLunaIni+LEVEL-2)/12),'fm0000')||'.'||To_Char(Mod(vAnLunaIni+LEVEL-2,12)+1 ,'fm00') display
           FROM vrec v where v.LEVEL &lt; vNrLuni
        )
        SELECT c.fieldname||'_'||v.fieldname,
          c.display||'_'||v.display,
          row_number() over (order by c.fieldname||'_'||v.fieldname)
        FROM
        (
           SELECT CODCENTRU, 'C'||to_char(CODCENTRU) fieldname, DENUMIRE display
           FROM CENTRECOST
           WHERE CODCENTRU &gt; 0
           UNION ALL
           SELECT 0 CODCENTRU, 'C0' fieldname, 'nedefinit' display
           ORDER BY CODCENTRU
          ) c, vrec v;
      END IF;
    ELSE
      if pkg_list_base_realgest_getccinactive() then
        INSERT INTO tmp_dinamic_cols(
          fieldname,
          display,
          indexlocal)
          with recursive vRec(fieldname, LEVEL, display) as (
            SELECT 'D'||1 fieldname, 1 AS LEVEL, 'Val./'||To_Char(Trunc((1+1-2)/12),'fm0000')||'.'||To_Char(Mod(1+1-2,12)+1 ,'fm00') display
            UNION ALL
             SELECT 'D'||level fieldname, LEVEL+ 1 AS LEVEL, 'Val./'||To_Char(Trunc((vAnLunaIni+LEVEL-2)/12),'fm0000')||'.'||To_Char(Mod(vAnLunaIni+LEVEL-2,12)+1 ,'fm00') display
           FROM vrec v where v.LEVEL &lt; vNrLuni
        )
        SELECT c.fieldname||'_'||v.fieldname,
          c.display||'_'||v.display,
          row_number() over (order by c.fieldname||'_'||v.fieldname)
        FROM
        (
           SELECT CODCENTRU, 'C'||to_char(CODCENTRU) fieldname, DENUMIRE display
           FROM CENTRECOST
           WHERE CODCENTRU &gt; 0
           UNION ALL
           SELECT 0 CODCENTRU, 'C0' fieldname, 'nedefinit' display
           ORDER BY CODCENTRU
          ) c, vrec v;
      ELSE
        INSERT INTO tmp_dinamic_cols(
          fieldname,
          display,
          indexlocal)
          with recursive vRec(fieldname, LEVEL, display) as (
            SELECT 'D'||1 fieldname, 1 AS LEVEL, 'Val./'||To_Char(Trunc((1+1-2)/12),'fm0000')||'.'||To_Char(Mod(1+1-2,12)+1 ,'fm00') display
            UNION ALL
             SELECT 'D'||level fieldname, LEVEL+ 1 AS LEVEL, 'Val./'||To_Char(Trunc((vAnLunaIni+LEVEL-2)/12),'fm0000')||'.'||To_Char(Mod(vAnLunaIni+LEVEL-2,12)+1 ,'fm00') display
           FROM vrec v where v.LEVEL &lt; vNrLuni
        )
        SELECT c.fieldname||'_'||v.fieldname,
          c.display||'_'||v.display,
          row_number() over (order by c.fieldname||'_'||v.fieldname)
        FROM
        (
           SELECT CODCENTRU, 'C'||to_char(CODCENTRU) fieldname, DENUMIRE display
           FROM CENTRECOST
           WHERE CODCENTRU &gt; 0
           UNION ALL
           SELECT 0 CODCENTRU, 'C0' fieldname, 'nedefinit' display
           ORDER BY CODCENTRU
          ) c, vrec v;
      END IF;
    END IF;
  ELSE
    IF pkg_list_base_realgest_GetDetLunara() THEN
      INSERT INTO tmp_dinamic_cols(
        fieldname,
        display,
        indexlocal)
        with recursive vRec(fieldname, LEVEL, display) as (
            SELECT 'D'||1 fieldname, 1 AS LEVEL, 'Val./'||To_Char(Trunc((1+1-2)/12),'fm0000')||'.'||To_Char(Mod(1+1-2,12)+1 ,'fm00') display
            UNION ALL
             SELECT 'D'||level fieldname, LEVEL+ 1 AS LEVEL, 'Val./'||To_Char(Trunc((vAnLunaIni+LEVEL-2)/12),'fm0000')||'.'||To_Char(Mod(vAnLunaIni+LEVEL-2,12)+1 ,'fm00') display
           FROM vrec v where v.LEVEL &lt; vNrLuni)
        SELECT 'D'||v.level,
        'Val./'||To_Char(Trunc((vAnLunaIni+v.LEVEL-2)/12),'fm0000')||'.'||To_Char(Mod(vAnLunaIni+v.LEVEL-2,12)+1 ,'fm00'),
        v.LEVEL FROM vRec v;
    ELSE
  IF (pkg_list_base_realgest_GetDetCCost()) THEN
    IF (pkg_list_base_realgest_getallcc()) THEN
      IF (pkg_list_base_realgest_getccinactive()) THEN
          INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal)
            SELECT 'C' || coalesce(row_number() over() :: varchar,''), Denumire, CodCentru
            FROM (
                  SELECT CODCENTRU, DENUMIRE
                  FROM CENTRECOST
                  WHERE CODCENTRU &gt; 0
                  ORDER BY   CODCENTRU ) A_PG
            UNION ALL
            SELECT 'C0', 'nedefinit' DENUMIRE, 0 CODCENTRU;
      ELSE
        INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal)
          SELECT 'C' || coalesce(row_number() over() :: varchar,''), Denumire, CodCentru
          FROM (
            SELECT CODCENTRU, DENUMIRE
            FROM CENTRECOST
            WHERE CODCENTRU &gt; 0 AND  COALESCE(INACTIV, 0) = 0
            ORDER BY  CODCENTRU ) B_PG
            UNION ALL
            SELECT 'C0', 'nedefinit' DENUMIRE, 0 CODCENTRU;
      END IF;
    ELSE
      IF (pkg_list_base_realgest_getccinactive()) THEN
        INSERT INTO tmp_dinamic_cols (FieldName, Display, IndexLocal)
        SELECT 'C' || coalesce(row_number() over() :: varchar,''), Denumire, CodCentru
        FROM (SELECT CODCENTRU, DENUMIRE
              FROM CENTRECOST
              WHERE CODCENTRU IN (SELECT VALOARE::NUMERIC FROM TMP_MANEVRA_LISTE WHERE Upper(FILTRU) = 'CODCENTRU') AND  CODCENTRU &gt; 0
              ORDER BY   CODCENTRU
             ) C_PG;
      ELSE
        INSERT INTO tmp_dinamic_cols ( FieldName, Display, IndexLocal )
          SELECT 'C' || coalesce(row_number() over() :: varchar,''), Denumire, CodCentru
          FROM (SELECT CODCENTRU, DENUMIRE
                FROM CENTRECOST
                WHERE CODCENTRU IN (SELECT VALOARE::NUMERIC FROM TMP_MANEVRA_LISTE WHERE Upper(FILTRU) = 'CODCENTRU' ) AND  CODCENTRU &gt; 0 AND  COALESCE(INACTIV, 0) = 0
                ORDER BY CODCENTRU
               ) D_PG;
          END IF;
        END IF;
      END IF;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest2_baga_dinamic_cols_lun</obj_name>
  <obj_hashval>68268b02117f27b40c1c5fb517662ddc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest2_baga_dinamic_cols_lun()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnLunaIni numeric := pkg_list_base_realgest_GetAnLunaIni();
  vAnLunaFin numeric := pkg_list_base_realgest_GetAnLunaFin();
  vNrLuni    numeric := vAnLunaFin - vAnLunaIni + 1;
begin
  --BogdanL 30.07.2020
  IF (pkg_list_base_realgest_GetDetLunara()) THEN
    INSERT INTO tmp_dinamic_cols (fieldname, display, indexlocal)
      with recursive vRec as (
            select  1 as level
            union all
              select  v.level+1
            from vRec v where level &lt; vNrLuni
        )
      select 'D' || level::varchar,
      'Val./' || coalesce(To_Char(Trunc((  vAnLunaIni + LEVEL - 2)  / 12), 'fm0000'),'')
          || '.' || coalesce(To_Char(Mod(vAnLunaIni + LEVEL - 2, 12) + 1, 'fm00'),''),
          level
      from vRec;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest2_swith</obj_name>
  <obj_hashval>dec560fd71626165b70e423f37501f36</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest2_swith(pcondclasa character varying, pdinwith character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar;
BEGIN
  --Florin 04.11.2024 - sinc. Oracle
  --BogdanL 29.07.2020
    sResult := '  WITH Sintetice as (
        SELECT c.codsint, c.codcont, c.codconts, s.codsints, c.clasa, c.tipcont, c.codcentru
        FROM (
          with recursive
             clvl1 as (
              select distinct
                  c.codcont,
                  c.clasa,
                  c.tipcont,
                  coalesce(c.codparinte, 0) codparinte,
                  last_value(c1.ContSecundar) over (
                      partition by c1.codcont
                      order by c1.AnStart, c1.LunaStart range between unbounded preceding and unbounded following
                  ) CodContS,
                  first_value (c1.AnStart) over (
                  partition by c1.codcont
                  order by
                    c1.AnStart, c1.LunaStart range between unbounded preceding and unbounded following
                  ) AnStart,
                  first_value(c1.LunaStart) over (
                  partition by c1.codcont
                  order by
                    c1.AnStart, c1.LunaStart range between unbounded preceding and unbounded following
                  ) LunaStart,
                  last_value(c1.CodCentru) over (
                  partition by c1.codcont
                  order by
                    c1.AnStart, c1.LunaStart range between unbounded preceding and unbounded following
                  ) CodCentru
              from
                ncont c
                inner join ncont1 c1 on  c1.codcont = c.codcont
              where c.clasa ' || coalesce(pCondClasa,'') || '
                AND AnStart*12+LunaStart &lt;= ' || coalesce((pkg_list_base_realgest_GetAnLunaFin())::varchar,'') || '
            ),
            c2lvlRec as (
               SELECT codcont as CodSint, CodCont, CodContS, Clasa, TipCont, codcentru, codparinte
               from clvl1 c1
               where c1.codparinte = 0 AND Coalesce(c1.codcont,0) &lt;&gt; 0
               union all
               select cr.CodSint,ci.CodCont, ci.CodContS, ci.Clasa, ci.TipCont, ci.codcentru, ci.codparinte
               from clvl1 ci
                join c2lvlRec cr on cr.codcont=ci.codparinte
             )
             select c2.CodSint, c2.CodCont, c2.CodContS, c2.Clasa, c2.TipCont, c2.codcentru,
                case when not exists (select * from c2lvlRec c2r where c2r.codparinte = c2.codcont) then 1 else 0 end as farafii from c2lvlRec c2
          ) c
          LEFT JOIN (
            with recursive nctsRec as (
            select codconts as codSints, codconts
            from nconts ncsP
            where coalesce(ncsP.codparinte, 0) = 0 and coalesce(ncsP.codconts, 0) &lt;&gt; 0
            union all
            select nR.codSints, ncsC.codconts
            from nconts ncsC
            join nctsRec nR on nR.codconts = ncsC.codparinte
            where coalesce(ncsC.codconts, 0) &lt;&gt; 0
          )
            select codSints, codconts from nctsRec   ) s ON s.CodContS = c.CodContS
        WHERE c.codsint &lt;&gt; c.codcont OR c.farafii = 1),
      x as (
        SELECT codcont, codsint, codconts, codsints, sum(valoare) valoare, gest, den_subunit, MAX(Misc) Misc'|| coalesce(pDinWith,'') || '
        FROM (';
  return  sResult;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_receptii_setjoinuri</obj_name>
  <obj_hashval>e85904d369ce0a61f2489acbb8b8e509</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_receptii_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 11.08.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_RECEPTII.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_reclamatii_processlist</obj_name>
  <obj_hashval>e0307c3c9f885d00df2dd2bece46e32a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_reclamatii_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;
  vDataStart  varchar;
  vDataStop   varchar;
BEGIN
  --Florin 11.08.2022 - reclamatii la suplimentare
  --Bogdan 15.09.2020
  gSuplCols := 'npart PA, Reclamatii R';

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs (gSuplCols , 'NPARTDET', 'PD', 'PD.CODPART = PA.CODPART',NULL);
  CALL pkg_list_struct_getsuplcols( aLISTID, aLISTVER, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config ('PKG_LIST_BASE_RECLAMATII.gSuplCols',gSuplCols,false);

  sInsert := 'INSERT INTO '|| tmpName|| '
          (NAV_CodDoc,
          NAV_TIPDOC,
          NRDOC,
          SERIADOC,
          DATADOC,
          CARNETDOC,
          Den_subunit,
          Nume,
          Prenume,
          Motiv,
          Reclamatie,
          Rezolvat,
          DataRez'
          || coalesce (gUserFields ,'')
          || ')
      SELECT R.CodDOC,
        R.TipDOC,
        R.NRDOC,
        R.SERIADOC,
        R.DATADOC,
        DC.Denumire CARNETDOC,
        S.Den_subunit,
        P.Nume,
        P.Prenume,
        R.Motiv,
        R.Reclamatie,
        (case R.Rezolvat
            when 0 then ''Nu''
            when 1 then ''Da'' end) Rezolvat,
        R.DataRez'
          || coalesce (gUserAlias ,'')|| '
      FROM RECLAMATII        R
        LEFT JOIN NPERS      P  on P.CodPERS    = R.Codutilizator
        LEFT JOIN NSUBUNIT   S  ON S.CodSubunit = R.Codsubunit
        LEFT JOIN doccarnete DC on DC.CodCarnet = R.CarnetDoc
        LEFT JOIN npart      PA on PA.CodPart   = R.CodPart '
          || coalesce (gSuplJoins ,'');
  PERFORM LIST_EXECUTE_IMMEDIATE (sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_reganalitic_setjoinuri</obj_name>
  <obj_hashval>5eccaf0274b00fa042fa50300cdd17e7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_reganalitic_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 09.11.2023
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('pkg_list_base_reganalitic.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regcasabanca_setjoinuri</obj_name>
  <obj_hashval>b4f6367f205386df9056d1ce2a2706f2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regcasabanca_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 30.07.2020

  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_REGCASABANCA.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regcontabil_processlist</obj_name>
  <obj_hashval>c5b064c8b89ccfae81d9dc2a723c91fd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regcontabil_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sINSERT         varchar := '';
  gSuplCols        VARCHAR := 'NCONT NC, NCONTS NCS, CENTRECOST C';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  sAnLunaLucru    varchar := coalesce(getAnLunaLucru()::varchar,'0');
BEGIN
  --Adina 10.05.2021 - alstart,alstop, sAnLunaLucru
  --Adina 10 septembrie 2020
  CALL PRC_AL_CHECK('ncont1', 0);

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

  sInsert :=
  'INSERT INTO ' || TMPNAME || ' (SIMBOL,DEN_GEST,POSTING_KEY,VALOARE' || gUserFields || ')
  SELECT NCS.SIMBOL, C.SIMBOL CENTRUCOST, POSTING_KEY,VALOARE ' || gUserAlias || '
  FROM (
    SELECT NC1.CODCONT, coalesce(JC.CODCENTRU,0) CODCENTRU, coalesce(NC1.CONTSECUNDAR,0) CONTSECUNDAR, CASE WHEN SUM(JC.VALOARE) &gt; 0 THEN ''50'' ELSE ''40'' END POSTING_KEY, ABS(SUM(JC.VALOARE)) VALOARE
    FROM JURNAL JC
      INNER JOIN NCONT1 NC1 ON NC1.CODCONT = JC.CONTC AND '||sAnLunaLucru||' BETWEEN NC1.ALSTART and NC1.ALSTOP
    WHERE JC.AN * 12 + JC.LUNA = ' || sAnLunaLucru || ' ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('JC',NULL,NULL,NULL),'') || '
    GROUP BY NC1.CODCONT, coalesce(JC.CODCENTRU,0), NC1.CONTSECUNDAR
    UNION ALL
    SELECT NC1.CODCONT, coalesce(JD.CODCENTRU,0) CODCENTRU, coalesce(NC1.CONTSECUNDAR,0) CONTSECUNDAR, CASE WHEN SUM(JD.VALOARE) &gt; 0 THEN ''40'' ELSE ''50'' END POSTING_KEY, ABS(SUM(JD.VALOARE)) VALOARE
    FROM JURNAL JD
      INNER JOIN NCONT1 NC1 ON NC1.CODCONT = JD.CONTD AND '||sAnLunaLucru||' BETWEEN NC1.ALSTART and NC1.ALSTOP
    WHERE JD.AN * 12 + JD.LUNA = ' || sAnLunaLucru || ' ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('JD',NULL,NULL,NULL),'') || '
    GROUP BY NC1.CODCONT, coalesce(JD.CODCENTRU,0), NC1.CONTSECUNDAR
  ) J
    INNER JOIN NCONT      NC  ON NC.CODCONT   = J.CODCONT
    INNER JOIN NCONTS     NCS ON NCS.CODCONTS = J.CONTSECUNDAR
    LEFT  JOIN CENTRECOST C   ON C.CODCENTRU  = J.CODCENTRU' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regevfisc_processlist</obj_name>
  <obj_hashval>dc9840b58fb99b5cf7bb2f8776facf68</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regevfisc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols       varchar := 'ncont c';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Florin 05.11.2024 - sinc. Oracle
  --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_REGEVFISC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    RULAJ,
    VENCHELT,
    SUMA,
    SIMBOL,
    DEN_CONT,
    TIPCONT,
    TIP' || gUserFields || ')
  SELECT
          ch.RULAJ,
          ch.cheltuieli VENCHELT,
          ch.SUMA,
          c.SIMBOL,
          c.DEN_CONT,
          (case C.TIPCONT when 0 then  ''ACTIV'' when 1 then ''PASIV'' when 2 then ''BIFUNC'' end) TIPCONT,
          ''Cheltuieli'' TIP ' || gUserAlias || '
  FROM dprofitc ch
       inner join ncont c on ch.codcont = c.codcont ' || gSuplJoins || '
  WHERE ch.coddprofit = ' || coalesce(current_setting('PKG_LIST_BASE_REGEVFISC.vCodDProfit', true),'') || '
  union all
  SELECT
          ch.RULAJ,
          ch.venituri VENCHELT,
          ch.SUMA,
          c.SIMBOL,
          c.DEN_CONT,
          (case C.TIPCONT when 0 then  ''ACTIV'' when 1 then ''PASIV'' when 2 then ''BIFUNC'' end) TIPCONT,
          ''Venituri'' TIP ' || gUserAlias || '
  FROM dprofitv ch
       inner join ncont c on ch.codcont = c.codcont
    ' || gSuplJoins || '
  WHERE ch.coddprofit = ' || coalesce(current_setting('PKG_LIST_BASE_REGEVFISC.vCodDProfit', true),'');

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regevfisc_setjoinuri</obj_name>
  <obj_hashval>92e7cc7fef3c64d57555247a64b99b51</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regevfisc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01 octombrie 2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_REGEVFISC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regevfisc_setparams</obj_name>
  <obj_hashval>ddf5b05371a9415d4098f8b19dccc8a4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regevfisc_setparams(pcoddprofit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01 octombrie 2020
  perform set_config('PKG_LIST_BASE_REGEVFISC.vCodDProfit',(pCodDProfit)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_reginout_processlist</obj_name>
  <obj_hashval>fe042e76d1cb44ee02ae6cb03ac792c9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_reginout_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sSelect1    varchar;
  sSelect2    varchar;
  vZiuaIni    date := fnc_current_setting_date('PKG_LIST_ALEGPERIOADA.gDataS');
  vZiuaFin    date := fnc_current_setting_date('PKG_LIST_ALEGPERIOADA.gDataF');
  sPer        varchar := 'Null';
  gSuplCols   varchar := 'NPART NP, NAGENDA NA, NLOCALIT NL, NJUDET NJ, NPARTCODFISC FISC';
  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_REGINOUT.gSuplCols',gSuplCols,false);

  IF vZiuaIni = vZiuaFin THEN
    sPer := '= TO_DATE(''' || coalesce(To_Char(vZiuaIni, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
  ELSE
    sPer := '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'')';
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(
        NAV_CodDoc, NAV_TipDoc, TIPINTR, TIPIES, TIPDOC,
        PREFIXDOC, NRDOC, DATADOC, DATACREARE,
        PARTENER, CODFISCAL,
        LOCALITATE, JUDET,
        ADRESA,
        OBS, OPERATOR ' || gUserFields || ')';
  sSelect1 := '
      SELECT
        I.CODIES, I.TIPDOC, ''NU'' Intrari, ''DA'' Iesiri, pkg_list_base_utils_decode_tipdoc_scurt(i.tipdoc),
        I.PREFIXDOC, I.NRDOC, I.DATADOC, I.DATACREARE,
        NP.DEN_PART, FISC.CODFISCAL,
        NL.DEN_LOCALIT, NJ.DEN_JUDET,
        (select getadresa.WME_RESULT FROM getadresa(NULL, na.sector, na.strada, na.nr1, na.nr2, na.bloc, na.scara, na.etaj, na.apart, na.codpostal)),
        I.OBS, UT.NUME ' || gUserAlias || '
      FROM IESIRI I
        LEFT JOIN NPART          NP   ON np.codpart         = i.partener
        LEFT JOIN NAGENDA        NA   ON NA.codagenda       = I.codlocatie
        LEFT JOIN NLOCALIT       NL   ON NL.codlocalit      = NA.codlocalit
        LEFT JOIN NJUDET         NJ   ON NJ.codjudet        = NL.codjudet
        LEFT JOIN NPARTCODFISC   FISC ON fisc.cod_codfiscal = i.codfiscal
        LEFT JOIN TMP_UTILIZATOR UT   ON ut.codutilizator   = i.userid' || gSuplJoins || '
      WHERE COALESCE(I.OPERAT,0) = 1 AND COALESCE(I.ANULAT,0) = 0
        AND I.DATADOC ' || coalesce(sPer,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'');
  sSelect2 := '
      SELECT
        I.CODINTR, I.TIPDOC, ''DA'' Intrari, ''NU'' Iesiri, pkg_list_base_utils_decode_tipdoc_scurt(i.tipdoc),
        I.PREFIXDOC, I.NRDOC, I.DATADOC, I.DATACREARE,
        NP.DEN_PART, FISC.CODFISCAL,
        NL.DEN_LOCALIT, NJ.DEN_JUDET,
        (select getadresa.WME_RESULT FROM getadresa(NULL, na.sector, na.strada, na.nr1, na.nr2, na.bloc, na.scara, na.etaj, na.apart, na.codpostal)),
        I.OBS, UT.NUME ' || gUserAlias || '
      FROM INTRARI I
        LEFT JOIN NPART          NP   ON np.codpart         = i.partener
        LEFT JOIN NAGENDA        NA   ON NA.codagenda       = I.codlocatie
        LEFT JOIN NLOCALIT       NL   ON NL.codlocalit      = NA.codlocalit
        LEFT JOIN NJUDET         NJ   ON NJ.codjudet        = NL.codjudet
        LEFT JOIN NPARTCODFISC   FISC ON fisc.cod_codfiscal = i.codfiscal
        LEFT JOIN TMP_UTILIZATOR UT   ON ut.codutilizator   = i.userid' || gSuplJoins || '
      WHERE COALESCE(I.OPERAT,0) = 1 AND COALESCE(I.ANULAT,0) = 0
        AND I.DATADOC ' || coalesce(sPer,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'');
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect1,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect2,''), aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_reginout_setjoinuri</obj_name>
  <obj_hashval>c06f57cafabeb7e6baa9f477326eebcd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_reginout_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 10.09.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_REGINOUT.gSuplCols', TRUE));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regjurnal_getgnullalias</obj_name>
  <obj_hashval>1a5ed22b4f9454bf651a8603703ed5cd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_getgnullalias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_REGJURNAL.gNullAlias'));
  RETURN ;
  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_regjurnal_getgsuplcols</obj_name>
  <obj_hashval>3da440258f2772d976e1a42d811d51c8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_getgsuplcols(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_REGJURNAL.gSuplCols'));
  RETURN ;
  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_regjurnal_getgsupljoins</obj_name>
  <obj_hashval>91136ddd9d279bb9839bc3220228f46d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_getgsupljoins(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_REGJURNAL.gSuplJoins'));
  RETURN ;
  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_regjurnal_getguseralias</obj_name>
  <obj_hashval>4d7cc174f25872568ef5f7e5c701a10d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_getguseralias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_REGJURNAL.gUserAlias'));
  RETURN ;
  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_regjurnal_getguserfields</obj_name>
  <obj_hashval>761ac71896b0770116e920af7607ec55</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_getguserfields(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_REGJURNAL.gUserFields'));
  RETURN ;
  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_regjurnal_getp_lunafin</obj_name>
  <obj_hashval>7ecad1771177138bbb99e20e1029af88</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_getp_lunafin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_LIST_BASE_REGJURNAL.p_LunaFin')),'999999999999999999');
  RETURN ;
  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_regjurnal_getp_lunaini</obj_name>
  <obj_hashval>4d04550bb71b4e03a20f945a42472a07</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_getp_lunaini(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_LIST_BASE_REGJURNAL.p_LunaIni')),'999999999999999999');
  RETURN ;
  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_regjurnal_getp_plan</obj_name>
  <obj_hashval>3b0772de1a1c96bd090aa5f668d7f1a8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_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_REGJURNAL.p_plan')),'999999999999999999');
  RETURN ;
  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_regjurnal_getp_subcurenta</obj_name>
  <obj_hashval>11286fc35c1ed9794a6d2030c511f693</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_getp_subcurenta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_LIST_BASE_REGJURNAL.p_SubCurenta')),'999999999999999999');
  RETURN ;
  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_regjurnal_gnullalias</obj_name>
  <obj_hashval>dbd3463245fdfe978f7fe89f4eb0be5b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_gnullalias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_REGJURNAL.gNullAlias'));
  RETURN ;
  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_regjurnal_gsuplcols</obj_name>
  <obj_hashval>b2ef9caafc2510c73c6f51ac2b34e5ce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_gsuplcols(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_REGJURNAL.gSuplCols'));
  RETURN ;
  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_regjurnal_gsupljoins</obj_name>
  <obj_hashval>4abdf384e0f13bfb72d888dcb4b38c30</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_gsupljoins(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_REGJURNAL.gSuplJoins'));
  RETURN ;
  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_regjurnal_guserfields</obj_name>
  <obj_hashval>f333516d7459d7fc997ec619187cfcb6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_guserfields(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_REGJURNAL.gUserFields'));
  RETURN ;
  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_regjurnal_lunaini</obj_name>
  <obj_hashval>f3f4c32906431bd2a5ee2c992e9843f8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_lunaini(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  current_setting('PKG_LIST_BASE_REGJURNAL.p_LunaIni')::numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regjurnal_p_lunafin</obj_name>
  <obj_hashval>adf236b430f0f0642ce3c64a84c2c1da</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_p_lunafin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  --Florin 15.11.2023 - fixat 60060
  WME_Result := (current_setting('PKG_LIST_BASE_REGJURNAL.p_LunaFin'))::NUMERIC;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regjurnal_p_lunaini</obj_name>
  <obj_hashval>607ec504616db2b6b982d089cf6625b5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_p_lunaini(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  --Florin 15.11.2023 - fixat 60060
  WME_Result := (current_setting('PKG_LIST_BASE_REGJURNAL.p_LunaIni'))::NUMERIC;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regjurnal_p_plan</obj_name>
  <obj_hashval>8f5a8d68627a61c1415c81bc6050f9f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_p_plan(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  --Florin 15.11.2023 - fixat 60060
  WME_Result := (current_setting('PKG_LIST_BASE_REGJURNAL.p_plan'))::NUMERIC;
  RETURN ;
  EXCEPTION WHEN undefined_object THEN
WME_Result := NULL;
RETURN ;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regjurnal_p_subcurenta</obj_name>
  <obj_hashval>538c0effc4da670283d79e7fc642b96c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_p_subcurenta(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_LIST_BASE_REGJURNAL.p_SubCurenta')),'999999999999999999');
  RETURN ;
  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_regjurnal_setguseralias</obj_name>
  <obj_hashval>2394c3de235c835e79ab5e66ba3fe73a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_setguseralias(aguseralias character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_REGJURNAL.gUserAlias',agUserAlias,false);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regjurnal_setjoinuri</obj_name>
  <obj_hashval>3cc564af1e1934b7b2855071e530fdda</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
PERFORM Pkg_List_Struct_SetTableSpec( (current_setting('PKG_LIST_BASE_REGJURNAL.gSuplCols')));
PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regjurnal_setp_lunafin</obj_name>
  <obj_hashval>ad66f3bf3150d8750dfa652e5ace25b9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_setp_lunafin(ap_lunafin numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_REGJURNAL.p_LunaFin',to_char(ap_LunaFin,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regjurnal_setp_lunaini</obj_name>
  <obj_hashval>20010fdf03f9ce4d916e2e34455a5992</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_setp_lunaini(ap_lunaini numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_REGJURNAL.p_LunaIni',to_char(ap_LunaIni,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regjurnal_setp_plan</obj_name>
  <obj_hashval>c350e82d3be3f188f4eea51b7c63336d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_setp_plan(ap_plan numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_REGJURNAL.p_plan',to_char(ap_plan,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regjurnal_setp_subcurenta</obj_name>
  <obj_hashval>9607d8dae1fc7f05ab4585eab9bca784</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_setp_subcurenta(ap_subcurenta numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_REGJURNAL.p_SubCurenta',to_char(ap_SubCurenta,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regjurnal_setparams</obj_name>
  <obj_hashval>1ef4d81d7333b11bca681f7ba363049c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_setparams(vplan numeric, vlunaini numeric, vlunafin numeric, vsubcurenta numeric, v_index numeric, v_codjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDataS date;
  vDataF date;
begin
  perform set_config('PKG_LIST_BASE_REGJURNAL.p_plan'      ,vPlan::varchar      ,false);
  perform set_config('PKG_LIST_BASE_REGJURNAL.p_LunaIni'   ,vLunaIni::varchar   ,false);
  perform set_config('PKG_LIST_BASE_REGJURNAL.p_LunaFin'   ,vLunaFin::varchar   ,false);
  perform set_config('PKG_LIST_BASE_REGJURNAL.p_SubCurenta',vSubCurenta::varchar,false);
  perform set_config('PKG_LIST_BASE_REGJURNAL.p_Index'     ,v_Index::varchar    ,false);

  IF  v_CodJob1 &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(v_CodJob1, vDataS, vDataF, current_setting('PKG_LIST_BASE_REGJURNAL.p_LunaIni', true)::numeric, current_setting('PKG_LIST_BASE_REGJURNAL.p_LunaFin', true)::numeric);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regmf_processlist</obj_name>
  <obj_hashval>930f53c15d51450741d9069b98862cd6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regmf_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';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 15.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_REGMF.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    Articol,
    NrInventar,
    Gestiune,
    CentruCost,
    DataPunere,
    ValIn,
    DurataN,
    RestDurata,
    DurataParcursa,
    AmoLunara,
    AmoCumulIntr,
    ValReev,
    RestDurataLaReev,
    AmoLunaraReev,
    AmoCumulReev,
    ValMF,
    ValAmoLunara,
    AmoCumul,
    DataOperatie' || gUserFields || ')';

  sSelect :=
  'SELECT
    OBJ.DENUMIRE Articol,
    MF.NrInventar,
    G.DEN_GEST Gestiune,
    CC.DENUMIRE CentruCost,
    DataPunere,
    ValIn,
    DurataN,
    RestDurata,
    DurataParcursa,
    AmoLunara,
    AmoCumulIntr,
    ValReev,
    RestDurataLaReev,
    AmoLunaraReev,
    AmoCumulReev,
    ValMF,
    ValAmoLunara,
    AmoCumul,
    DataOperatie ' || gUserAlias || '
  FROM MIFIX MF
       INNER JOIN MIFIX1 MF1     ON MF1.CODMIFIX   = MF.CODMIFIX
       INNER JOIN NIRSTOC NS     ON NS.CODNIRSTOC  = MF1.CODNIRSTOC
       INNER JOIN NIR            ON NIR.CODNIR     = NS.CODNIR
       INNER JOIN NGEST G        ON G.CODGEST      = NIR.GEST
       INNER JOIN NARTOBJ OBJ    ON OBJ.CODOBIECT  = NS.CODOBIECT
       INNER JOIN NART ART       ON ART.CODARTICOL = OBJ.CODARTICOL
       INNER JOIN CENTRECONST CC ON MF1.CODCENTRU  = CC.CODCENTRU
    ' || gSuplJoins || '
  WHERE MF1.ANSTART*12+MF1.LUNASTART = (SELECT MAX(ANSTART*12+LUNASTART FROM MIFIX1 WHERE CODMIFIX = MF.CODMIFIX)';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regmf_setjoinuri</obj_name>
  <obj_hashval>a36625a09786ebcbfe114dab70c497be</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regmf_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_REGMF.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regreev_processlist</obj_name>
  <obj_hashval>6fff26cb59a3cfe1b295f91d023bf250</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regreev_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';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 07.04.2021 - alstart,alstop
  --Adina 15.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_REGREEV.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    DataReev,
    Articol,
    Cont,
    NrInventar,
    ValNetaConta,
    Tip,
    ValReev,
    RezReev,
    ReevAnte,
    ValDinRez,
    Jurnal,
    ValChelt,
    JurnalChel,
    ValVenit,
    JurnalVenit ' || gUserFields || ')';

  sSelect := '
  SELECT
    F.DATAOPERATIE DataReev,
    OBJ.DENUMIRE Articol,
    C.SIMBOL Cont,
    MFIX.NrInventar,
    0 ValNetaConta,
    CASE
      WHEN F.CODOPERATIE = 6 THEN ''Reevaluare - valoare MF''
      WHEN F.CODOPERATIE = 7 THEN ''Reevaluare - amortizare prec''
    END Tip,
    0 ValReev,
    0 RezReev,
    0 ReevAnte,
    0 ValDinRez,
    '''' Jurnal,
    0 ValChelt,
    '''' JurnalChel,
    0 ValVenit,
    '''' JurnalVenit' || gUserAlias || '
  FROM FISAMF F
       INNER JOIN MIFIX   MFIX ON MFIX.CODMIFIX  = F.CODMIFIX
       INNER JOIN TRANSF1 T1   ON F.CODDOC1      = T1.CODTRANSF1
       INNER JOIN TRANSF  T    ON T.CODTRANSF    = T1.CODTRANSF  AND F.TIPDOC = T.TIPDOC
       INNER JOIN 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 NS.CODIOART    = IOA1.CODIOART AND (T.AN*12+T.LUNA) BETWEEN IOA1.ALStart and IOA1.ALStop
       INNER JOIN NARTOBJ OBJ  ON OBJ.CODOBIECT  = NS.CODOBIECT
       INNER JOIN NART    ART  ON OBJ.CODARTICOL = ART.CODARTICOL
       INNER JOIN NCONT   C    ON C.CODCONT      = IOA1.CONT
       ' || gSuplJoins || '
  WHERE F.CODOPERATIE in (6,7)
        ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('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_regulariztrez_processlist</obj_name>
  <obj_hashval>3679754365312e529be73e1da352c1ae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regulariztrez_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  An          numeric;
  Luna        numeric;
  AnPrec      numeric;
  LunaPrec    numeric;
  gSuplCols   varchar :=  'npart p, nbank b, nmonede m, nbankcont bc';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Adina 02.03.2021 - sinc.Oracle din 01.03.2021
  --Florin 27.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_REGULARIZTREZ.gSuplCols', gSuplCols, false);

  Luna := mod(current_setting('PKG_LIST_SELECTLUNAAN.vLunaStart', true)::numeric, 12);
  IF Luna = 0 THEN
    Luna := 12;
  END IF;

  An := (current_setting('PKG_LIST_SELECTLUNAAN.vLunaStart', true)::numeric - Luna)  / 12;
  WHILE An * 12 + Luna &lt;= (current_setting('PKG_LIST_SELECTLUNAAN.vLunaStop', true)::numeric) LOOP
    sInsert := 'INSERT INTO ' || tmpName || '(Nr, Data_REG, Moneda, Curs, Banca, DenCont, NrCont, SoldV, SoldL, SoldReg, Dif, CursVechi, Sub, Gest, An, Luna'
    || gUserFields || ')
    SELECT
      r.NrDoc, r.dataDoc, m.Simbol, r.Curs, b.Denumire, bc.Den_Cont, bc.NrCont,
      t1.SoldValuta, t1.SoldLei, t1.SoldValuta * r.Curs, t1.SoldValuta * r.Curs - t1.SoldLei,
      CASE WHEN coalesce(t1.SoldValuta,0) = 0 THEN 0 ELSE t1.SoldLei / t1.SoldValuta END,
      s.den_subunit, g.den_gest, r.an, r.luna' || gUserAlias || '
    FROM REG R
      INNER JOIN nmonede            m  ON m.codmoneda    = r.codmoneda
      INNER JOIN nbankcont          bc ON bc.CodMoneda   = R.CodMoneda and coalesce(bc.farareg,0) = 0
      INNER JOIN nbank              b  ON b.CodBank      = bc.CodBank
      INNER JOIN v_solduribanciluna t1 ON t1.CodBankCont = bc.CodBankCont
      LEFT JOIN nsubunit            s  ON s.codsubunit   = bc.subunitatea
      LEFT JOIN jurnal1             j1 ON j1.tipdoc      = r.tipreg    AND j1.coddoc = r.codreg AND j1.codbazad = bc.CodBankCont
      LEFT JOIN ngest               g  ON g.codgest      = j1.gest' || gSuplJoins || '
    WHERE R.TipReg = 45
      AND r.an = ' || AN || ' AND r.luna = ' || Luna || '
      AND T1.SoldValuta * R.Curs - T1.SoldLei &lt;&gt; 0 ';
    PERFORM PKG_GLOBALS_SetLunaTEMP(An, Luna);
    select  NEWAN, newLuna from PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA(An, Luna, AnPrec, AnPrec) into AnPrec, LunaPrec;
    PERFORM PKG_GLOBALS_SETLUNAPRECEDENTA(AnPrec, LunaPrec);
--    insert into x(view_name, test) values ('regtrez', sinsert);
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

    IF Luna = 12 THEN
      An   := An + 1;
      Luna := 1;
    ELSE
      Luna := Luna + 1;
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_restlistgest_processlist</obj_name>
  <obj_hashval>f147db76c369237ca3908bf174d7038c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_restlistgest_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  S               varchar := '';
  gSuplCols        VARCHAR := 'RESTCMD1 R1, NARTOBJ O, NART A, NUM1 U1';
  gUserFields      VARCHAR := COALESCE(NULLIF(current_setting('PKG_LIST_BASE_RESTLISTGEST.gUserFields', true),''),'');
  gUserAlias       VARCHAR := COALESCE(NULLIF(current_setting('PKG_LIST_BASE_RESTLISTGEST.gUserAlias' , true),''),'');
  gNullAlias       VARCHAR := COALESCE(NULLIF(current_setting('PKG_LIST_BASE_RESTLISTGEST.gNullAlias' , true),''),'');
  gSuplJoins       VARCHAR := COALESCE(NULLIF(current_setting('PKG_LIST_BASE_RESTLISTGEST.gSuplJoins' , true),''),'');
BEGIN
  --Bogdan 27.06.2023 - corectie sinc
    --Florin 26.05.2023 - sinc. Oracle
  --Adina 15.06.2021 - sinc.Oracle din 14.06.2021
  --Adina 15.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');
  PERFORM set_config('PKG_LIST_BASE_RESTLISTGEST.gSuplCols'  ,gSuplCols  ,false);
  PERFORM set_config('PKG_LIST_BASE_RESTLISTGEST.gUserFields',gUserFields,false);
  PERFORM set_config('PKG_LIST_BASE_RESTLISTGEST.gUserAlias' ,gUserAlias ,false);
  PERFORM set_config('PKG_LIST_BASE_RESTLISTGEST.gNullAlias' ,gNullAlias ,false);
  PERFORM set_config('PKG_LIST_BASE_RESTLISTGEST.gSuplJoins' ,gSuplJoins ,false);

  S := 'INSERT INTO ' || TMPNAME || '(DENUMIRE, DENUM, CANT, OBS, ORDINE ' || gUserFields||') ' || CHR(13) ||
  ' SELECT '           || CHR(13) ||
  '   O.DENUMIRE, '   || CHR(13) ||
  '   U1.DEN_UM1, '   || CHR(13) ||
  '   R1.CANT, '       || CHR(13) ||
  '   R1.OBS, '         || CHR(13) ||
  '   R1.ORDINE '    ||  CHR(13) ||gUserAlias||
  ' FROM '             || CHR(13) ||
  '   RESTCMD1 R1                                   ' || CHR(13) ||
  '   JOIN  NARTOBJ O ON O.CODOBIECT = R1.CODOBIECT ' || CHR(13) ||
  '   JOIN NART A ON A.CODARTICOL = O.CODARTICOL    ' || CHR(13) ||
  '   JOIN NUM1 U1 ON U1.CODUM = A.UM               '  || CHR(13) || gSuplJoins ||
  ' WHERE '              || CHR(13) ||
  '   R1.CODRESTCMD = '  || coalesce(current_setting('PKG_LIST_BASE_RESTLISTGEST.CODRESTCMD', true),'') || CHR(13) ||
  '   AND R1.CODGEST = ' || coalesce(current_setting('PKG_LIST_BASE_RESTLISTGEST.CODGEST', true),'')    || CHR(13) ||
  '   AND coalesce(R1.LISTAREGEST, 0) = 0 '    || CHR(13) ||
  '   AND O.CODOBIECT = R1.CODOBIECT '        || CHR(13) ||
  '   AND A.CODARTICOL = O.CODARTICOL '       || CHR(13) ||
  '   AND U1.CODUM = A.UM '                   || CHR(13) ||
  '   AND U1.SECUNDARA = 0';
  PERFORM LIST_EXECUTE_IMMEDIATE(s, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_restlistgest_processlistcfg</obj_name>
  <obj_hashval>91acd5436cf2c56bf5f4a6e422dc36ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_restlistgest_processlistcfg(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  S               varchar := '';
  gSuplCols        VARCHAR := 'RESTCMD1 R1, NARTOBJ O, NART A, NUM1 U1';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Florin 26.03.2023 - sinc. Oracle
  --Adina 15.06.2021 - sinc.Oracle din 14.06.2021
  --Adina 15.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_RESTLISTGEST.gSuplCols'  ,gSuplCols  ,false);
  PERFORM set_config('PKG_LIST_BASE_RESTLISTGEST.gUserFields',gUserFields,false);
  PERFORM set_config('PKG_LIST_BASE_RESTLISTGEST.gUserAlias' ,gUserAlias ,false);
  PERFORM set_config('PKG_LIST_BASE_RESTLISTGEST.gNullAlias' ,gNullAlias ,false);
  PERFORM set_config('PKG_LIST_BASE_RESTLISTGEST.gSuplJoins' ,gSuplJoins ,false);

  S := 'INSERT INTO ' || TMPNAME || '(DENUMIRE, DENUM, CANT, OBS, ORDINE) ' || coalesce(CHR(13),'') ||
  'VALUES (''ARTICOL CONFIGURARE'',''Buc'', 10, ''Observatie'', 1)';
  PERFORM LIST_EXECUTE_IMMEDIATE(s, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_restlistnp_processlist</obj_name>
  <obj_hashval>56c26ba5ee854718781711d88623b7a5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_restlistnp_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  S               varchar := '';
  gSuplCols        VARCHAR := 'RESTNP1 R1, RESTNP R, RESTCMD RCMD, NARTOBJ O, NART A, NUM1 U1';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Florin 19.05.2022
  --Adina 17.12.2020 - sincronizare cu Oracle
  --Adina 15.12.2020 - sincronizare cu Oracle
  --Adina 15.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_RESTLISTNP.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  S := 'INSERT INTO ' || TMPNAME || '(DENUMIRE, DENUM, CANT, PRET, DISCOUNT, VALDISCOUNT'||gUserFields||') '  || CHR(13) ||
  ' SELECT '               || CHR(13) ||
  '   O.DENUMIRE, '       || CHR(13) ||
  '   U1.DEN_UM1, '       || CHR(13) ||
  '   R1.CANT, '           || CHR(13) ||
  '   R1.PRET, '           || CHR(13) ||
  '   ABS(R1.DISCOUNT),'   || CHR(13) ||
  '   R1.PRET * R1.CANT * ABS(coalesce(R1.DISCOUNT, 0)) / 100 '||gUserAlias         ||  CHR(13) ||
  ' FROM '                                                                           ||  CHR(13) ||
  '   RESTNP1            R1 '                                                       ||  CHR(13) ||
  '   INNER JOIN RESTNP  R    ON R1.CODRESTNP = R.CODRESTNP'                        ||  CHR(13) ||
  '   INNER JOIN NARTOBJ O    ON O.CODOBIECT  = R1.CODOBIECT'                       ||  CHR(13) ||
  '   INNER JOIN NART    A    ON A.CODARTICOL = O.CODARTICOL'                       ||  CHR(13) ||
  '   INNER JOIN NUM1    U1   ON U1.CODUM     = A.UM         AND U1.SECUNDARA = 0'  ||  CHR(13) ||
  '   LEFT  JOIN RESTCMD RCMD ON RCMD.CODRESTCMD = R.CODRESTCMD '                   ||  CHR(13) || gSuplJoins||
  'WHERE '                                                                          ||  CHR(13) ||
  '   R1.CODRESTNP = '  || coalesce(current_setting('PKG_LIST_BASE_RESTLISTNP.CODNP', true),'');

/*
  '   RESTNP1 R1, ' || CHR(13) ||
  '   RESTNP R ' || CHR(13) ||
  '   LEFT JOIN RESTCMD RCMD ON RCMD.CODRESTCMD = R.CODRESTCMD, ' || CHR(13) ||
  '   NARTOBJ O, '   || CHR(13) ||
  '   NART A,'       || CHR(13) ||
  '   NUM1 U1 '     || CHR(13) ||
  ' WHERE '         || CHR(13) ||
  '   R1.CODRESTNP = ' || coalesce(current_setting('PKG_LIST_BASE_RESTLISTNP.CODNP', true),'') || CHR(13) ||
  '   AND R1.CODRESTNP = R.CODRESTNP '  || CHR(13) ||
  '   AND O.CODOBIECT = R1.CODOBIECT '  || CHR(13) ||
  '   AND A.CODARTICOL = O.CODARTICOL ' || CHR(13) ||
  '   AND U1.CODUM = A.UM ' || CHR(13)  ||
  '   AND U1.SECUNDARA = 0';
*/
  PERFORM LIST_EXECUTE_IMMEDIATE(s, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_restlistnp_setparams</obj_name>
  <obj_hashval>b538963ab4406f52c76a506bc437d224</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_restlistnp_setparams(acodrestnp numeric, aid numeric, aver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  perform set_config('PKG_LIST_BASE_RESTLISTNP.CODNP',(aCodRestNP)::varchar,false);
  perform set_config('PKG_LIST_BASE_RESTLISTNP.ID'   ,(aID)::varchar       ,false);
  perform set_config('PKG_LIST_BASE_RESTLISTNP.VER'  ,(aVer)::varchar      ,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rezdoc_processlist</obj_name>
  <obj_hashval>5f960ded33a1990418f6b10907957b3a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rezdoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'TMP_REZERVARI_COMANDA T';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Florin 30.08.2022 - sinc. Oracle (26.08.2022)
  --Adina 15.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_REZDOC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    PRODUS, UMPRODUS, TERMEN, CANTACCEPTAT, COMPONENT, GESTIUNE, TIPCONTABIL, UMCOMPONENT, NECESAR, REZSTOC, CERFURN, NESOSIT, NEACOPERIT' || gUserFields || ')
  SELECT
    T.PRODUS, T.UMPRODUS, T.TERMEN, T.CANTACCEPTAT, T.COMPONENT, T.GESTIUNE, T.TIPCONTABIL, T.UMCOMPONENT, T.NECESAR, T.REZSTOC, T.CERFURN, T.NESOSIT, T.NEACOPERIT' || gUserAlias || '
  FROM TMP_REZERVARI_COMANDA T ' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rezmf_processlist</obj_name>
  <obj_hashval>9dfc18263402ae962e7d00336104ffca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rezmf_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols       VARCHAR :=  'MIFIX MF, MIFIX1 MF1, NIRSTOC NS, NIRSER  NSER, NSERII  SER';
  gUserFields     VARCHAR := '';
  gUserAlias      VARCHAR := '';
  gNullAlias      VARCHAR := '';
  gSuplJoins      VARCHAR := '';
BEGIN
  --Florin 21.06.2023 - sinc. Oracle (20.06.2023)
  --Florin 07.04.2022 - fixat 53799
  --Florin 29.12.2021
  CALL pkg_list_struct_startsuplcols();
  PERFORM set_config('PKG_LIST_BASE_REZMF.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);

    sInsert :=
  ' INSERT INTO '||tmpName||'(
    NrInventar, SerieInv, AnIntrare, LunaIntrare, Amo, DurataF, Neutil,
    Gradu, TipAmo, Stare, Cant, Serie, Responsabil, DenLoc '||gUserFields||')
    SELECT
        MF.NRINVENTAR,
        MF.SERIEINV,
        MF.ANINTRARE,
        MF.LUNAINTRARE,
        MF1.AMO,
        MF1.DURATAF,
        MF1.NEUTIL,
        MF1.GRADU,
        CASE MF1.TIPAMO
          when 1 then ''Liniara''
          when 2 then ''Accelerata''
          when 3 then ''Degresiva 1''
          when 4 then ''Degresiva 2''
          else '''' end :: varchar as TIPAMO ,
        CASE MF1.STARE
          when 1 then ''in Curs de amortizare''
          when 2 then ''Trecut in conservare''
          when 3 then ''Casat in luna curenta''
          when 4 then ''Vandut in luna curenta''
          else '''' end :: varchar as STARE ,
        MF1.CANT,
        SER.SERIE,
        PRS.NUME || '' '' || PRS.PRENUME AS RESPONSABIL,
        LOC.DENUMIRE AS DENLOC '||gUserAlias||'
      FROM
        MIFIX MF
        INNER JOIN MIFIX1 MF1 ON MF1.CODMIFIX = MF.CODMIFIX
        INNER JOIN NIRSTOC  NS   ON NS.CODNIRSTOC  = MF1.CODNIRSTOC
        INNER JOIN NARTOBJ O ON O.CODOBIECT = NS.CODOBIECT
        LEFT OUTER JOIN NIRSER   NSER ON NSER.CODNIRSER = MF1.CODNIRSER
        LEFT OUTER JOIN NSERII   SER  ON SER.CODSERIE   = NSER.CODSERIE
        LEFT OUTER JOIN NPERS    PRS  ON PRS.CODPERS    = MF1.CODPERS
        LEFT OUTER JOIN NLOCATII LOC  ON LOC.CODLOCATIE = NS.CODLOCATIE '||
        gSuplJoins||'
      WHERE
        MF1.CODNIRSTOC = '|| COALESCE(current_setting('pkg_list_base_rezmf.vCod', FALSE), '') || ' AND
        MF1.ANSTART * 12 + MF1.LUNASTART = '||getAnLunaLucru()::varchar;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rptvanzum_processlist</obj_name>
  <obj_hashval>490c537427f1f2180639f63b00345861</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rptvanzum_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
  filtre   varchar := '';
BEGIN
  --Adina 10 septembrie 2020
  filtre := ' AND IES.AN*12+IES.LUNA =getANLUNALUCRU() AND NUM.CODUM = ' || coalesce(current_setting('PKG_LIST_BASE_RPTVANZUM.gCodUm', true),'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('IES',NULL,NULL,NULL),'');

  sInsert := 'INSERT INTO ' || TMPNAME || ' (MEASURE,EXPLICATIE,CANTITATEA,ANLUNA,NIVEL)
  SELECT
    CASE
      WHEN NIVEL = 1 THEN ''M1_VBA00R''
      WHEN NIVEL = 2 THEN ''M1_LTK001''
      WHEN NIVEL = 3 THEN ''M1_LT0001''
    END MEASURE,
    CASE
      WHEN NIVEL = 1 THEN ''VANZARI IN BUCATI''
      WHEN NIVEL = 2 THEN ''VANZARI IN TONE''
      WHEN NIVEL = 3 THEN ''VANZARI IN LITRI''
    END EXPLICATIE,
    CASE
      WHEN NIVEL = 1 THEN A.CANTITATE
      WHEN NIVEL = 2 THEN A.MASA
      WHEN NIVEL = 3 THEN A.VOLUM
    END CANTITATEA,
    A.AN::varchar||CASE WHEN A.LUNA &lt; 10 THEN ''0''||A.LUNA::varchar ELSE A.LUNA::varchar END ANLUNA, X.NIVEL
  FROM (
    SELECT
      SUM(IES1.CANT) Cantitate , SUM(IES1.CANT * coalesce(NOBJ.VOLUM,0))/1000 VOLUM,
      SUM(IES1.CANT * coalesce(NOBJ.MASA,0)) MASA, IES.AN , IES.LUNA
    FROM IESIRI1 IES1
      INNER JOIN NUM1         ON IES1.UMSEC     = NUM1.CODUM1
      INNER JOIN NARTOBJ NOBJ ON NOBJ.CODOBIECT = IES1.CODOBIECT
      INNER JOIN IESIRI  IES  ON IES.CODIES     = IES1.CODIES
      INNER JOIN NUM          ON NUM1.CODUM     = NUM.CODUM
    WHERE IES.TIPDOC IN (19,21,22,26) AND IES.OPERAT = 1 ' || filtre || '
    GROUP BY IES.AN,IES.LUNA
  ) A, (SELECT 1 NIVEL union SELECT 2 nivel union SELECT 3 nivel) X  ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_scadcheltavans_baga_dinamic_cols</obj_name>
  <obj_hashval>ee8282efdeb1daeb783bef788989e2a8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_scadcheltavans_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  s       varchar := '';
  vAn     numeric := getANLUCRU();
  vLuna   numeric := getLUNALUCRU();
  vNrLuni NUMERIC;
BEGIN
  --Florin 09.03.2023 - fixat 57520
  --Adina 26 august 2020
  SELECT
    Coalesce(Max(CASE WHEN C.DATASTART IS NOT NULL AND C.DATAEND IS NOT NULL  THEN (EXTRACT( YEAR FROM C.DATAEND) * 12 + EXTRACT( MONTH FROM C.DATAEND))  - (C1.ANSTART * 12 + C1.LUNASTART)  + 1
                       ELSE Coalesce(C1.DURATAF, 0)
                  END ), 0)
  INTO vNrLuni
  FROM CHELTAVANS1 C1
       INNER JOIN CHELTAVANS C ON  C.CODCHELTAVANS = C1.CODCHELTAVANS
  WHERE C1.ANSTART = getANLUCRU() AND  C1.LUNASTART = getLUNALUCRU();

  FOR i IN 1..vNrLuni LOOP
    S := to_char(vLuna,'fm00')||'.'||to_char(vAn,'fm0000');
    INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES ('D'||To_Char(i,'fm999'), 'Amo.'||S, i);
    vLuna := vLuna + 1;
    IF vLuna &gt; 12 THEN
      vAn   := vAn + 1;
      vLuna := 1;
    END IF;
  END LOOP;
  PERFORM set_config('PKG_LIST_BASE_SCADCHELTAVANS.vNrLuni',vNrLuni::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_scadentarcl_calcadaosdoc</obj_name>
  <obj_hashval>da53abba473b03dca94a8059c1c96f5f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_scadentarcl_calcadaosdoc(pcoddoc numeric, prest numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTipDoc numeric;
  vValDoc numeric;
  vAdaos  numeric;
  vCurs   numeric;
BEGIN
  --Adina 10 august 2020
  IF  Coalesce(pRest, 0) = 0 THEN
    RETURN  0;
  END IF;

  SELECT tipdoc, valdoc, CASE WHEN  Curs IS NULL THEN 1 WHEN  Curs=0 THEN 1 ELSE  Curs END
  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_scadentarcl_getjoinfiltru</obj_name>
  <obj_hashval>823827d9bf3dabf62409d54948a42f51</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_scadentarcl_getjoinfiltru()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sJoinFiltru TEXT := '';
BEGIN
  --Florin 09.08.2022 - fixat 55173
  --Stef 08.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)::varchar = 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::varchar = 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_scadentarcl_setjoinuri</obj_name>
  <obj_hashval>f11b047aed70d33e83fb45a72b5af5d3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_scadentarcl_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 10 august 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_SCADENTARCL.gSuplCols', true));
  PERFORM Pkg_List_Struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_scadentarcl_umple_tmp_lst_scad_sertar</obj_name>
  <obj_hashval>b4cff188e720909677eb81472ec81a48</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_scadentarcl_umple_tmp_lst_scad_sertar(alistid numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsTMP varchar := '';
BEGIN
  --Stef 08.08.2022
  EXECUTE 'TRUNCATE TABLE TMP_LST_SCAD_SERTAR';

  sInsTmp := 'INSERT INTO tmp_lst_scad_sertar  (codobligpif, decont, doc, ser, nrdoc, datadoc, valoare, datadecont, valasoc)
  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::varchar||''/''||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,
    string_agg(To_char(NS.DATADOC,''dd.mm.yyyy''),'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' 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;= ' || coalesce(getAnLunaLucru()::varchar,'') || '
    LEFT JOIN obligpif o ON o.codobligpif = ns1.codobligpif
  WHERE t1.codtrezor IS NULL
  GROUP BY ns1.codobligpif';

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsTmp, aListID, 0);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_scadentarcl_umple_tmp_lst_scad_stins</obj_name>
  <obj_hashval>1972cbd34d3087fe26bb37bebce5bda2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_scadentarcl_umple_tmp_lst_scad_stins(alistid numeric, pfiltruluna character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsTMP     TEXT;
  sJoinFiltru TEXT := PKG_LIST_BASE_SCADENTARCL_GetJoinFiltru();
BEGIN
  --Florin 30.10.2025 - sinc. Oracle
  --Stef 30.05.2025
  EXECUTE 'TRUNCATE TABLE TMP_LST_SCAD_STINS';

  sInsTmp := 'INSERT INTO tmp_lst_scad_stins  (codstinspif, valoare, tva)
  SELECT codstinspif, SUM(val*semn) valoare, Sum(tva*semn) tva
  FROM (
    SELECT
      s.codstinspif, Abs(s.valoare) val, Abs(Coalesce(g.tva,0)) tva,
      CASE
        -- la resturi nesemnificative nu poate fi determinat semnul in functie de valoare initiala a obligatiei (posibil sa se fi platit mai mult si atunci e semn invers)
        WHEN OS.SEMNIFICATIE = 1300 AND O.SEMNIFICATIE = 210 THEN -SIGN(s.valoare)
        WHEN OS.SEMNIFICATIE = 1350 AND O.SEMNIFICATIE = 200 THEN  SIGN(s.valoare)
        ELSE
          CASE WHEN Coalesce(o.valoare,0) &lt; 0 THEN -1 ELSE 1 END *
          CASE
            WHEN OS.SEMNIFICATIE = 750                                                                                    THEN -1
            WHEN OS.SEMNIFICATIE = 1350 AND O.ICONT  =  3 AND      O.SEMNIFICATIE IN (           1201) AND O.ICONT  =  3  THEN  1
            WHEN OS.SEMNIFICATIE = 1350 AND O.ICONT  =  3 AND NOT (O.SEMNIFICATIE IN (     1200      )                  ) THEN -1
            WHEN OS.SEMNIFICATIE = 1350 AND OS.ICONT =  5 AND NOT (O.SEMNIFICATIE IN (210, 1200, 1201) AND O.ICONT  =  5) THEN -1
            ELSE                                                                                                                1
          END *
          CASE
            WHEN O.SEMNIFICATIE  IN (1200, 1201)                            AND O.ICONT = 5             THEN -1
            WHEN O.SEMNIFICATIE = 1201           AND OS.SEMNIFICATIE = 1303                             THEN -1
            WHEN O.SEMNIFICATIE = 1301           AND OS.SEMNIFICATIE = 1350 AND O.ICONT NOT IN (10, 11) THEN -1
            WHEN O.SEMNIFICATIE = 1351                                      AND O.ICONT NOT IN (3, 10)  THEN -1
            WHEN O.SEMNIFICATIE IN (210,330,410)                                                        THEN -1
            ELSE                                                                                             1
          END
      END semn
    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' || sJoinFiltru || '
      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 --AND os.semnificatie IN (211,400)
    WHERE Coalesce(i.an * 12 + i.luna,t1.an * 12 + t1.luna,c.an * 12 + c.luna)'||pFiltruLuna||'
      AND Coalesce(i.infocm,0) &lt;&gt; 1'||
      PKG_LIST_SELECTSCADENTAR_FiltruData('i.DataDoc,t1.DataDoc,c.DataDoc')||'
  ) a_pg
  GROUP BY codstinspif';

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsTmp, aListID, 0);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_scadentarcl_umpletmp</obj_name>
  <obj_hashval>9d3066a829173f9edaa3d5877b9826e0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_scadentarcl_umpletmp(alistid numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsTMP        TEXT;
  sSelTMP        TEXT;
  sJoinFiltru    TEXT         := PKG_LIST_BASE_SCADENTARCL_GetJoinFiltru();
  sCoefValCEC    VARCHAR(200);

  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(100);
  sZilePlusTerm  VARCHAR(100);
  sZilePlusTermC VARCHAR(100);
  sFiltruLuna    VARCHAR(200);
  sAnP           NUMERIC(4);
  sLunaP         NUMERIC(2);
  sAnC           NUMERIC(4);
  sLunaC         NUMERIC(2);
  sData1PCA      VARCHAR(10);
  sData2PCA      VARCHAR(10);

  sIcontS_C      VARCHAR := ',30,31,32,33,34';

  sConv          VARCHAR(100);
BEGIN
  --Florin 10.11.2025 - fixat 67252
  --Florin 01.10.2025 - sinc. Oracle
  --Florin 10.02.2025 - sinc. Oracle
  --Florin 29.07.2024 - sinc. Oracle
  --Stef 06.03.2024
  TRUNCATE TABLE TMP_SCADENTARCL;
  TRUNCATE TABLE TMP_LST_SCAD_PARTVAL;

  SELECT ancurent, lunacurenta INTO sAnC,sLunaC FROM FIRMALUNI;

  sData1PCA  := '01.01.'||to_char(sAnC-1,'fm0000');
  IF To_Number(To_Char(dDataRef,'yyyy')) &lt; sAnC
  THEN sData2PCA  := '31.12.'||to_char(sAnC-1,'fm0000');
  ELSE sData2PCA  := sDataRef;
  END IF;

  sZilePlusDoc := '(TO_DATE('''||sDataRef||''',''dd.mm.yyyy'') - Coalesce(D.DATADOC,TO_DATE('''||sDataNVL||''',''dd.mm.yyyy''))::DATE)';
  IF current_setting('PKG_LIST_SELECTSCADENTAR.g_CodJob1', TRUE)::NUMERIC &gt; 0 THEN
    PERFORM pkg_globals_SetLunaLucru_SIMPLA(extract(year from dDataRef), extract(month from dDataRef));
  END IF;

  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 := ' = '||getAnLunaLucru()::varchar;
  ELSE
    SELECT  NEWAN, newLuna INTO sAnP, sLunaP from pkg_globals_Calculeaza_Luna_Precedenta(sAnC, sLunaC, sAnP, sLunaP);
    sFiltruLuna := ' BETWEEN '||(sAnC*12+sLunaC)::varchar||' AND '||getAnLunaLucru()::varchar;
  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  := 'Coalesce(TO_DATE('''||sDataRef||''',''dd.mm.yyyy'')-Coalesce(O.TERMEN,D.DATADOC)::DATE,0)';
    sZilePlusTermC := 'Coalesce(TO_DATE('''||sDataRef||''',''dd.mm.yyyy'')-Coalesce(D.DATADECONT,O.TERMEN,D.DATADOC)::DATE,0)';
  ELSE
    sZilePlusTerm  := 'Coalesce(TO_DATE('''||sDataRef||''',''dd.mm.yyyy'')-D.DATADOC::DATE,0)';
    sZilePlusTermC := 'Coalesce(TO_DATE('''||sDataRef||''',''dd.mm.yyyy'')-D.DATADOC::DATE,0)';
  END IF;

  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,
    leg_doc, leg_nrdoc, leg_datadoc)';

  sSelTMP := '
  SELECT -- FACTURI PERIOADA CURENTA
    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,
    o.valoare * CASE WHEN o.semnificatie = 210 THEN -1 ELSE 1 END valoare,
    CASE
      WHEN O.VALOARE = 0                                                                    THEN 0
      WHEN Coalesce(G.TVA,0) = 0                                                            THEN 0
      WHEN (SELECT SUM(xO.VALOARE) FROM OBLIGPIF xO WHERE xO.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 * CASE WHEN o.semnificatie = 210 THEN -1 ELSE 1 END tva,
    o.valoare * CASE WHEN o.semnificatie = 210 THEN -1 ELSE 1 END restval,
    CASE
      WHEN O.VALOARE = 0                                                                    THEN 0
      WHEN Coalesce(G.TVA,0) = 0                                                            THEN 0
      WHEN (SELECT SUM(xO.VALOARE) FROM OBLIGPIF xO WHERE xO.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 * 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,'||getAnLunaLucru()::varchar||',o.semnificatie) cont,
    o.adaosdoc,
    Coalesce(g.moneda,0) 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(rc.curs, NullIf(g.curs,0), 1) curs,
    o.codcentru, d.userid,
    round(d.tvadoc/Coalesce(NULLIF(CASE WHEN d.tipdoc = 22 THEN d.valdoc ELSE d.valdoc-d.tvadoc END*100,0),1),2) TVAMediu,
    Coalesce(d.TvaIncasare,0) TvaIncasare, (to_char(Coalesce(O.TERMEN,D.DATADOC)::DATE, ''IYYYIW''))::numeric ansapt, NULL::numeric codtippartincert,
    NULL leg_doc, NULL leg_nrdoc, NULL leg_datadoc
  FROM iesiri d
    INNER JOIN general  g ON g.coddoc     = d.codies AND g.tipdoc = d.tipdoc
    INNER JOIN obligpif o ON o.codgeneral = g.codgeneral'||
    sJoinFiltru||'
    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;= '||getAnLunaLucru()::varchar||'
      ) x where x.nr=1
      GROUP BY x.CodGeneral
    ) rc ON rc.codgeneral = g.codgeneral
  WHERE d.an * 12 + d.luna'||sFiltruLuna||'
    AND d.tipdoc IN (19,21,22,26)
    AND o.semnificatie IN (200,210,220)
    AND NOT (o.semnificatie = 210 AND Coalesce(g.tva,0)=o.valoare)
    AND Coalesce(d.infocm,0) &lt;&gt; 1'||
    PKG_LIST_SELECTSCADENTAR_COND_SUBUNIT('d')||
    PKG_LIST_BASE_UTILS_COND_USERID ('d')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('d.DataDoc');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInstmp||sSeltmp, aLISTID, 0);
  sSelTMP := '
  SELECT -- FACTURI CU SOLD LA INCEPUTUL PERIOADEI
    o.codobligpif, g.coddoc, NULL coddoc1, g.tipdoc, o.codpart, 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,
    CASE
      WHEN O.VALOARE = 0                                                                    THEN 0
      WHEN Coalesce(G.TVA,0) = 0                                                            THEN 0
      WHEN (SELECT SUM(xO.VALOARE) FROM OBLIGPIF xO WHERE xO.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 * CASE WHEN o.semnificatie = 210 THEN -1 ELSE 1 END tva,
    Coalesce(ol.rest,0)    * CASE WHEN o.semnificatie = 210 THEN -1 ELSE 1 END restval,
    Coalesce(ol.resttva,0) * 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,'||getAnLunaLucru()::varchar||',o.semnificatie) cont, o.adaosdoc,
    Coalesce(g.moneda,0) 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(rc.curs, NullIf(g.curs,0), 1) curs,
    o.codcentru, d.userid,
    round(d.tvadoc/Coalesce(NULLIF(CASE WHEN d.tipdoc = 22 THEN d.valdoc ELSE d.valdoc-d.tvadoc END*100,0),1)*100,2) TVAMediu,
    Coalesce(d.TvaIncasare,0) TvaIncasare, (to_char(Coalesce(O.TERMEN,D.DATADOC)::DATE, ''IYYYIW''))::numeric ansapt, NULL codtippartincert,
    NULL leg_doc, NULL leg_nrdoc, NULL leg_datadoc
  FROM obligpifluna ol
    INNER JOIN obligpif o ON o.codobligpif = ol.codobligpif
    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 (
      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;= '||getAnLunaLucru()::varchar||') x where x.nr=1
      GROUP BY x.CodGeneral
    ) rc ON rc.codgeneral = g.codgeneral
  WHERE ol.an = '||sAnP::varchar||' AND ol.luna = '||sLunaP::varchar||'
    AND (Coalesce(ol.rest,0) &lt;&gt; 0 OR Coalesce(ol.resttva,0) &lt;&gt; 0)
    AND o.semnificatie IN (200,210,220)
    AND NOT (o.semnificatie = 210 AND Coalesce(g.tva,0)=o.valoare)
    AND Coalesce(d.infocm,0) &lt;&gt; 1'||
    PKG_LIST_SELECTSCADENTAR_COND_SUBUNIT('d')||
    PKG_LIST_BASE_UTILS_COND_USERID ('d')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('d.DataDoc');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInstmp||sSeltmp, aLISTID, 0);
  sSelTMP := '
  SELECT -- FACTURI ANTERIOARE PERIOADEI CU STINGERI IN LUNA CURENTA SI CU SOLD 0 LA INCEPUTUL PERIOADEI
    o.codobligpif, g.coddoc, NULL coddoc1, g.tipdoc, o.codpart, 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,
    CASE
      WHEN O.VALOARE = 0                                                                    THEN 0
      WHEN Coalesce(G.TVA,0) = 0                                                            THEN 0
      WHEN (SELECT SUM(xO.VALOARE) FROM OBLIGPIF xO WHERE xO.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 * CASE WHEN o.semnificatie = 210 THEN -1 ELSE 1 END tva,
    0 restval, 0 resttva,
    Coalesce(o.majorari,0) majorare, '||sZilePlusDoc||' zile_trecute, '||sZilePlusTerm||' zile_depasire,
    PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont,o.codpart,'||getAnLunaLucru()::varchar||',o.semnificatie) cont, o.adaosdoc,
    Coalesce(g.moneda,0) 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(rc.curs, NullIf(g.curs,0), 1) curs,
    o.codcentru, d.userid,
    round(d.tvadoc/Coalesce(NULLIF(CASE WHEN d.tipdoc = 22 THEN d.valdoc ELSE d.valdoc-d.tvadoc END*100,0),1),2) TVAMediu,
    Coalesce(d.TvaIncasare,0) TvaIncasare, (to_char(Coalesce(O.TERMEN,D.DATADOC)::DATE, ''IYYYIW''))::numeric ansapt, NULL codtippartincert,
    NULL leg_doc, NULL leg_nrdoc, NULL leg_datadoc
  FROM (
    SELECT DISTINCT o.codobligpif
    FROM trezor t
      INNER JOIN trezor1      t1 ON t1.codtrezor      = t.codtrezor
      INNER JOIN general      gs ON gs.coddoc         = t1.codtrezor1 AND gs.tipdoc = t.tipdoc
      INNER JOIN obligpif     os ON os.codgeneral     = gs.codgeneral
      INNER JOIN stingere     s  ON s.codstingatorpif = os.codobligpif
      INNER JOIN obligpif     o  ON o.codobligpif     = s.codstinspif
      INNER JOIN general      g  ON g.codgeneral      = o.codgeneral  AND g.tipdoc IN (19,21,22,26)
      LEFT  JOIN obligpifluna ol ON ol.codobligpif    = o.codobligpif AND ol.an = '||sAnP::varchar||' AND ol.luna = '||sLunaP::varchar||'
    WHERE t.tipdoc IN (29,30,31,33)
      AND gs.semnificatie = 750 AND (t.an*12+t.luna'||sFiltruLuna||')
      AND o.semnificatie IN (200,210,220)
      AND NOT (o.semnificatie = 210 AND Coalesce(g.tva,0)=o.valoare)
      AND Coalesce(ol.rest,0) = 0 AND Coalesce(ol.resttva,0) = 0 '||
      PKG_LIST_SELECTSCADENTAR_COND_SUBUNIT('t')||
      PKG_LIST_BASE_UTILS_COND_USERID ('t')||
      PKG_LIST_SELECTSCADENTAR_FiltruData('t.DataDoc')||'
  ) x
    INNER JOIN obligpif o ON o.codobligpif = x.codobligpif
    INNER JOIN general  g ON g.codgeneral  = o.codgeneral
    INNER JOIN iesiri   d ON d.codies      = g.coddoc'||
    sJoinFiltru||'
    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;= '||getAnLunaLucru()::varchar||') x where x.nr=1
      GROUP BY x.CodGeneral
    ) rc ON rc.codgeneral = g.codgeneral
  WHERE d.an * 12 + d.luna &lt;= '||To_Char(sAnP*12+sLunaP)||'
    AND Coalesce(d.infocm,0) &lt;&gt; 1'||
    PKG_LIST_SELECTSCADENTAR_COND_SUBUNIT('d')||
    PKG_LIST_BASE_UTILS_COND_USERID ('d')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('d.DataDoc');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInstmp||sSeltmp, aLISTID, 0);
  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_SELECTSCADENTAR_COND_SUBUNIT('t')||
      PKG_LIST_BASE_UTILS_COND_USERID ('t')||
      PKG_LIST_SELECTSCADENTAR_FiltruData('t.DataDoc')||'
  )
  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,'||getAnLunaLucru()::varchar||',o.semnificatie) cont, o.adaosdoc,
    Coalesce(g.moneda,0) 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(rc.curs, NullIf(g.curs,0), 1) curs,
    o.codcentru, d.userid,
    round(d.tvadoc/Coalesce(NULLIF(CASE WHEN d.tipdoc = 22 THEN d.valdoc ELSE d.valdoc-d.tvadoc END*100,0),1),2) TVAMediu,
    Coalesce(d.TvaIncasare,0) TvaIncasare, (to_char(Coalesce(O.TERMEN,D.DATADOC)::DATE, ''IYYYIW''))::numeric ansapt, c.codtippartincert,
    NULL leg_doc, NULL leg_nrdoc, NULL leg_datadoc
  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
    ) 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::varchar||' AND ol.luna = '||sLunaP::varchar||'
    LEFT  JOIN xStins          ON xStins.codstinspif = o.codobligpif
    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;= '||getAnLunaLucru()::varchar||'
      ) x where x.nr=1
      GROUP BY x.CodGeneral
    ) rc ON rc.codgeneral = gl.codgeneral
  WHERE o.semnificatie = 1303
    AND d.an * 12 + d.luna &lt;= '||getAnLunaLucru()::varchar||'
    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_SELECTSCADENTAR_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);
  TRUNCATE TABLE TMP_SCADCL_COEFG;

  IF current_setting('PKG_LIST_SELECTSCADENTAR.g_DetTranzInCurs', true)::boolean
  THEN sCoefValCEC := '*CASE WHEN o.valoare = 0 THEN 0 ELSE Coalesce(s.valoare, ox.valoare,o.valoare)/o.valoare END';
  ELSE sCoefValCEC := '';
  END IF;


  IF  aListID = 250 THEN
    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) * CASE WHEN  Coalesce(AE1.CANT, I1.CANT) = I1.CANT THEN 1 ELSE I1.CANT / AE1.CANT END ) VAL,
        Count(1) OVER (PARTITION BY S.CODOBLIGPIF) NRLINII,
        Sum(Sum(I1.PRETORIG * Coalesce(I1.COEFDISCMAJ, 1) * Coalesce(L1.CANT, I1.CANT) * CASE WHEN  Coalesce(AE1.CANT, I1.CANT) = I1.CANT THEN 1 ELSE I1.CANT / AE1.CANT END )) 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 IESLINK ILAE ON  ILAE.CODIES1  = I1.CODIES1
        LEFT JOIN IESIRI1 AE1  ON  AE1.CODIES1   = ILAE.CODLINIEAVIZ
        LEFT JOIN IESIRI  AE   ON  AE.CODIES     = AE1.CODIES
        LEFT JOIN LIVR    L    ON  L.CODIES      = Coalesce(AE.CODIES, I.CODIES) AND  L.TIPLIVR = Coalesce(AE.TIPDOC, I.TIPDOC)
        LEFT JOIN LIVR1   L1   ON  L1.CODLIVR    = L.CODLIVR AND  L1.CODIES1 = Coalesce(AE1.CODIES1, I1.CODIES1)
        LEFT JOIN 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, '||
  CASE
    WHEN current_setting('PKG_LIST_SELECTSCADENTAR.g_DetTranzInCurs', true)::boolean THEN '
    CASE
      WHEN IES_S.CODIES    IS NOT NULL THEN COALESCE(IES_S.PREFIXDOC, ''F'')
      WHEN INT_S.CODINTR   IS NOT NULL THEN COALESCE(INT_S.PREFIXDOC, ''F'')
      WHEN NC_S.CODNC      IS NOT NULL THEN ''NC''
      WHEN T1_S.CODTREZOR1 IS NOT NULL THEN T1_S.DOC
      ELSE d.doc
    END doc,
    CASE
      WHEN IES_S.CODIES    IS NOT NULL THEN IES_S.NRDOC
      WHEN INT_S.CODINTR   IS NOT NULL THEN INT_S.NRDOC
      WHEN NC_S.CODNC      IS NOT NULL THEN NC_S.NRDOC
      WHEN T1_S.CODTREZOR1 IS NOT NULL THEN T1_S.NRDOC
      ELSE d.nrdoc
    END nrdoc,
    CASE
      WHEN IES_S.CODIES    IS NOT NULL THEN IES_S.DATADOC
      WHEN INT_S.CODINTR   IS NOT NULL THEN INT_S.DATADOC
      WHEN NC_S.CODNC      IS NOT NULL THEN NC_S.DATADOC
      WHEN T1_S.CODTREZOR1 IS NOT NULL THEN T1_S.DATADOC
      ELSE d.datadoc
    END datadoc,'
    ELSE 'd.doc, d.nrdoc, d.datadoc, '
  END ||'
    d.nri, t.blocat, COALESCE(d.datadecont,o.termen,d.datadoc) termen,
    o.valoare'||sCoefValCEC||' valoare, Coalesce(g.tva,0)'||sCoefValCEC||' tva,
    CASE WHEN ol.codobligpif IS NULL THEN o.valoare         ELSE ol.rest                END'||sCoefValCEC||' restval,
    CASE WHEN ol.codobligpif IS NULL THEN Coalesce(g.tva,0) ELSE Coalesce(ol.resttva,0) END'||sCoefValCEC||' resttva,
    Coalesce(o.majorari,0) majorare, '||sZilePlusDoc||' zile_trecute, '||sZilePlusTermC||' 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,
    Coalesce(g.moneda,0) Moneda, Coalesce(NullIf(g.curs,0), 1) cursini, d.obs, d.carnetdoc, d.seriedoc seriadoc, t.subunitatea, (case when d.agent is NULL then t.agent when d.agent=0 then t.agent else d.agent end) agent, d.codlocatie, d.Initializari,
    g.CodGeneral, o.coefprovizion, g.exclusplata,
    Coalesce(rc.curs, NullIf(g.curs,0), 1) curs,
    o.codcentru, t.userid,
    0 TVAMediu,
     0 TvaIncasare, (to_char(Coalesce(d.datadecont,o.termen,d.datadoc), ''IYYYIW''))::numeric  ansapt, NULL codtippartincert,'||
  CASE
    WHEN current_setting('PKG_LIST_SELECTSCADENTAR.g_DetTranzInCurs', true)::boolean THEN '
    d.doc leg_doc, d.nrdoc leg_nrdoc, d.datadoc leg_datadoc'
    ELSE '
    NULL leg_doc, NULL leg_nrdoc, NULL leg_datadoc '
  END||'
  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||'
    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;= '||getAnLunaLucru()::varchar||'
      ) x where x.nr=1
      GROUP BY x.CodGeneral
    ) rc ON rc.codgeneral = g.codgeneral'||
  CASE
    WHEN current_setting('PKG_LIST_SELECTSCADENTAR.g_DetTranzInCurs', true)::boolean THEN '
    LEFT JOIN general  gx    ON gx.coddoc         = g.coddoc     AND gx.tipdoc = g.tipdoc AND gx.semnificatie &lt;&gt; g.semnificatie
    LEFT JOIN obligpif ox    ON ox.codgeneral     = gx.codgeneral
    LEFT JOIN STINGERE S     ON S.CODSTINGATORPIF = ox.CODOBLIGPIF
    LEFT JOIN OBLIGPIF O_S   ON O_S.CODOBLIGPIF   = S.CODSTINSPIF
    LEFT JOIN GENERAL  G_S   ON G_S.CODGENERAL    = O_S.CODGENERAL
    LEFT JOIN OBLIGPIF O_F   ON O_F.CODOBLIGPIF   = O_S.CODOBLIGASOCIAT AND O.SEMNIFICATIE = 400 AND O_S.SEMNIFICATIE = 1303
    LEFT JOIN GENERAL  G_F   ON G_F.CODGENERAL    = O_F.CODGENERAL
    LEFT JOIN COMPENS  C_S   ON C_S.CODCOMPENS    = G_S.CODDOC AND G_S.TIPDOC = 28
    LEFT JOIN IESIRI   IES_S ON IES_S.CODIES      = Coalesce(G_F.CODDOC, G_S.CODDOC) AND IES_S.TIPDOC = Coalesce(G_F.TIPDOC, G_S.TIPDOC)
    LEFT JOIN DVI      DVI_S ON DVI_S.CODDVI      = G_S.CODDOC AND O.SEMNIFICATIE = 300 AND O_S.SEMNIFICATIE = 130
    LEFT JOIN INTRARI  INT_S ON INT_S.CODINTR     = Coalesce(DVI_S.CODINTR, G_S.CODDOC) AND INT_S.TIPDOC = G_S.TIPDOC
    LEFT JOIN NC1      NC1_S ON NC1_S.CODNC1      = G_S.CODDOC AND G_S.TIPDOC = 35
    LEFT JOIN NC       NC_S  ON NC_S.CODNC        = NC1_S.CODNC
    LEFT JOIN TREZOR1  T1_S  ON T1_S.CODTREZOR1   = G_S.CODDOC AND G_S.TIPDOC IN (29, 30, 31, 33)
    LEFT JOIN TREZOR   T_S   ON T_S.CODTREZOR     = T1_S.CODTREZOR'
    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 current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric &gt; 1 THEN '
    AND (
      t.subunitatea = '||current_setting('PKG_GLOBALS.SUBUNITATE', true)::varchar||'
      OR
      EXISTS (
        SELECT 1
        FROM general gg
          INNER JOIN obligpif og ON og.codgeneral     = gg.codgeneral
          INNER JOIN stingere s  ON s.codstingatorpif = og.codobligpif
          INNER JOIN obligpif os ON os.codobligpif    = s.codstinspif
          INNER JOIN general  gs ON gs.codgeneral     = os.codgeneral
          INNER JOIN iesiri   i  ON i.codies          = gs.coddoc AND i.tipdoc = gs.tipdoc
        WHERE gg.coddoc = g.coddoc AND gg.tipdoc = g.tipdoc AND gg.semnificatie &lt;&gt; g.semnificatie
          AND i.subunitatea = '||current_setting('PKG_GLOBALS.SUBUNITATE', true)||'
      )
    )'
    WHEN PKG_LIST_SELECTSCADENTAR_TranzCursFirma() THEN ''
    ELSE PKG_LIST_SELECTSCADENTAR_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,'||getAnLunaLucru()::varchar||',o.semnificatie) cont, o.adaosdoc,
    Coalesce(g.moneda,0) Moneda, Coalesce(NullIf(g.curs,0), 1) cursini,  d.obs, d.carnetdoc, d.seriedoc seriadoc, t.subunitatea, (case when d.agent is NULL then t.agent when d.agent=0 then t.agent else d.agent end) agent, d.codlocatie, d.Initializari,
    g.CodGeneral, o.coefprovizion, g.exclusplata,
    Coalesce(rc.curs, NullIf(g.curs,0), 1) curs,
    o.codcentru, t.userid,
    0 TVAMediu,
    0 TvaIncasare, (to_char(Coalesce(D.DATADECONT,O.TERMEN,D.DATADOC)::DATE, ''IYYYIW''))::numeric ansapt, NULL codtippartincert,
    NULL leg_doc, NULL leg_nrdoc, NULL leg_datadoc
  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||'
    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;= '||getAnLunaLucru()::varchar||'
      ) x where x.nr=1
      GROUP BY x.CodGeneral
    ) rc ON rc.codgeneral = g.codgeneral
  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_SELECTSCADENTAR_COND_SUBUNIT('t')||
    PKG_LIST_BASE_UTILS_COND_USERID ('t')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('d.DataDoc');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInstmp||sSeltmp, aLISTID, 0);

  sSelTMP := '
  SELECT -- NOTE CONTABILE LEGATE DE PARTENERI
    o.codobligpif, d.codnc, NULL coddoc1, g.tipdoc, o.codpart, ''NC'' doc, d.nrdoc, d.datadoc, '' '' nri, 0 blocat, o.termen,
    CASE WHEN o.icont = 5 AND o.semnificatie in (1200,1201) THEN -1 ELSE 1 END * o.valoare         valoare,
    CASE WHEN o.icont = 5 AND o.semnificatie in (1200,1201) THEN -1 ELSE 1 END * Coalesce(g.tva,0) tva,
    CASE WHEN o.icont = 5 AND o.semnificatie in (1200,1201) THEN -1 ELSE 1 END * CASE WHEN ol.codobligpif IS NULL THEN o.valoare         ELSE ol.rest                END restval,
    CASE WHEN o.icont = 5 AND o.semnificatie in (1200,1201) THEN -1 ELSE 1 END * 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,'||getAnLunaLucru()::varchar||',o.semnificatie) cont, o.adaosdoc,
    Coalesce(g.moneda,0) 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(rc.curs, NullIf(g.curs,0), 1) curs,
    o.codcentru, d.userid,
    0 TVAMediu,
    0 TvaIncasare, (to_char(Coalesce(O.TERMEN,D.DATADOC)::DATE, ''IYYYIW''))::numeric ansapt, NULL codtippartincert,
    NULL leg_doc, NULL leg_nrdoc, NULL leg_datadoc
  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||'
    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;= '||getAnLunaLucru()::varchar||') x where x.nr=1
      GROUP BY x.CodGeneral
    ) rc ON rc.codgeneral = g.codgeneral
  WHERE o.icont IN (3,5,10,11,18,20,23,24'||sIcontS_C||')  -- 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_SELECTSCADENTAR_COND_SUBUNIT('d')||
    PKG_LIST_BASE_UTILS_COND_USERID ('d')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('d.DataDoc');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInstmp||sSeltmp, aLISTID, 0);

  sSelTMP := '
  SELECT -- NOTE CONTABILE LEGATE DE PARTENERI - LITIGII
    o.codobligpif, d.codnc, NULL coddoc1, g.tipdoc, o.codpart, ''Litigiu NC'' doc, d.nrdoc, d.datadoc, '' '' nri, 0 blocat,  o.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,
    PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont,o.codpart,'||getAnLunaLucru()::varchar||',o.semnificatie) cont, o.adaosdoc,
    Coalesce(g.moneda,0) Moneda, Coalesce(NullIf(g.curs,0), 1) 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(rc.curs, NullIf(g.curs,0), 1) curs,
    o.codcentru, d.userid,
    0 TVAMediu,
    0 TvaIncasare, (to_char(Coalesce(O.TERMEN,D.DATADOC)::DATE, ''IYYYIW''))::numeric ansapt, c.codtippartincert,
    NULL leg_doc, NULL leg_nrdoc, NULL leg_datadoc
  FROM obligpif o
    INNER JOIN general gl ON gl.codgeneral = o.codgeneral AND gl.tipdoc = 28
    INNER JOIN compens c  ON c.codcompens  = gl.coddoc
    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
    ) olit ON olit.rootcodobligpif = o.codobligpif
    INNER JOIN general g ON g.codgeneral = olit.codgeneral AND g.tipdoc IN (35) '||
    sJoinFiltru||'
    LEFT  JOIN nc1       ON nc1.codnc1   = g.coddoc
    LEFT  JOIN nc      d ON d.codnc      = nc1.codnc
    LEFT  JOIN obligpifluna ol ON ol.codobligpif = o.codobligpif AND ol.an = '||sAnP::varchar||' AND ol.luna = '||sLunaP::varchar||'
    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;= '||getAnLunaLucru()::varchar||'
      ) x where x.nr=1
      GROUP BY x.CodGeneral
    ) rc ON rc.codgeneral = gl.codgeneral
  WHERE o.semnificatie = 1303
    AND olit.icont IN (3,5,10,11,18'||sIcontS_C||') -- 7 - facturi de intocmit - trebuie exclus
    AND Coalesce(d.an * 12 + d.luna, c.an * 12 + c.luna) &lt;= '||getAnLunaLucru()::varchar||'
    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_SELECTSCADENTAR_COND_SUBUNIT('', 'Coalesce(d.subunitatea, c.subunitatea)')||
    PKG_LIST_BASE_UTILS_COND_USERID ('', 'Coalesce(d.userid, c.userid)')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('Coalesce(d.DataDoc, c.DataDoc)')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('c.DataDoc');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInstmp||sSeltmp, aLISTID, 0);

  sSelTMP := '
  SELECT -- COMPENSARI
    o.codobligpif, g.coddoc, NULL 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,'||getAnLunaLucru()::varchar||',o.semnificatie) cont, o.adaosdoc,
    Coalesce(g.moneda,0) 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(rc.curs, NullIf(g.curs,0), 1) curs,
    o.codcentru, d.userid,
    0 TVAMediu,
    0 TvaIncasare, (to_char(Coalesce(O.TERMEN,D.DATADOC)::DATE, ''IYYYIW''))::numeric ansapt, d.codtippartincert,
    NULL leg_doc, NULL leg_nrdoc, NULL leg_datadoc
  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||'
    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;= '||getAnLunaLucru()::varchar||'
      ) x where x.nr=1
      GROUP BY x.CodGeneral
    ) rc ON rc.codgeneral = g.codgeneral
  WHERE o.semnificatie IN (1301,1351)
    AND o.icont IN (3,5,10,11,18'||sIcontS_C||') -- 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_SELECTSCADENTAR_COND_SUBUNIT('d')||
    PKG_LIST_BASE_UTILS_COND_USERID ('d')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('d.DataDoc');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInstmp||sSeltmp, aLISTID, 0);

  TRUNCATE TABLE 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 PKG_LIST_BASE_SCADENTARCL_UMPLE_tmp_lst_scad_stins (aListID, sFiltruLuna);
  PERFORM PKG_LIST_BASE_SCADENTARCL_UMPLE_tmp_lst_scad_sertar(aListID);

  sInsTmp := 'INSERT INTO tmp_lst_scad_partval (partener, partvaliesac, partvaliesap)
  SELECT
    partener,
    SUM(CASE WHEN an = '||To_char(sAnC-1,'fm0000')||' THEN 0 ELSE (valdoc-tvadoc)*Coalesce(NullIf(curs,0), 1) END) PARTVALIESAC,
    SUM(CASE WHEN an = '||To_char(sAnC-1,'fm0000')||' THEN (valdoc-tvadoc)*Coalesce(NullIf(curs,0), 1) ELSE 0 END) PARTVALIESAP
  FROM iesiri
  WHERE tipdoc in (19,21,26) AND Coalesce(operat,0) = 1 AND Coalesce(anulat,0) = 0
    AND Coalesce(partener, 0) &lt;&gt; 0
    AND datadoc between TO_DATE('''||sData1PCA||''',''dd.mm.yyyy'') AND TO_DATE('''||sData2PCA||''',''dd.mm.yyyy'')
  GROUP BY partener';

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsTmp, aListID, 0);

  PERFORM PKG_LIST_BASE_UTILS_Make_idx_tmp_lst_scad();

  PERFORM set_config('PKG_LIST_BASE_SCADENTARCL.sConv',    sConv,    false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_scadentarf_calcadaosdoc</obj_name>
  <obj_hashval>4d222fcf7e2d23376eb48f976c4bf5ad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_scadentarf_calcadaosdoc(pcoddoc numeric, prest numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vTipDoc numeric;
  vValDoc numeric;
  vAdaos  numeric;
  vCurs   numeric;
BEGIN
  --Adina 07.04.2021 -alstart,alstop
  --Adina 13 august 2020
  IF  Coalesce(pRest, 0) = 0 THEN
    RETURN  0;
  END IF;

  SELECT tipdoc, valdoc, Coalesce(Curs, 1)
  INTO vTipDoc, vValDoc, vCurs
  FROM intrari
  WHERE codintr = pCodDoc;

  IF vTipDoc IS NULL THEN
    RETURN  0;
  ELSIF vTipDoc = 9 THEN
    SELECT SUM(CASE io1.aretvaneex
                  WHEN 1 THEN ns.adaos - ns.pret * Coalesce(ns.tva, 0) / (1 + Coalesce(ns.tva, 0))
                  WHEN 2 THEN ns.adaos / (1 + Coalesce(ns.tva, 0))
                  ELSE ns.adaos
                END  * ns.cantnir * i1.cant / a1.cant)
    INTO vAdaos
    FROM intrari i
      INNER JOIN intrari1 i1  ON  i1.codintr   = i.codintr
      INNER JOIN intrlink il  ON  il.codintr1  = i1.codintr1
      INNER JOIN intrari1 a1  ON  a1.codintr1  = il.codlinieaviz
      INNER JOIN intrari  a   ON  a.codintr    = a1.codintr
      INNER JOIN nir      n   ON  n.codintr    = a.codintr   AND  n.tipnir    = a.tipdoc
      INNER JOIN nirstoc  ns  ON  ns.codnir    = n.codnir    AND  ns.codintr1 = a1.codintr1
      INNER JOIN ioart1   io1 ON  io1.codioart = ns.codioart AND  (a.an * 12 + a.luna) BETWEEN io1.ALStart AND io1.ALStop
    WHERE i.codintr = pCodDoc;
  ELSE
    SELECT SUM(CASE io1.aretvaneex
           WHEN 1 THEN ns.adaos - ns.pret * Coalesce(ns.tva, 0) / (  1 + Coalesce(ns.tva, 0))
           WHEN 2 THEN ns.adaos / (  1 + Coalesce(ns.tva, 0))
           ELSE ns.adaos
            END  * ns.cantnir)
    INTO vAdaos
    FROM intrari i
      INNER JOIN nir     n   ON  n.codintr    = i.codintr   AND  n.tipnir = i.tipdoc
      INNER JOIN nirstoc ns  ON  ns.codnir    = n.codnir
      INNER JOIN ioart1  io1 ON  io1.codioart = ns.codioart AND  (i.an * 12 + i.luna) BETWEEN io1.ALStart AND io1.ALStop
    WHERE i.codintr = pCodDoc;
  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_scadentarf_setjoinuri</obj_name>
  <obj_hashval>843086fa879bdcbf9f40474d3b6cf3e3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_scadentarf_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 13 august 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_SCADENTARF.gSuplCols', true));
  PERFORM Pkg_List_Struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sediipart_processlist</obj_name>
  <obj_hashval>9b9f96ccecb9c4d033d92a6995766f90</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sediipart_processlist(tmp_name character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  gSuplCols   varchar := 'npart p, npart1 p1, nagenda a, nagenda1 a1, npartcodfisc, nlocalit l, njudet j, ntari t, npers  np, nzone z, traseulivr tl, ntipsedii tips, nperscontact pc';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Adina 30.04.2021 - alstart,alstop
  --Adina iulie 2020
  CALL PRC_AL_CHECK('nagenda1',0);
  CALL PRC_AL_CHECK('npart1'  ,0);

  CALL pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_SEDIIPART.gSuplCols',gSuplCols,false);

  sInsert := 'INSERT INTO ' ||tmp_name || ' (
      DEN_PART,REGCOM,CODFISCAL,SEDIU,TELEFON,FAX,EMAIL,
      ADRESA,
      KM,AGENT,
      SEDIUSOCIAL,
      DEN_LOCALIT,DEN_JUDET,DEN_TARA,DEN_ZONA, TRASEU, POZTRASEU,
      TIPSEDIU, X_JUDET ' || gUserFields || ')
    SELECT
      p.den_part, coalesce(p.regcom,'' ''), coalesce(cf.codfiscal,'' ''), a.obs sediu, a.telefon, a.fax, a.email,
      (select getadresa.wme_result from getadresa('''',a.sector, a.strada, a.nr1, a.nr2, a.bloc, a.scara, a.etaj, a.apart, a.codpostal)),
      a.km, coalesce(np.nume,''...'') ||'';''||coalesce(np.prenume,''...'') AGENT,
      case when (A.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(A.INACTIV, 0) = 0) then ''DA'' else ''NU'' end sediusocial,
      l.den_localit, j.den_judet, t.den_tara, z.den_zona, tl.dentraseu, a.poztraseu,
      case
         when A.SEDIUSOCIAL=1 then ''S.livrare''
         when A.SEDIUSOCIAL=2 then ''S.facturare''
         when A.SEDIUSOCIAL=3 then ''S.facturare + livrare''
         when A.SEDIUSOCIAL=4 then ''S.social''
         when A.SEDIUSOCIAL=5 then ''S.social + livrare''
         when A.SEDIUSOCIAL=6 then ''S.social + facturare''
         when A.SEDIUSOCIAL=7 then ''S.social + facturare + livrare''
         when A.SEDIUSOCIAL=9 then ''livrare la beneficiar''
      end,
      j.simbauto'|| gUserAlias || '
    FROM npart p
      INNER JOIN nagenda     a    ON p.codpart        = a.codpart
      LEFT JOIN nagenda1     a1   ON a1.codagenda     = a.codagenda AND ' || coalesce(getAnLunaLucru(),'0') || ' BETWEEN a1.ALStart and a1.ALStop
      LEFT JOIN npartcodfisc cf   ON cf.codpart       = p.codpart   AND cf.principal = 1
      LEFT JOIN nlocalit     l    ON l.codlocalit     = a.codlocalit
      LEFT JOIN njudet       j    ON j.codjudet       = l.codjudet
      LEFT JOIN ntari        t    ON t.codtara        = l.codtara
      LEFT JOIN npers        np   ON np.codpers       = a.codagent
      LEFT JOIN nzone        z    ON z.codzona        = l.codzona
      LEFT JOIN traseulivr   tl   ON tl.codtraseulivr = a.codtraseu
      LEFT JOIN npart1       p1   ON p1.codpart1      = a.codpart AND ' || coalesce(getAnLunaLucru(),'0') || ' BETWEEN p1.ALStart and p1.ALStop
      LEFT JOIN ntipsedii    tips ON tips.codtipsediu = a.codtipsediu
      LEFT JOIN nperscontact pc ON pc.codpart         = p.codpart AND pc.implicit = 1' || gSuplJoins || '
    WHERE P.CODPART &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_selanlunaref_an</obj_name>
  <obj_hashval>4274bfa741ea521287aa6de04e12f8ad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_selanlunaref_an()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 11 septembrie 2020
  RETURN current_setting('PKG_LIST_BASE_SELANLUNAREF.vAn', true)::numeric;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_selanlunaref_an</obj_name>
  <obj_hashval>32228c46118fe986d431766e950cda60</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_selanlunaref_an(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 28.08.2020
  WME_Result :=  current_setting('PKG_LIST_BASE_SELANLUNAREF.vAn', true)::numeric;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_selanlunaref_luna</obj_name>
  <obj_hashval>923dad3fe215f1525f7a936bc95e8a41</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_selanlunaref_luna(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 28.08.2020
  WME_Result :=  current_setting('PKG_LIST_BASE_SELANLUNAREF.vLuna', true)::numeric;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_selanlunaref_setparams</obj_name>
  <obj_hashval>2fee949b127c2ba41d6c7e36ab488f09</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_selanlunaref_setparams(pluna numeric, pan numeric, psubunit numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_SELANLUNAREF.vLuna'   ,pLuna::varchar   ,false);
  perform set_config('PKG_LIST_BASE_SELANLUNAREF.vAn'     ,pAn::varchar     ,false);
  perform set_config('PKG_LIST_BASE_SELANLUNAREF.vSubunit',pSubunit::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_selanlunaref_sub</obj_name>
  <obj_hashval>00dd72b619c72019924b9be4713b9571</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_selanlunaref_sub(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 28.08.2020
  WME_Result :=  current_setting('PKG_LIST_BASE_SELANLUNAREF.vSubunit', true)::numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_serii_filtru_livr</obj_name>
  <obj_hashval>fd60d8356250dca531583e368c52f29b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_serii_filtru_livr(INOUT wme_result character varying, INOUT ptipdoc numeric, INOUT pcoddoc numeric, INOUT pliniedoc numeric, INOUT ptipserie numeric, INOUT pumsec numeric DEFAULT NULL::numeric, INOUT pcodioart numeric DEFAULT NULL::numeric, INOUT pcodgest numeric DEFAULT NULL::numeric, INOUT pcodlocatie numeric DEFAULT NULL::numeric, INOUT pcodgestprod numeric DEFAULT NULL::numeric, INOUT pfurn numeric DEFAULT NULL::numeric, INOUT pd1 numeric DEFAULT NULL::numeric, INOUT pd2 numeric DEFAULT NULL::numeric, INOUT pd3 numeric DEFAULT NULL::numeric, INOUT pdataachiz character varying DEFAULT NULL::character varying, INOUT psign numeric DEFAULT NULL::numeric, INOUT pcodgestd numeric DEFAULT NULL::numeric, INOUT pcodlocatied numeric DEFAULT NULL::numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResult varchar;
BEGIN
  --Florin 14.08.2020
  --Adina 17 august 2020 - inlocuit nvl cu coalesce +adaugat cast la pTipDoc,pliniedoc,pTipSerie,pumsec,pFurn,pd1,pd2,pd3,pSign + linia 70
  IF  pTipSerie &lt;&gt; 0 THEN
    sResult := ' WHERE L.TIPLIVR = ' || coalesce(pTipDoc::varchar,'');
    IF pTipDoc IN (12, 13) THEN
      sResult := coalesce(sResult,'') || ' AND L.CodTransf = ' || coalesce(pCodDoc::varchar ,'') || ' AND L1.CodIes1 = ' || coalesce(pLinieDoc::varchar,'');
    ELSIF pTipDoc = 5 THEN
      sResult := coalesce(sResult,'') || ' AND L.CodIntr = ' || coalesce(pCodDoc::varchar ,'') || ' AND L1.CodDvi1 = ' || coalesce(pLinieDoc::varchar,'');
    ELSE
      sResult := coalesce(sResult,'') || ' AND L.CodIes = ' || coalesce(pCodDoc::varchar ,'') || ' AND L1.CodIes1 = ' || coalesce(pLinieDoc::varchar,'');
    END IF;

    IF pTipSerie IN (1, 2) THEN
      sResult := coalesce(sResult,'') || ' AND NS.TipSerie = ' || coalesce(pTipSerie::varchar,'');
    ELSE
      sResult := coalesce(sResult,'') || ' AND NS.TipSerie IS NOT NULL';
    END IF;

    IF pUMSec IS NOT NULL THEN
      sResult := coalesce(sResult,'') || ' AND L1.UmSec = ' || coalesce(pUMSec::varchar,'');
    END IF;

    IF pCodIoart IS NOT NULL THEN
      sResult := coalesce(sResult,'') || ' AND NS.CodIoart = ' || coalesce(pCodIoart::varchar ,'');
    END IF;

    IF pCodGest IS NOT NULL THEN
      sResult := coalesce(sResult,'') || ' AND N.Gest = ' || coalesce(pCodGest::varchar ,'');
    END IF;

    IF pCodLocatie IS NOT NULL THEN
      sResult := coalesce(sResult,'') || ' AND coalesce(NS.CodLocatie,0) = ' || coalesce(pCodLocatie::varchar ,'');
    END IF;

    IF pCodGestProd IS NOT NULL THEN
      sResult := coalesce(sResult,'') || ' AND coalesce(NS.codgestProd,0) = ' || coalesce(pCodGestProd::varchar ,'');
    END IF;

    IF pFurn IS NOT NULL THEN
      sResult := coalesce(sResult,'') || ' AND coalesce(NS.Furn,0) = ' || coalesce(pFurn::varchar,'');
    END IF;

    IF pD1 IS NOT NULL THEN
      sResult := coalesce(sResult,'') || ' AND coalesce(NS.D1,0) = ' || coalesce(pD1::varchar,'');
    END IF;

    IF pD2 IS NOT NULL THEN
      sResult := coalesce(sResult,'') || ' AND coalesce(NS.D2,0) = ' || coalesce(pD2::varchar,'');
    END IF;

    IF pD3 IS NOT NULL THEN
      sResult := coalesce(sResult,'') || ' AND coalesce(NS.D3,0) = ' || coalesce(pD3::varchar,'');
    END IF;

    IF  pDataAchiz = '0' THEN
      sResult := coalesce(sResult,'') || ' AND NS.DataAchiz IS NULL';
    ELSIF pDataAchiz IS NOT NULL THEN
      sResult := coalesce(sResult,'') || ' AND NS.DataAchiz = to_date(''' || coalesce(pDataAchiz,'') || ''',''dd.mm.yyyy'')';
    END IF;

    IF pSign IS NOT NULL THEN
      sResult := coalesce(sResult,'') || ' AND SIGN(l1.cant) = ' || coalesce(pSign::varchar,'');
    END IF;

    IF pCodGestD IS NOT NULL THEN
      sResult := coalesce(sResult,'') || ' AND ND.Gest = ' || coalesce(pCodGestD::varchar ,'');
    END IF;

    IF pCodLocatieD IS NOT NULL THEN
      sResult := coalesce(sResult,'') || ' AND coalesce(NSD.CodLocatie,0) = ' || coalesce(pCodLocatieD::varchar ,'');
    END IF;
  END IF;
  WME_Result :=  sResult;
  RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_serii_processlist</obj_name>
  <obj_hashval>83564f70ef9e9716b6fda0c75e3eefe3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_serii_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 := 'NIRSER NSER, NIRSTOC NS, NIR N, NSERII SER, NARTOBJ NOBJ, CERTIF C, NTARI TARA, NUM1 UM, NPART FURN';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Adina 17 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_SERII.gSuplCols'  ,gSuplCols  ,false);
  PERFORM set_config('PKG_LIST_BASE_SERII.gUserFields',gUserFields,false);
  PERFORM set_config('PKG_LIST_BASE_SERII.gUserAlias' ,gUserAlias ,false);
  PERFORM set_config('PKG_LIST_BASE_SERII.gNullAlias' ,gNullAlias ,false);
  PERFORM set_config('PKG_LIST_BASE_SERII.gSuplJoins' ,gSuplJoins ,false);

  sInsert :=
  'INSERT INTO ' || coalesce(TMPNAME,'') || ' (
      DENUMIRE,SERIE,CANT,OBS,NRCERTIF,DATAPRIMIRE,PROVENIENTA,DEN_TARA,
      TIPSERIE,STARE,
      PREINREG,PRETACHIZ,DEN_UM1,DATAPROD' || gUserFields || ')';

  IF  current_setting('PKG_LIST_BASE_SERII.TIP_SQL', true)::numeric = 0 THEN
    sSelect := '
      SELECT
        NOBJ.DENUMIRE,SER.SERIE,NSER.CANTNIR,SER.OBS,C.NRCERTIF,C.DATAPRIMIRE, C.PROVENIENTA,TARA.DEN_TARA,
        (case when NS.TIPSERIE=1 then ''Serie pe bucata'' when NS.TIPSERIE=2 then ''Serie pe lot'' end) tipserie,
      (case when nser.stare=1 then ''Liber'' when nser.stare=2 then ''Restrictionat'' when nser.stare=3 then ''Blocat'' end) stare,
        ns.pret pretinreg, ns.pret - ns.adaos pretachiz,UM.DEN_UM1,NSER.DATAPROD' || gUserAlias || '
      FROM NIRSER NSER
        INNER JOIN NIRSTOC NS   ON NSER.CODNIRSTOC = NS.CODNIRSTOC
        INNER JOIN NIR     N    ON N.CODNIR        = NS.CODNIR
        INNER JOIN NSERII  SER  ON SER.CODSERIE    = NSER.CODSERIE
        INNER JOIN NARTOBJ NOBJ ON NOBJ.CODOBIECT  = NS.CODOBIECT
        LEFT  JOIN CERTIF  C    ON C.CODCERTIF     = NSER.CODCERTIF
        LEFT  JOIN NTARI   TARA ON TARA.CODTARA    = C.CODTARA
        LEFT  JOIN NUM1    UM   ON UM.CODUM1       = NS.UMSEC
        LEFT  JOIN NPART   FURN ON FURN.CODPART    = NS.FURN' || gSuplJoins;
  END IF;

  IF  current_setting('PKG_LIST_BASE_SERII.TIP_SQL', true)::numeric = 1 THEN
    sSelect := '
      SELECT
        NOBJ.DENUMIRE,SER.SERIE,L1.CANT,SER.OBS,C.NRCERTIF,C.DATAPRIMIRE, C.PROVENIENTA,TARA.DEN_TARA,
        (case when NS.TIPSERIE=1 then ''Serie pe bucata'' when NS.TIPSERIE=2 then ''Serie pe lot'' end) tipserie,
      (case when nser.stare=1 then ''Liber'' when nser.stare=2 then ''Restrictionat'' when nser.stare=3 then ''Blocat'' end) stare,
        ns.pret pretinreg, ns.pret - ns.adaos pretachiz,UM.DEN_UM1,NSER.DATAPROD' || gUserAlias || '
      FROM NIRSER NSER
        INNER JOIN LIVR1   L1   ON L1.CODNIRSER    = NSER.CODNIRSER
        INNER JOIN LIVR    L    ON L.CODLIVR       = L1.CODLIVR
        INNER JOIN NIRSTOC NS   ON NSER.CODNIRSTOC = NS.CODNIRSTOC
        INNER JOIN NIR     N    ON N.CODNIR        = NS.CODNIR
        INNER JOIN NSERII  SER  ON SER.CODSERIE    = NSER.CODSERIE
        INNER JOIN NARTOBJ NOBJ ON NOBJ.CODOBIECT  = NS.CODOBIECT
        LEFT  JOIN CERTIF  C    ON C.CODCERTIF     = NSER.CODCERTIF
        LEFT  JOIN NTARI   TARA ON TARA.CODTARA    = C.CODTARA
        LEFT  JOIN NUM1    UM   ON UM.CODUM1       = NS.UMSEC
        LEFT  JOIN NIRSTOC NSD  ON NSD.CODLIVR1    = L1.CODLIVR1
        LEFT  JOIN NIR     ND   ON ND.CODNIR       = NSD.CODNIR
        LEFT  JOIN NPART   FURN ON FURN.CODPART    = NS.FURN' || gSuplJoins;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_serii_setparams</obj_name>
  <obj_hashval>7968571eaa50ed5177e1dec6ce649088</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_serii_setparams(aconditie character varying, atipsql numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 17 august 2020
  perform set_config('PKG_LIST_BASE_SERII.Tip_Sql',(aTipSql)::varchar,false);
  IF  current_setting('PKG_LIST_BASE_SERII.Tip_Sql', true)::numeric = 0 THEN
    perform set_config('PKG_LIST_BASE_SERII.WHERE_FILTER',(' WHERE NS.CODNIRSTOC = ' || coalesce(aConditie,''))::varchar,false);
  ELSIF current_setting('PKG_LIST_BASE_SERII.Tip_Sql', true)::numeric = 1 THEN
    perform set_config('PKG_LIST_BASE_SERII.WHERE_FILTER',(aConditie)::varchar,false);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sertar_processlist</obj_name>
  <obj_hashval>3c58f2bd4b78416e2f1b12e714270206</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sertar_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sFiltru     varchar;
  sCamp       varchar;
  sGroup      varchar;
  gSuplCols   varchar := 'NSERTAR NS, NSERTAR1 NS1, OBLIGPIF O, NBANK B, NMONEDE MON, NPART NPE, NPART NPP, NSUBUNIT SUB, NPARTCODFISC PCF, NPARTB PB, NBANK BP';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 30.07.2020

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

  sFiltru := (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL, 'NS', 'SUBUNITATE', 'WHERE', NULL));
  IF current_setting('PKG_LIST_BASE_SERTAR.vOriceData', true)::numeric = 0 THEN
    sFiltru := coalesce(sFiltru,'') || ' AND NS.DATADOC ' || coalesce(current_setting('PKG_LIST_BASE_SERTAR.vPerioada', true),'');
  END IF;
  IF current_setting('PKG_LIST_BASE_SERTAR.vDepus0', true)::numeric =  1 THEN
    sFiltru := coalesce(sFiltru,'') || ' AND NS.DEPUS = 0';
  END IF;
  IF current_setting('PKG_LIST_BASE_SERTAR.vDefalcat', true)::numeric = 1 THEN
    sCamp := ', NS1.CodSertar1, NS1.DenDocLegatura, NS1.Valoare';
    sGroup := '';
  ELSE
    sCamp := ', 0 CodSertar1, string_agg(DISTINCT NS1.DenDocLegatura, '''') DenDocLegatura, SUM(NS1.Valoare) Valoare';
    sGroup := ' GROUP BY NS.CODSERTAR';
  END IF;
  sInsert := 'INSERT INTO ' || tmpName || '(
    NAV_CodDoc, NAV_TipDoc, DATAOBLIG,
    TIP, DECONT,
    BANCA, MONEDA, PARTENER, EMITENT, SERDOC, NRDOC, DATADECONT, DECONTAT, DATADOC, VALDOC, OBSDOC,
    DOCLEG, VALASOC, CODSWIFT, CODBNR, CODFISCAL' || gUserFields || ')
  SELECT
    NS.CodSertar, 69, NS.DATAOBLIG,
    (case when NS.TIP = 1 then ''Incasare'' else ''Plata'' end) Tip,
    (Case When NS.DECONT = 3 then ''Efecte remise'' When NS.DECONT = 2 then ''Efecte acceptate'' else ''Cecuri'' end) Decont,
    B.DENUMIRE, MON.SIMBOL, NPP.Den_Part, NPE.Den_Part, NS.Doc, NS.NrDoc, NS.DataDecont,
    (Case  When NS.Depus = 0 then  ''NU'' else ''DA'' end) DECONTAT,
    NS.DataDoc, NS.Valoare, NS.Obs,
    TMP.DenDocLegatura, TMP.Valoare, B.CODSWIFT, B.CODBNR, PCF.CODFISCAL ' || gUserAlias || '
  FROM (
    SELECT NS.CODSERTAR' || coalesce(sCamp,'') || '
    FROM NSERTAR NS LEFT JOIN NSERTAR1 NS1 ON NS1.CODSERTAR = NS.CODSERTAR ' || coalesce(sFiltru,'') || coalesce(sGroup,'') || '
  ) TMP
    LEFT JOIN NSERTAR      NS  ON NS.CODSERTAR   = TMP.CODSERTAR
    LEFT JOIN NSERTAR1     NS1 ON NS1.CODSERTAR1 = TMP.CODSERTAR1
    LEFT JOIN NBANK        B   ON B.CODBANK      = NS.BANCA
    LEFT JOIN NMONEDE      MON ON MON.CODMONEDA  = COALESCE(NS.MONEDA,0)
    LEFT JOIN NPART        NPE ON NPE.CODPART    = NS.CODEMITENT
    LEFT JOIN NPART        NPP ON NPP.CODPART    = NS.CODPARTENER
    LEFT JOIN NSUBUNIT     SUB ON SUB.CODSUBUNIT = NS.SUBUNITATE
    LEFT JOIN OBLIGPIF     O   ON O.CODOBLIGPIF  = NS1.CODOBLIGPIF
    LEFT JOIN NPARTCODFISC PCF ON PCF.CODPART    = NS.CODPARTENER AND PCF.PRINCIPAL = 1
    LEFT JOIN NPARTB       PB  ON PB.CODPART     = NS.CODPARTENER AND PB.IMPLICIT   = 1
    LEFT JOIN NBANK        BP  ON BP.CODBANK     = PB.CODBANK' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sertar_setparams</obj_name>
  <obj_hashval>5a5cb80dc1adaf130c779f8ce4438efd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sertar_setparams(poricedata numeric, pdataini character varying, pdatafin character varying, pdepus0 numeric, pdefalcat numeric, pcodjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDataIni    DATE;
  vDataFin    DATE;
begin
  vDataIni := to_date(pDataIni,'dd.mm.yyyy');
  vDataFin := to_date(pDataFin,'dd.mm.yyyy');
  perform set_config('PKG_LIST_BASE_SERTAR.vOriceData', pOriceData::varchar, false);

  IF current_setting('PKG_LIST_BASE_SERTAR.vOriceData', true)::numeric = 0 THEN
    perform set_config('PKG_LIST_BASE_SERTAR.vDataIni', vDataIni::varchar, false);
    perform set_config('PKG_LIST_BASE_SERTAR.vDataFin', vDataFin::varchar, false);
  ELSE
    perform set_config('PKG_LIST_BASE_SERTAR.vDataIni', '',false);
    perform set_config('PKG_LIST_BASE_SERTAR.vDataFin', '', false);
  END IF;

  IF  pCodJob1 &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1, current_setting('PKG_LIST_BASE_SERTAR.vDataIni', true), current_setting('PKG_LIST_BASE_SERTAR.vDataFin', true), vAnLunaIni, vAnLunaFin);
  END IF;

  IF current_setting('PKG_LIST_BASE_SERTAR.vOriceData', true)::numeric = 1 THEN
    perform set_config('PKG_LIST_BASE_SERTAR.vPerioada', '', false);
  ELSIF current_setting('PKG_LIST_BASE_SERTAR.vDataIni', true) = current_setting('PKG_LIST_BASE_SERTAR.vDataFin', true) THEN
    perform set_config('PKG_LIST_BASE_SERTAR.vPerioada', '= TO_DATE('''||to_char(vDataIni,'yyyy.mm.dd')||''',''yyyy.mm.dd'')', false);
  ELSE
    perform set_config('PKG_LIST_BASE_SERTAR.vPerioada', 'BETWEEN TO_DATE('''||to_char(vDataIni,'yyyy.mm.dd')||''',''yyyy.mm.dd'') AND TO_DATE('''||to_char(vDataFin,'yyyy.mm.dd')||''',''yyyy.mm.dd'')', false);
  END IF;

  perform set_config('PKG_LIST_BASE_SERTAR.vDepus0'  , pDepus0::varchar  , false);
  perform set_config('PKG_LIST_BASE_SERTAR.vDefalcat', pDefalcat::varchar, false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sim406_processlist</obj_name>
  <obj_hashval>a153c4ada00efa5355d84d4ffe213bf9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sim406_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC        RECORD;
  sInsert     varchar;
  sSelect     varchar;
  condS       VARCHAR(1000);
  condSubunitHolding  VARCHAR(1000);
  gSuplCols   varchar := 'TAXDECL TXDCL, NCONT ncnt, NARTOBJ nobj, NART art, NUM1 um';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  anLucru     numeric;
  alStart     numeric;
  alStop      numeric;
BEGIN
  --Florin 28.08.2025 - sinc. Oracle
  --Florin 10.10.2024 - sinc. Oracle
  --Florin 19.09.2024 - fixat 63413
  --Florin 18.09.2024 - sinc. Oracle
  --Bogdan 26.09.2023 - 59531 - Simulare D406 SAF-T: diminuari
  --Florin 27.07.2023 - sinc. Oracle
  --Florin 18.07.2023 - sinc. Oracle
  --Bogdan 30.08.2022 55387 Lista Simulare D406 - compensari
  --Bogdan 18.07.2022 54911 Lista Simulare D406 - coloana noua Denumire Taxcode
  --Bogdan 07.05.2022 54801 SAF-T: Lista Simulare D406 - note contabile
  --Bogdan 06.05.2022 54081 Lista Simulare D406: de adaugat coloanele "Rand D300", "Procent taxa", "Tip taxa" din Winmadmin.TAXCODESAFT aferent Taxcode-ului din TAXDECL.
  --Bogdan 26.04.2022 53998 Lista Simulare D406: de adaugat coloana Partener, Cod fiscal
  --Bogdan 31.03.2021 53844 Lista Simulare D406 SAF-T: de adaugat o coloana noua "Corespondent rand D300"
  --Bogdan 31.03.2021 53701 Lisa noua Simulare D406 SAf-T - documente sursa pentru Taxcode
  condSubunitHolding := '';
  IF fnc_getvalconstantalucru('Holding')::NUMERIC = 1 THEN
    condS := PKG_LIST_BASE_UTILS_COND_SUBUNIT('dcs','subunit', '');
    if conds is not null THEN
      condSubunitHolding := ' AND ((' || condS || ') OR (dcs.subunit IS NULL))';
    END IF;
  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_SIM406.gSuplCols', gSuplCols, false);

  anLucru := getanlucru();
  alStart := anLucru * 12 + current_setting('PKG_LIST_SELECTLUNA.vLunaStart', true)::numeric;
  alStop  := anLucru * 12 + current_setting('PKG_LIST_SELECTLUNA.vLunaFin', true)::numeric;

  sInsert := '
    INSERT INTO ' || tmpName || '(
      NAV_TipDoc, NAV_CodDoc, TAXCODE, DEN_TAXCODE, TAXBASE, TAXVAL, TIPDOC_STR, MODIF_MANUAL, SIMBOL_CONT, DEN_CONT,
                       ESTE_IMPOZIT, NRDOC, DATADOC, AN, LUNA, DEN_ARTICOL, PU, CANT, DEN_UM1, CURS, VALOARE, RANDD300, den_part, codfiscal,
                       proctaxa, tiptaxa, COD_SUBUNIT, DEN_SUBUNIT '||gUserFields||' )';
  sSelect := '                 with din_iesiri as
                 (select txIes.CODTAXDECL,
                         ies.CODIES as coddoc,
                         ies.NRDOC,
                         ies.DATADOC,
                         ies.AN,
                         ies.LUNA,
                         ies1.CODOBIECT,
                         ies1.CANT,
                         ies1.UMSEC,
                         ies1.pretorig * ies1.coefdiscmaj as pret,
                         ies.curs,
                         ies.partener as codpart,
                         1 as signValue,
                         ies.subunitatea as subunit
                    from TAXDECL txIes
                    join IESIRI ies
                      on ies.CODIES = txIes.CODDOC
                     and ies.TIPDOC = txIes.TIPDOC
                    join IESIRI1 ies1
                      on ies1.CODIES1 = txIes.CODDOC1
                   where txIes.Tipdoc in (14, 19, 20, 21, 26)),
                din_intrari as
                 (select txIntr.CODTAXDECL,
                         intr.CODINTR as coddoc,
                         intr.NRDOC,
                         intr.DATADOC,
                         intr.AN,
                         intr.LUNA,
                         intr1.CODOBIECT,
                         intr1.CANT,
                         intr1.UMSEC,
                         intr1.pretorig * intr1.coefdiscmaj as pret,
                         intr.CURS,
                         intr.partener as codpart,
                         1 as signValue,
                         intr.subunitatea as subunit
                    from TAXDECL txIntr
                    join INTRARI intr
                      on intr.CODINTR = txIntr.CODDOC
                     and intr.TIPDOC = txIntr.TIPDOC
                    join INTRARI1 intr1
                      on intr1.CODINTR1 = abs(txIntr.CODDOC1)
                   where txIntr.Tipdoc in (1, 2, 3, 4, 5, 9)),
                din_monetare as
                 (select txMon.CODTAXDECL,
                         ies.CODIES as coddoc,
                         ies.NRDOC,
                         ies.DATADOC,
                         ies.AN,
                         ies.LUNA,
                         null::numeric             as CODOBIECT,
                         null::numeric             as CANT,
                         null::numeric             as UMSEC,
                         null::numeric             as pret,
                         ies.curs         as CURS,
                         ies.partener     as codpart,
                         1 as signValue,
                         ies.subunitatea as subunit
                    from TAXDECL txMon
                    join IESIRI ies
                      on ies.CODIES = txMon.CODDOC
                     and ies.TIPDOC = txMon.TIPDOC
                   where txMon.Tipdoc in (16)),
                din_trezor as
                (select txTrz.CODTAXDECL,
                         trz1.CODTREZOR as coddoc,
                         trz1.NRDOC,
                         trz1.DATADOC,
                         trz1.AN,
                         trz1.LUNA,
                         null ::numeric            as CODOBIECT,
                         null::numeric            as CANT,
                         null::numeric             as UMSEC,
                         null::numeric             as pret,
                         trz1.curs,
                         trz1.codpart     as codpart,
                         1 as signValue,
                         trz.subunitatea as subunit
                    from TAXDECL txTrz
                    join TREZOR1 trz1
                      on trz1.Codtrezor1 = txTrz.CODDOC
                    left join trezor trz on trz1.codtrezor = trz.codtrezor
                   where txTrz.Tipdoc in (29,30,33)),
                din_nc as
                (select txTrz.CODTAXDECL,
                         nca.codnc as coddoc,
                         nca.NRDOC,
                         nca.DATADOC,
                         nca.AN,
                         nca.LUNA,
                         null ::numeric   as CODOBIECT,
                         null ::numeric   as CANT,
                         null ::numeric   as UMSEC,
                         null ::numeric   as pret,
                         nca.curs         as CURS,
                         nca.part         as codpart,
                         1 as signValue,
                         nca.subunitatea as subunit
                    from TAXDECL txTrz
                    join NC nca
                      on nca.codnc = txTrz.CODDOC
                   where txTrz.TIPDOC in (35)),
                din_compensari as
                (select txTrz.CODTAXDECL,
                         cmp.CODCOMPENS as coddoc,
                         cmp.NRDOC,
                         cmp.DATADOC,
                         cmp.AN,
                         cmp.LUNA,
                         null ::numeric as CODOBIECT,
                         null ::numeric as CANT,
                         null ::numeric as UMSEC,
                         null ::numeric as pret,
                         null ::numeric  as CURS,
                         null ::numeric  as codpart,
                         1 as signValue,
                         cmp.subunitatea as subunit
                    from TAXDECL txTrz
                    join compens cmp
                      on cmp.CODCOMPENS = txTrz.CODDOC
                   where txTrz.TIPDOC in (28)),
                all_docs as
                 (select *
                    from din_iesiri
                  union all
                  select *
                    from din_intrari
                  union all
                  select *
                    from din_monetare
                  union all
                  select *
                    from din_trezor
                  union all
                  select *
                    from din_nc
                  union all
                  select *
                    from din_compensari)
                select txdcl.TIPDOC,
                       dcs.CODDOC,
                       txdcl.TAXCODE,
                       ntax.DENUMIRE,
                       txdcl.TAXBASE * dcs.signValue,
                       txdcl.TAXVAL * dcs.signValue,
                       case txdcl.TIPDOC when  1 then ''Intrari pe factura''
                                         when  2 then ''Intrari pe aviz''
                                         when  3 then ''Intrari pe chitanta/bon fiscal''
                                         when  4 then ''Intrari de la persoane fizice''
                                         when  5 then ''Intrari din import''
                                         when  9 then ''Intrari pe factura la aviz''
                                         when 14 then ''Diminuari de stoc''
                                         when 16 then ''Monetare''
                                         when 19 then ''Iesiri pe factura''
                                         when 20 then ''Iesiri pe aviz''
                                         when 21 then ''Iesiri pe chitanta/bon fiscal''
                                         when 26 then ''Iesiri pe factura la aviz''
                                         when 28 then ''Compensari''
                                         when 29 then ''Casa''
                                         when 30 then ''Banca''
                                         when 33 then ''Justificare decont''
                                         when 35 then ''Note contabile''
                                else '''' end :: varchar as TIPDOC_STR,
                       case when coalesce(txdcl.MANUAL,0) = 0 then ''Nu'' else ''Da'' end :: varchar,
                       ncnt.SIMBOL,
                       ncnt.DEN_CONT,
                       case when coalesce(ncnt.IMPOZIT,0) = 0 then ''Nu'' else ''Da'' end :: varchar,
                       dcs.NRDOC,
                       dcs.DATADOC,
                       dcs.AN,
                       dcs.LUNA,
                       art.DEN_ARTICOL,
                       case when coalesce(dcs.pret,0) &gt; 0 then dcs.pret*coalesce(um.paritate,1) else 0 end as pret,
                       case when coalesce(dcs.CANT,0) &gt; 0 then dcs.CANT/coalesce(um.paritate,1) else 0 end as cantitate,
                       um.DEN_UM1,
                       dcs.CURS ,
                       coalesce(dcs.pret,0) * coalesce(dcs.CANT,0) * coalesce(dcs.CURS,1) as Valoare,
                       txcds.RANDD300,
                       part.den_part, cf.codfiscal,
                       txcds.proctaxa, txcds.tiptaxa,
                       dcs.subunit,
                       nsub.den_subunit '
                ||gUserAlias||
                ' from TAXDECL txdcl
                  left join winmadmin.taxcodesaft ntax on ntax.cod = txdcl.TAXCODE
                  join NCONT ncnt
                    on ncnt.CODCONT = txdcl.CODCONT
                  left join all_docs dcs
                    on dcs.CODTAXDECL = txdcl.CODTAXDECL
                  left join NARTOBJ nobj
                    on nobj.CODOBIECT = dcs.CODOBIECT
                  left join NART art
                    on art.CODARTICOL = nobj.CODARTICOL
                  left join NUM1 um
                    on um.CODUM1 = dcs.UMSEC
                  left join npart part
                    on part.codpart = dcs.codpart
                  left join npartcodfisc cf
                    on cf.codpart = part.codpart
                    and cf.principal = 1
                  left join winmadmin.taxcodesaft txcds
                    on txcds.cod = txdcl.taxcode
                  left join  nsubunit nsub on nsub.codsubunit = dcs.subunit'
                ||gSuplJoins||
                ' WHERE ANLUNA  BETWEEN '||alStart||' AND '||alStop||' '||condSubunitHolding||' ';
  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_sim406_setjoinuri</obj_name>
  <obj_hashval>50189f3936660e8f96fb80de2eaf12a8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sim406_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 31.03.2021 53701 Lisa noua Simulare D406 SAf-T - documente sursa pentru Taxcode
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_SIM406.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_simulamo_processlist</obj_name>
  <obj_hashval>a4c93ea98019434e17e122ac0abee15d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_simulamo_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;
  vAn         NUMERIC := (SELECT PKG_LIST_BASE_SELANLUNAREF_AN.WME_RESULT   FROM PKG_LIST_BASE_SELANLUNAREF_AN (NULL,NULL));
  vLuna       NUMERIC := (SELECT PKG_LIST_BASE_SELANLUNAREF_LUNA.WME_RESULT FROM PKG_LIST_BASE_SELANLUNAREF_LUNA (NULL,NULL));
begin
  --Bogdan 21.09.2020
  gSuplCols := 'MIFIX MF, MIFIX1 MF1, MFCLASIF MFC, NIRSTOC NS, NIR NIR, NGEST NG, NARTOBJ NAO, NGEST NG_S, NGEST NG_D, NPART PC, NPART FURN, NLOCATII L, NARTAMB AA, CENTRECOST CC, NIRSER NSER, NSERII SER, FISAMF FMF';

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

  sInsert := 'INSERT INTO '|| TMPNAME|| '(
            CODMIFIX,
            CODNIRSTOC,
            DENMIFIX,
            CANT,
            NRINVENTAR,
            DEN_UM1,
            DEN_IOART,
            DENCLASA,
            SIMBOLCLASA,
            DEN_GEST,
            DEN_SUBUNIT,
            CODINTERN,
            CODEXTERN,
            FURNIZOR,
            OBSMIFIX,
            CentruCost,
            PretInc,
            PretInitial,
            AN,
            LUNA,
            AE,
            AG'
            || coalesce (gUserFields ,'')
            || ')
        SELECT mfs.codmifix,
          mfs.codnirstoc,
          obj.denumire DENMIFIX,
          mfs.cant,
          mf.nrinventar,
          u1.den_um1,
          io.den_ioart,
          mfc.denumire DENCLASA,
          mfc.simbol   SIMBOLCLASA,
          ng.den_gest,
          sub.den_subunit,
          OBJ.CODINTERN,
          OBJ.CODEXTERN,
          FURN.DEN_PART FURNIZOR,
          mf.obs        obsmifix,
          cc.denumire   CentruCost,
          CASE WHEN mfs.PretVechi = 0 THEN nso.Pret - nso.Adaos ELSE mfs.PretVechi END PretInc,
          nso.pret PretInitial,
          mfs.AnStart,
          mfs.LunaStart,
          mfs.amo - Lag (mfs.amo, 1, 0::numeric) OVER (Partition by MFS.CODMIFIX ORDER BY mfs.AnStart, mfs.LunaStart) AE,
          mfs.amog - Lag (mfs.amog,1,0::numeric) OVER (Partition by MFS.CODMIFIX ORDER BY mfs.AnStart, mfs.LunaStart) AG '
            || coalesce (gUserAlias ,'')|| '
        FROM mifix1_simulare   mfs
          LEFT JOIN mifix      mf   ON mfs.codmifix   = mf.codmifix
          LEFT JOIN nirstoc    ns   ON mfs.codnirstoc = ns.codnirstoc
          LEFT JOIN nartobj    obj  ON obj.codobiect  = ns.codobiect
          LEFT JOIN num1       u1   ON u1.codum1      = ns.umsec
          LEFT JOIN ioart      io   ON ns.codioart    = io.codioart
          LEFT JOIN mfclasif   mfc  ON mfc.codclasif  = mfs.codclasif
          LEFT JOIN nir        n    ON n.codnir       = ns.codnir
          LEFT JOIN ngest      ng   ON ng.codgest     = n.gest
          LEFT JOIN nsubunit   sub  ON sub.codsubunit = ng.codsubunit
          LEFT JOIN npart      furn ON furn.codpart   = ns.furn
          LEFT JOIN centrecost cc   ON cc.codcentru   = mfs.codcentru
          LEFT JOIN nirstoc1   ns1  on ns1.codnirstoc = ns.codnirstoc
          LEFT JOIN nirstoc    nso  on nso.codnirstoc = ns1.codnirstocorig'
            || coalesce (gSuplJoins ,'')|| '
        WHERE
          1 = 1'
            || coalesce ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'NG', 'CODSUBUNIT',NULL,NULL)) ::varchar ,'');

  PERFORM pkg_inchideri_SIMULARE_AMORTIZARI (getAnLucru(), getLunaLucru(), vAn, vLuna);
  PERFORM LIST_EXECUTE_IMMEDIATE (sInsert, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE ('DELETE FROM '|| coalesce (TMPNAME,'')
        || ' WHERE an*12+luna &lt;= '|| coalesce ( ( (SELECT pkg_globals_AnLunaLucru.WME_RESULT FROM pkg_globals_AnLunaLucru (NULL,NULL))) ::varchar,'') , aListID, aListVer);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sinttrez_baga_dinamic_cols</obj_name>
  <obj_hashval>5f5c2890aaec34140e415b9b3f34ffc0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sinttrez_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  i     NUMERIC;
  oData DATE;
BEGIN
  --Adina 16.11.2020 modificat dupa Oracle
  i := 0;
  oData := date_trunc('day',to_date(current_setting('PKG_LIST_SELECTPERIOADA.vdataini', true),'dd.mm.yyyy')::date)::date;

  WHILE  oData &lt;= date_trunc('day',to_date(current_setting('PKG_LIST_SELECTPERIOADA.vdatafin', true),'dd.mm.yyyy')::date)::date LOOP
    i := i + 1;
    INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES('W'    || i::varchar,'SOLD_'    || To_Char(oData, 'DD.MM.YYYY'),i);
    INSERT INTO tmp_dinamic_cols(FieldName, Display, IndexLocal) VALUES('WLEI' || i::varchar,'SOLDLEI_' || To_Char(oData, 'DD.MM.YYYY'),i);
    oData := oData + 1;
  END LOOP;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sinttrezdet_processlist</obj_name>
  <obj_hashval>36f4fa4b98c857fb6b0a2fb371e5710c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sinttrezdet_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     TEXT;
  sSelect     TEXT;
  sFields     varchar;
  sAlias      varchar;
  oData       date;
  i           numeric;
  gSuplCols   varchar :=  'nmonede m, nbankcont bc, nbank b, ncont nc, nsubunit sub'  ;
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Stef 19.10.2023
  CALL create_wm_temps_flag('TMP_SINTTREZ');
  call pkg_list_struct_StartSuplCols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'trezor1', 't1', 't1.codtrezor1 = stt.coddoc1'                          , 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'trezor',  't',  't.codtrezor   = stt.coddoc  AND t.tipdoc = stt.tipdoc', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'iesiri',  'i',  'i.codies      = stt.coddoc  AND i.tipdoc = stt.tipdoc', 1);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_SINTTREZDET.gSuplCols',gSuplCols,false);

  PERFORM PKG_LIST_BASE_SINTTREZ_TMPPrepare();
  CALL PRC_AL_CHECK('nbankcont1',0);
  CALL PRC_AL_CHECK('iobank1',0);

  sInsert :=
  'INSERT INTO '||tmpName||'(
    NAV_TipDoc,  NAV_CodDoc,  NAV_CodDoc1,
    Ordine,
    AnLuna, An,
    Luna,
    Banca, Cont, NrCont, Moneda, Document,
    SoldInit,    Incasari,    Plati,    SoldFin,
    SoldInitLEI, IncasariLEI, PlatiLEI, DifRegLEI, SoldFinalLEI,
    ContReprez, DataDoc, Subunitate, CodBankCont, Explicatii'||gUserFields||' )';

  sSelect := '
  SELECT
    STT.TIPDOC, STT.CODDOC, STT.CODDOC1,
    CASE WHEN STT.TIPDOC = 0 THEN 0 ELSE 1 END Ordine,
    stt.an*12+stt.luna anluna, stt.an,
    CASE stt.luna
      WHEN  1 THEN ''01 - Ianuarie''
      WHEN  2 THEN ''02 - Februarie''
      WHEN  3 THEN ''03 - Martie''
      WHEN  4 THEN ''04 - Aprilie''
      WHEN  5 THEN ''05 - Mai''
      WHEN  6 THEN ''06 - Iunie''
      WHEN  7 THEN ''07 - Iulie''
      WHEN  8 THEN ''08 - August''
      WHEN  9 THEN ''09 - Septembrie''
      WHEN 10 THEN ''10 - Octombrie''
      WHEN 11 THEN ''11 - Noiembrie''
      WHEN 12 THEN ''12 - Decembrie''
    END luna,
    b.simbol banca, bc.den_cont cont, bc.nrcont, m.simbol moneda, stt.document,
    stt.soldin,    stt.incasari,    stt.plati,    0 soldfin,
    stt.soldinlei, stt.incasarilei, stt.platilei,
    0 DifRegLei,
    0 soldfinlei,
    nc.simbol, stt.datadoc, sub.den_subunit, bc.codbankcont, stt.explicatii '||gUserAlias||'
  FROM tmp_stt stt
    LEFT JOIN nbankcont  bc   ON bc.codbankcont  = stt.codbankcont
    LEFT JOIN nmonede    m    ON m.codmoneda     = bc.codmoneda
    LEFT JOIN nbank      b    ON b.codbank       = bc.codbank
    LEFT JOIN nbankcont1 bc1  ON bc1.codbankcont = bc.codbankcont and stt.an*12+stt.luna between  bc1.Alstart and  bc1.Alstop
    LEFT JOIN iobank1    iob1 ON iob1.codiobank  = bc1.codiobanca and stt.an*12+stt.luna between iob1.Alstart and iob1.Alstop
    LEFT JOIN ncont      nc   ON nc.codcont      = iob1.cont
    LEFT JOIN tmp_sttreg cr   ON cr.codmoneda    = bc.codmoneda AND cr.luna = stt.luna AND cr.an = stt.an AND Coalesce(bc.farareg, 0) = 0
    LEFT JOIN nsubunit   sub  ON sub.codsubunit  = bc.subunitatea '||
    gSuplJoins;

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

  sSelect := '
  SELECT
    STT.TIPDOC, STT.CODDOC, STT.CODDOC1,
    2 Ordine,
    stt.an*12+stt.luna anluna, stt.an,
    CASE stt.luna
      WHEN  1 THEN ''01 - Ianuarie''
      WHEN  2 THEN ''02 - Februarie''
      WHEN  3 THEN ''03 - Martie''
      WHEN  4 THEN ''04 - Aprilie''
      WHEN  5 THEN ''05 - Mai''
      WHEN  6 THEN ''06 - Iunie''
      WHEN  7 THEN ''07 - Iulie''
      WHEN  8 THEN ''08 - August''
      WHEN  9 THEN ''09 - Septembrie''
      WHEN 10 THEN ''10 - Octombrie''
      WHEN 11 THEN ''11 - Noiembrie''
      WHEN 12 THEN ''12 - Decembrie''
    END luna,
    b.simbol banca, bc.den_cont cont, bc.nrcont, m.simbol moneda, ''Sold final'' as document,
    0 soldin, 0 incasari, 0 plati, stt.soldin + (stt.incasari - stt.plati) * CASE WHEN Coalesce(bc.credit,0) = 0 THEN 1 ELSE -1 END soldfin,
    0 soldinlei, 0 incasarilei, 0 platilei,
    CASE
      WHEN cr.curs IS NULL then 0
      ELSE (stt.soldin    + (stt.incasari    - stt.plati   ) * CASE WHEN Coalesce(bc.credit,0) = 0 THEN 1 ELSE -1 END) * cr.curs -
           (stt.soldinlei + (stt.incasarilei - stt.platilei) * CASE WHEN Coalesce(bc.credit,0) = 0 THEN 1 ELSE -1 END)
    END DifRegLei,
    CASE
      WHEN cr.curs IS NULL
      THEN  stt.soldinlei + (stt.incasarilei - stt.platilei) * CASE WHEN Coalesce(bc.credit,0) = 0 THEN 1 ELSE -1 END
      ELSE (stt.soldin    + (stt.incasari    - stt.plati   ) * CASE WHEN Coalesce(bc.credit,0) = 0 THEN 1 ELSE -1 END) * cr.curs
    END soldfinlei,
    nc.simbol, stt.datadoc, sub.den_subunit, bc.codbankcont, '''' explicatii '||gUserAlias||'
  FROM (
    SELECT
      an, luna, codbankcont,
      0 tipdoc, 0 coddoc, 0 coddoc1, 0 indexlocal, Max(datadoc) datadoc,
      sum(incasari)    incasari,    sum(plati)    plati,    sum(soldin)    soldin,
      sum(incasarilei) incasarilei, sum(platilei) platilei, sum(soldinlei) soldinlei
    FROM tmp_stt
    GROUP BY an, luna, codbankcont
  ) stt
    LEFT JOIN nbankcont  bc   ON bc.codbankcont  = stt.codbankcont
    LEFT JOIN nmonede    m    ON m.codmoneda     = bc.codmoneda
    LEFT JOIN nbank      b    ON b.codbank       = bc.codbank
    LEFT JOIN nbankcont1 bc1  ON bc1.codbankcont = bc.codbankcont and stt.an*12+stt.luna between  bc1.Alstart and  bc1.Alstop
    LEFT JOIN iobank1    iob1 ON iob1.codiobank  = bc1.codiobanca and stt.an*12+stt.luna between iob1.Alstart and iob1.Alstop
    LEFT JOIN ncont      nc   ON nc.codcont      = iob1.cont
    LEFT JOIN tmp_sttreg cr   ON cr.codmoneda    = bc.codmoneda AND cr.luna = stt.luna AND cr.an = stt.an AND Coalesce(bc.farareg, 0) = 0
    LEFT JOIN nsubunit   sub  ON sub.codsubunit  = bc.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_sinttrezdet_setjoinuri</obj_name>
  <obj_hashval>54545aad6baa734be7d4905aed162dc8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sinttrezdet_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 02.03.2021
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_SINTTREZDET.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitaccrualls_cond</obj_name>
  <obj_hashval>2316cda57b12053724e9a0cc66b9e71b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitaccrualls_cond(vtabelas character varying, vcamppart character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sCond varchar;
BEGIN
  --Stef 25.01.2021
  --Florin 03.01.2021 - fixat 42711
  sCond := PKG_LIST_BASE_UTILS_COND_SUBUNIT(vTabelaS);
  IF NOT (PKG_LIST_SELPARTART_IsAllPart()) THEN
    sCond := COALESCE(sCond, '')||'
        AND '||COALESCE(vCampPart, '')||' IN (SELECT VALOARE::numeric 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_sitaccrualls_exprcurs</obj_name>
  <obj_hashval>698c95a2072a8b086bc0198d12b19d1a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitaccrualls_exprcurs(palias character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sResuls varchar := '';
BEGIN
  --Stef 25.01.2021
  IF PKG_LIST_SELPARTART_IsExtra1() THEN
    sResuls := '*Coalesce(NullIF('||coalesce(pAlias, '')||'.curs,0),1)';
  END IF;
  RETURN sResuls;
END;
$function$
</obj_text>
</row>

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

  sInsert  varchar;
  sSelect1 varchar;
  sSelect2 varchar;
BEGIN
  --Bogdan 08.09.2020
  --Florin 03.02.2021 - fixat 42711
  gSuplCols := 'npart p, nartobj nao, nart na, nclasea ca, nclasedisc clsd';

  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_SITACCRUALLS.gSuplCols',gSuplCols,false);

  sInsert :=
  'INSERT INTO '||tmpName||' (
    Part, Art, ClasaA, Subunit,
    Categ,
    ValStart,
    ValStop,
    Disc,
    ProcDisc, BazaDisc, ValDisc, ValIncDec,
    PlataDoc, PlataVal, RestDisc,
    ValDiscFin, ValIncDecFin, PlataValFin, Moneda '||COALESCE(gUserFields ,'')||')';

  sSelect1 := '
  SELECT
    p.Den_Part Part, nao.Denumire Art, ca.Den_Clasea ClasaA, sub.Den_Subunit Subunit,
    ''OnnInvoice'' Categ,
    NULL ValStart,
    NULL ValStop,
    CASE
      WHEN tmp.codcriteriu &lt;&gt; 0 THEN cd.DenCriteriu
      WHEN Sign(tmp.proc) &gt; 0 THEN ''Majorare direct pe cont ''||c.simbol
      ELSE ''Discount direct pe cont ''||c.simbol
    END Disc,
    tmp.Proc ProcDisc, tmp.BazaDisc, tmp.ValDisc, NULL ValIncDec,
    NULL PlataDoc, NULL PlataVal, NULL RestDisc, tmp.valdiscfin, NULL ValIncDecFin, null PlataValFin, MON.SIMBOL Moneda '||COALESCE(gUserAlias ,'')||'
  FROM tmp_list_sitoninv   tmp
    LEFT JOIN NMONEDE      MON  ON TMP.CODMONEDA     = MON.CODMONEDA
    LEFT JOIN npart        p    ON p.codpart         = tmp.codpart
    LEFT JOIN nartobj      nao  ON nao.codobiect     = tmp.codobiect
    LEFT JOIN nart         na   ON na.codarticol     = nao.codarticol
    LEFT JOIN nclasea      ca   ON ca.codclasea      = na.clasa
    LEFT JOIN nsubunit     sub  ON sub.codsubunit    = tmp.subunitatea
    LEFT JOIN criteriidisc cd   ON cd.codcriteriu    = tmp.codcriteriu
    LEFT JOIN nclasedisc   clsd ON clsd.codclasedisc = cd.clasa
    LEFT JOIN ncont        c    ON c.codcont         = tmp.codcont'||
    COALESCE(gSuplJoins ,'');

  sSelect2 := '
  WITH x AS ('||
    pkg_list_base_sitaccrualls_ViewX(current_setting('PKG_LIST_SELPARTART.gAnLunaIni', TRUE)::NUMERIC, current_setting('PKG_LIST_SELPARTART.gAnLunaFin', TRUE)::NUMERIC)||'
  ),
  xfin AS ('||
    pkg_list_base_sitaccrualls_ViewX(current_setting('PKG_LIST_SELPARTART.gAnLunaFin', TRUE)::NUMERIC, current_setting('PKG_LIST_SELPARTART.gAnLunaFin', TRUE)::NUMERIC)||'
  )
  SELECT
    p.Den_Part Part, nao.Denumire Art, ca.Den_Clasea ClasaA, sub.Den_Subunit Subunit,
    CASE WHEN x.coddiscount = 0 THEN ''Volum'' WHEN cd.offinvoice = 3 THEN ''BillBack'' WHEN cd.offinvoice = 2 THEN ''NC'' ELSE ''OffInvoice'' END Categ,
    (SELECT Min(cd1.datastart) FROM criteriidisc1 cd1, discount d, discinterval di WHERE di.procent = x.Procent AND d.coddiscount = x.coddiscount AND d.codcriteriu1 = cd1.codcriteriu1 AND di.coddiscount = d.coddiscount) ValStart,
    NULL ValStop,
    cd.DenCriteriu Disc,
    x.Procent ProcDisc, x.BazaDisc, x.ValDisc, x.ValIncDec,
    tmp.Doc PlataDoc, CASE WHEN cd.offinvoice = 3 THEN -1 ELSE 1 END * tmp.Val PlataVal, x.ValDisc-Coalesce(tmp.Val,0) RestDisc,
    xfin.ValDisc ValDiscFin, xfin.ValIncDec ValIncDecFin, CASE WHEN cd.offinvoice = 3 THEN -1 ELSE 1 END * tmf.val PlataValFin, mon.simbol Moneda '||gUserAlias||'
  FROM x
    left join xfin              on x.partener        = xfin.partener and x.subunitatea = xfin.subunitatea and x.procent = xfin.procent and x.coddiscount = xfin.coddiscount
    LEFT JOIN nmonede      mon  on mon.codmoneda     = x.codmoneda
    LEFT JOIN npart        p    ON p.codpart         = x.partener
    LEFT JOIN nartobj      nao  ON nao.codobiect     = x.partener - x.partener
    LEFT JOIN nart         na   ON na.codarticol     = nao.codarticol
    LEFT JOIN nclasea      ca   ON ca.codclasea      = na.clasa
    LEFT JOIN nsubunit     sub  ON sub.codsubunit    = x.subunitatea
    LEFT JOIN discount     d    ON d.coddiscount     = x.coddiscount
    LEFT JOIN criteriidisc cd   ON cd.codcriteriu    = d.codcriteriu
    LEFT JOIN nclasedisc   clsd ON clsd.codclasedisc = cd.clasa
    LEFT JOIN ncont        c    ON c.codcont         = x.partener - x.partener
    LEFT JOIN (
      SELECT
        partener, procent, coddiscount, offinvoice,
        fnc_array_to_vc3200(ARRAY_AGG(PrefixDoc||'' ''||nrdoc||'' ''||to_char(DataDoc,''dd.mm.yyyy''))) Doc,
        SUM(Plata) Val, codmoneda
      FROM tmp_platiaccrualls
      where filtru = ''PER''
      GROUP BY partener, procent, coddiscount, offinvoice, codmoneda
    ) tmp ON tmp.partener = x.partener AND tmp.procent = x.procent AND tmp.coddiscount = x.coddiscount and tmp.codmoneda = x.codmoneda AND tmp.offinvoice = Coalesce(cd.offinvoice, -1)
    LEFT JOIN (
      SELECT
        partener, procent, coddiscount, offinvoice,
        fnc_array_to_vc3200(ARRAY_AGG(PrefixDoc||'' ''||nrdoc||'' ''||to_char (DataDoc,''dd.mm.yyyy''))) Doc,
        SUM(Plata) Val, codmoneda
      FROM tmp_platiaccrualls
      where filtru = ''INI''
      GROUP BY partener, procent, coddiscount, offinvoice, codmoneda
    ) tmf ON tmf.partener = x.partener AND tmf.procent = x.procent AND tmf.coddiscount = x.coddiscount and tmf.codmoneda = x.codmoneda AND tmf.offinvoice = Coalesce(cd.offinvoice, -1)'||
    COALESCE(gSuplJoins ,'');
  PERFORM PKG_LIST_BASE_SITONINV_UmpleTmp (FALSE);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert||sSelect1, aListID, aListVer);

  IF PKG_LIST_SELPARTART_IsAllArt() THEN
    PERFORM pkg_list_base_sitaccrualls_umpleTmpPlati ( PKG_LIST_SELPARTART_AnLunaIni() , PKG_LIST_SELPARTART_AnLunaFin() , 'PER', 1);
    PERFORM pkg_list_base_sitaccrualls_umpleTmpPlati ( PKG_LIST_SELPARTART_AnLunaFin() , PKG_LIST_SELPARTART_AnLunaFin() , 'INI', 0);
    PERFORM LIST_EXECUTE_IMMEDIATE (coalesce (sInsert,'') || coalesce (sSelect2,'') , aListID, aListVer);
  END IF;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitaccrualls_umpletmpplati</obj_name>
  <obj_hashval>dc4f99d22ae2a34abe6059dd2a512a79</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitaccrualls_umpletmpplati(aanlunaini numeric, aanlunafin numeric, afiltru character varying, cutruncate numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsTMP     TEXT;
  sCondTmp    VARCHAR := PKG_LIST_BASE_UTILS_COND_SUBUNIT('N');
  sALIni      VARCHAR := CURRENT_SETTING('PKG_LIST_SELPARTART.gAnLunaIni', TRUE)::VARCHAR;
  sALFin      VARCHAR := CURRENT_SETTING('PKG_LIST_SELPARTART.gAnLunaFin', TRUE)::VARCHAR;
BEGIN
  --STEF 26.01.2021
  --Florin 03.01.2021 - fixat 42711
  IF CuTruncate &lt;&gt; 0 THEN
    TRUNCATE TABLE tmp_platiaccrualls;
  END IF;

  IF NOT PKG_LIST_SELPARTART_IsAllPart () THEN
    sCondTmp := sCondTmp||'
      AND N.CODPART IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPART'')';
  END IF;

  IF PKG_LIST_SELPARTART_IsExtra2() THEN
    sCondTmp := sCondTmp||'
      AND Coalesce(N.INCHISA, 0) = 0';
  END IF;
  sInsTMP := '
  INSERT INTO tmp_platiaccrualls (PARTENER, PROCENT, CODDISCOUNT, OFFINVOICE, CODDOC, TIPDOC, PREFIXDOC, NRDOC, DATADOC, PLATA, ORDINE, MAXORD, FILTRU, CODMONEDA)
  WITH
  D(coddoc, tipdoc, prefixdoc, nrdoc, datadoc, offinvoice, val, curs) AS (
    SELECT i.codintr, i.tipdoc, i.prefixdoc, i.nrdoc, i.datadoc, 3 offinvoice, Sum(i1.pu*i1.cant'||PKG_LIST_BASE_SITACCRUALLS_ExprCurs('i')||') val, i.curs
    FROM (
      SELECT ANLUNASTART, ANLUNASTOP, VALOARE::NUMERIC AS artF
      FROM TMP_CONSTVAL_LST
      WHERE SIMBOL = ''ARTDISCOFFINVOICEF'' AND Coalesce(VALOARE, ''0'') &lt;&gt; ''0''
    ) da
      INNER JOIN intrari1 i1 ON i1.codobiect = da.artF
      LEFT  JOIN intrari  i  ON i.codintr    = i1.codintr
    WHERE i.an*12+i.luna BETWEEN da.ANLUNASTART AND da.ANLUNASTOP
    GROUP BY i.codintr, i.tipdoc, i.prefixdoc, i.nrdoc, i.datadoc, i.curs
    UNION ALL
    SELECT i.codies, i.tipdoc, i.prefixdoc, i.nrdoc, i.datadoc, 2 offinvoice, Sum(i1.pu*i1.cant'||PKG_LIST_BASE_SITACCRUALLS_ExprCurs('i')||') val, i.curs
    FROM (
      SELECT ANLUNASTART, ANLUNASTOP, VALOARE::NUMERIC AS artC
      FROM TMP_CONSTVAL_LST
      WHERE SIMBOL = ''ARTDISCOFFINVOICEF'' AND Coalesce(VALOARE, ''0'') &lt;&gt; ''0''
    ) da
      INNER JOIN iesiri1 i1 ON i1.codobiect = da.artC
      LEFT  JOIN iesiri  i  ON i.codies     = i1.codies
    WHERE i.an*12+i.luna BETWEEN da.ANLUNASTART AND da.ANLUNASTOP
    GROUP BY i.codies, i.tipdoc, i.prefixdoc, i.nrdoc, i.datadoc, i.curs),
  F AS (
    SELECT ncf.codncredit, d.coddoc, d.tipdoc, d.prefixdoc, d.nrdoc, d.datadoc, d.offinvoice, ncf.valdoc'||PKG_LIST_BASE_SITACCRUALLS_ExprCurs('d')||' val
    FROM d INNER JOIN notecreditfact ncf ON ncf.coddoc = d.coddoc AND ncf.tipdoc = d.tipdoc),
  Y AS (
    SELECT
      nc1.codncredit, n.codpart partener, cd.offinvoice,Coalesce(id.coddiscount,nc1.coddiscount) coddiscount, Coalesce(i.moneda, n.codmoneda, 0) codmoneda,
      Coalesce(id.procent,(SELECT Max(Procent) From discinterval di WHERE di.coddiscount = Coalesce(id.coddiscount,nc1.coddiscount)) ) Procent,
      Sum(Round(nc1.valoare'||PKG_LIST_BASE_SITACCRUALLS_ExprCurs('n')||',4)) v1,
      Sum(Sum(Round(nc1.valoare'||PKG_LIST_BASE_SITACCRUALLS_ExprCurs('n')||',4))) OVER (PARTITION BY nc1.codncredit, cd.offinvoice) v2
    FROM notecredit n
      INNER JOIN notecredit1  nc1 ON nc1.codncredit = n.codncredit
      LEFT  JOIN iesiri       i   ON i.codies       = nc1.codobligstins AND i.tipdoc = nc1.tipdoc
      LEFT  JOIN iesdisc      id  ON id.codiesdisc  = nc1.coddoc AND id.codies = i.codies AND id.offinvoice = CASE n.tipdoc WHEN 58 THEN 2 WHEN 59 THEN 3 ELSE 0 END
      LEFT  JOIN discount     d   ON d.coddiscount  = Coalesce(id.coddiscount,nc1.coddiscount)
      LEFT  JOIN criteriidisc cd  ON cd.codcriteriu = d.codcriteriu
    WHERE EXTRACT(YEAR FROM N.DATASTOP) *12 + EXTRACT(MONTH FROM N.DATASTOP) &gt;= '||sALIni||'
      AND EXTRACT(YEAR FROM N.DATASTART)*12 + EXTRACT(MONTH FROM N.DATASTART)&lt;= '||sALFin||
      sCondTmp||'
      AND nc1.tip = 5
    GROUP BY nc1.codncredit, n.codpart, cd.offinvoice, id.coddiscount,nc1.coddiscount, id.procent, i.moneda, n.codmoneda)
  SELECT
    y.partener, y.procent, y.coddiscount, f.offinvoice, f.coddoc, f.tipdoc, f.prefixdoc, f.nrdoc, f.datadoc,
    Round(Sum(case when y.v2 = 0 then f.val else f.val*y.v1/y.v2 end),2) plata,
    ROW_NUMBER() OVER (PARTITION BY y.partener, y.procent, y.coddiscount, f.offinvoice ORDER BY f.datadoc, f.nrdoc, f.coddoc) ordine,
    COUNT(1) OVER (PARTITION BY y.partener, y.procent, y.coddiscount, f.offinvoice) maxord, '''||aFiltru||''', Y.CODMONEDA
  FROM f INNER JOIN y ON y.codncredit = f.codncredit AND y.offinvoice = f.offinvoice
  GROUP BY y.partener, y.procent, y.coddiscount, f.offinvoice, f.coddoc, f.tipdoc, f.prefixdoc, f.nrdoc, f.datadoc, y.codmoneda';
  PERFORM PKG_LIST_BASE_UTILS_UMPLE_TMP_CONSTVAL_LST('ARTDISCOFFINVOICEC, ARTDISCOFFINVOICEF');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInstmp, 0, 0);

  sInsTMP := '
  INSERT INTO tmp_platiaccrualls (PARTENER, PROCENT, CODDISCOUNT, OFFINVOICE, CODDOC, TIPDOC, PREFIXDOC, NRDOC, DATADOC, PLATA, ORDINE, MAXORD, FILTRU, CODMONEDA)
  WITH
  D(coddoc, tipdoc, prefixdoc, nrdoc, datadoc, val, curs) AS (
    SELECT i.codintr coddoc, i.tipdoc, i.prefixdoc, i.nrdoc, i.datadoc, Sum(i1.pu*i1.cant'||PKG_LIST_BASE_SITACCRUALLS_ExprCurs('i')||') val, i.curs
    FROM (
      SELECT ANLUNASTART, ANLUNASTOP, VALOARE::NUMERIC AS artV
      FROM TMP_CONSTVAL_LST
      WHERE SIMBOL = ''ARTDISCPRIMVOL'' AND Coalesce(VALOARE, ''0'') &lt;&gt; ''0''
    ) da
      INNER JOIN intrari1 i1 ON i1.codobiect = da.artV
      LEFT  JOIN intrari  i  ON i.codintr    = i1.codintr
    WHERE i.an*12+i.luna BETWEEN da.ANLUNASTART AND da.ANLUNASTOP
    GROUP BY i.codintr, i.tipdoc, i.prefixdoc, i.nrdoc, i.datadoc, i.curs),
  F AS (
    SELECT ncf.codncredit, d.coddoc, d.tipdoc, d.prefixdoc, d.nrdoc, d.datadoc, ncf.valdoc'||PKG_LIST_BASE_SITACCRUALLS_ExprCurs('d')||' val
    FROM d INNER JOIN notecreditfact ncf ON ncf.coddoc = d.coddoc AND ncf.tipdoc = d.tipdoc),
  Y AS (
    SELECT
      nc1.codncredit, n.codpart partener, Coalesce(i.moneda, n.codmoneda, 0) codmoneda,
      Sum(Round(nc1.valoare'||PKG_LIST_BASE_SITACCRUALLS_ExprCurs('n')||',4)) v1,
      Sum(Sum(Round(nc1.valoare'||PKG_LIST_BASE_SITACCRUALLS_ExprCurs('n')||',4))) OVER (PARTITION BY nc1.codncredit) v2
    FROM notecredit n
      INNER JOIN notecredit1 nc1  ON nc1.codncredit = n.codncredit
      LEFT  JOIN IESIRI1     I1   ON I1.CODIES1     = NC1.CODDOC AND N.VOLUMPEARTICOLE = 1
      LEFT  JOIN IESIRI      I    ON I.CODIES       = CASE WHEN N.VOLUMPEARTICOLE = 1 THEN I1.CODIES ELSE NC1.CODDOC END
      LEFT  JOIN NOTECREDIT1 NC1X ON NC1X.CODNCREDIT1ORIG = NC1.CODNCREDIT1
    WHERE EXTRACT(YEAR FROM N.DATASTOP) *12 + EXTRACT(MONTH FROM N.DATASTOP) &gt;= '||sALIni||'
      AND EXTRACT(YEAR FROM N.DATASTART)*12 + EXTRACT(MONTH FROM N.DATASTART)&lt;= '||sALFin||'
      AND NC1.TIP = 2 AND N.IESIRIPEVOLUM = 1 AND NC1.VALOARE &lt;&gt; 0
      AND Coalesce(NC1.CODDOC, 0) &lt;&gt; 0
      AND Coalesce(N.CORECTIE,0) = 0
      AND NC1X.CODNCREDIT1 IS NULL '||
      sCondTmp||'
    GROUP BY nc1.codncredit, n.codpart, i.moneda, n.codmoneda)
  SELECT
    y.partener, 0 procent, 0 coddiscount, -1 offinvoice, f.coddoc, f.tipdoc, f.prefixdoc, f.nrdoc, f.datadoc,
    -Round(Sum(case when y.v2 = 0 then f.val else f.val*y.v1/y.v2 end),2) plata,
    ROW_NUMBER() OVER (PARTITION BY y.partener ORDER BY f.datadoc, f.nrdoc, f.coddoc) ordine,
    COUNT(1) OVER (PARTITION BY y.partener) maxord, '''||aFiltru||''', Y.CODMONEDA
  FROM f INNER JOIN y ON y.codncredit = f.codncredit
  GROUP BY y.partener, f.coddoc, f.tipdoc, f.prefixdoc, f.nrdoc, f.datadoc, y.codmoneda';

  PERFORM PKG_LIST_BASE_UTILS_UMPLE_TMP_CONSTVAL_LST('ARTDISCPRIMVOL');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInstmp, 0, 0);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitaccrualls_viewx</obj_name>
  <obj_hashval>bdbf295b3b92ee67a8955e728cf92c20</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitaccrualls_viewx(valini numeric, valfin numeric)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSql   VARCHAR;
  sALIni VARCHAR  := To_Char(vALIni, 'fm99999');
  sALFin VARCHAR  := To_Char(vALFin, 'fm99999');
BEGIN
  --Stef 25.01.2021
  sSql := '
    SELECT
      partener, subunitatea, coddiscount, codmoneda, procent, SUM(CASE WHEN Poz = 1 THEN BazaDisc ELSE 0 END) BazaDisc, Sum(CASE WHEN Poz = 1 THEN ValDisc ELSE 0 END) ValDisc,
      Sum(ValIncDec) ValIncDec
    FROM (
      SELECT
        CASE
          WHEN Coalesce(ID.CODOBIECT, 0) = 0 THEN 1
          ELSE Row_Number() OVER (PARTITION BY ID.CodIes, Coalesce(ID.CODOBIECT, 0), ID.CodDiscount ORDER BY ID.CodIes)
        END Poz,
        i.partener, i.subunitatea, id.coddiscount, Coalesce(i.moneda,0) codmoneda, id.procent,
        CASE
          WHEN Coalesce(ID.CODOBIECT, 0) = 0 THEN i.valdoc-i.tvadoc
          ELSE (SELECT Coalesce(Sum(i1.pretorig*i1.cant*Coalesce(i1.CoefDiscmaj,1)),0) FROM IESIRI1 I1 WHERE I1.CODIES = I.CODIES AND I1.CODOBIECT = ID.CODOBIECT)
        END'||PKG_LIST_BASE_SITACCRUALLS_ExprCurs('i')||' BazaDisc,
        Round(
          CASE
            WHEN Coalesce(ID.CODOBIECT, 0) = 0 THEN i.valdoc-i.tvadoc
            ELSE (SELECT Coalesce(Sum(i1.pretorig*i1.cant*Coalesce(i1.CoefDiscmaj,1)),0) FROM IESIRI1 I1 WHERE I1.CODIES = I.CODIES AND I1.CODOBIECT = ID.CODOBIECT)
          END'||PKG_LIST_BASE_SITACCRUALLS_ExprCurs('i')||'*id.procent/100,
          4
        ) ValDisc,
        0 ValIncDec
      FROM iesiri i
        INNER JOIN IESDISC ID ON ID.CODIES = I.CODIES
      WHERE Coalesce(I.Anulat,0) = 0 AND I.Operat = 1 AND Coalesce(I.TipFactura,0) &lt;&gt; 5
        AND i.an*12+i.luna BETWEEN '||sALIni||' AND '||sALFin||
        PKG_LIST_BASE_SITACCRUALLS_Cond('I', 'I.PARTENER') ||'
      UNION ALL
      SELECT
        1 Poz,
        nc.codpart, nc.subunitatea, nc1.coddiscount, Coalesce(nc.codmoneda,0) codmoneda,
        (SELECT Max(Procent) From discinterval di WHERE di.coddiscount = nc1.coddiscount) procent,
        0 BazaDisc,
        0 ValDisc,
        NC1.VALOARE'||PKG_LIST_BASE_SITACCRUALLS_ExprCurs('nc')||' + Coalesce(COR.VALOARE,0) ValIncDec
      FROM NOTECREDIT1 NC1
        INNER JOIN NOTECREDIT NC ON NC1.CODNCREDIT = NC.CODNCREDIT
        LEFT JOIN (
          SELECT
            NCC1.CODNCREDIT1ORIG CODNCREDIT1,
            SUM((Coalesce(NCC1.VALOARE,0) - Coalesce(NCC1.VALOAREOLD,0))'||PKG_LIST_BASE_SITACCRUALLS_ExprCurs('ncc')||') VALOARE
          FROM NOTECREDIT1 NCC1 INNER JOIN NOTECREDIT NCC ON NCC.CODNCREDIT = NCC1.CODNCREDIT
          WHERE NCC.CORECTIE = 1
          GROUP BY NCC1.CODNCREDIT1ORIG
        ) COR ON COR.CODNCREDIT1 = NC1.CODNCREDIT1
      WHERE NC1.TIP = 5
        AND Coalesce(NC1.CODDOC, 0) = 0
        AND Coalesce(NC.CORECTIE,0) = 2
        AND nc.an*12+nc.luna BETWEEN '||sALIni||' AND '||sALFin||
        PKG_LIST_BASE_SITACCRUALLS_Cond('NC', 'NC.CODPART') ||'
      UNION ALL
      SELECT
        1 Poz,
        nc.codpart, nc.subunitatea, 0 coddiscount, Coalesce(nc.codmoneda,0) codmoneda, 0 procent,
        0 BazaDisc,
        NC1.VALOARE'||PKG_LIST_BASE_SITACCRUALLS_ExprCurs('nc')||' ValDisc,
        0 ValIncDec
      FROM NOTECREDIT1 NC1
        INNER JOIN NOTECREDIT NC ON NC1.CODNCREDIT = NC.CODNCREDIT
        LEFT  JOIN IESIRI1    I1 ON I1.CODIES1     = NC1.CODDOC AND NC.VOLUMPEARTICOLE = 1
        LEFT  JOIN IESIRI     I  ON I.CODIES       = CASE WHEN NC.VOLUMPEARTICOLE = 1 THEN I1.CODIES ELSE NC1.CODDOC END
      WHERE NC1.TIP = 2 AND NC.IESIRIPEVOLUM = 1 AND NC1.VALOARE &lt;&gt; 0
        AND Coalesce(NC1.CODDOC, 0) &lt;&gt; 0
        AND Coalesce(NC.CORECTIE,0) = 0
        AND i.an*12+i.luna BETWEEN '||sALIni||' AND '||sALFin||
        PKG_LIST_BASE_SITACCRUALLS_Cond('NC', 'NC.CODPART') ||'
    ) a_pg
    GROUP BY partener, subunitatea, coddiscount, codmoneda, procent';

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitartfirma_processlist</obj_name>
  <obj_hashval>d70b90555e402516f1209bd8c9138387</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitartfirma_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert      varchar;
  vWhereNirExt varchar := '';
  vPerioada    varchar := current_setting('PKG_LIST_SELSITART.vPerioada', TRUE);
  vToateArt    BOOLEAN := current_setting('PKG_LIST_SELSITART.vToateArt', TRUE)::boolean;
  vTotiPart    BOOLEAN := current_setting('PKG_LIST_SELSITART.vTotiPart', TRUE)::boolean;
  vToateDoc    BOOLEAN := current_setting('PKG_LIST_SELSITART.vToateDoc', TRUE)::boolean;
  vJoinNir     varchar := '';
  vWhereNir    varchar := '';
  vWhereArt    varchar := '';
  gSuplCols    varchar := 'NARTOBJ NAO, NART NA, NUM NUM';
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplJoins   VARCHAR := '';
BEGIN
  --Florin 10.01.2023 - fixat 56753
  --Florin 11.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, 'NIRSTOC'   , 'NS'   , 'NS.CODNIRSTOC = LISTA.CODNIRSTOC', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NIR'       , 'NIR'  , 'NIR.CODNIR = NS.CODNIR'          ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARI'   , 'INTR' , 'INTR.CODINTR = NIR.CODINTR AND INTR.TIPDOC = NIR.TIPNIR'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARI1'  , 'INTR1', 'INTR1.CODINTR1 = NS.CODINTR1 AND INTR1.CODINTR = INTR.CODINTR',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NMONEDE'   , 'MINTR', 'MINTR.CODMONEDA = I.MONEDA'                                   ,NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_SITARTFIRMA.gSuplCols', gSuplCols, FALSE);

  IF NOT vTotiPart OR NOT vToateDoc THEN
    vJoinNir := ' INNER JOIN INTRARI I ON I.CODINTR = N.CODINTR ';
  END IF;
  IF vPerioada != '' THEN
    vWhereNir := coalesce(vWhereNir,'') || ' AND N.DATANIR ' || coalesce(vPerioada,'');
  END IF;
  IF NOT vTotiPart THEN
    vWhereNir := coalesce(vWhereNir,'') || '
           AND EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPART'' AND VALOARE = I.PARTENER::varchar) ';
  END IF;
  IF NOT vToateDoc THEN
    vWhereNir := coalesce(vWhereNir,'') || '
           AND I.TIPDOC::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''TIPDOC'') ';
  END IF;
  IF NOT vToateArt THEN
    vWhereArt := '
           AND NS.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'') ';
  END IF;
  IF vWhereNir != '' THEN
    vWhereNirExt := '
        AND EXISTS (SELECT 1 FROM NIR N ' || coalesce(vJoinNir,'') || ' WHERE N.CODNIR = NS.CODNIR ' || coalesce(vWhereNir,'') || ')';
  END IF;
  sInsert := 'INSERT INTO ' || tmpName || '( Art, UM, Ord, CantIn, CantIes, Stoc, PretIn, PretIes, DataDoc' || gUserFields || ' )
      WITH NSINTRARI AS (
        WITH RECURSIVE a (codnirstoc, codnirstocparinte, rootcodnirstoc) AS (
         SELECT codnirstoc, codnirstocparinte, codnirstoc rootcodnirstoc
         FROM nirstoc ns
         WHERE COALESCE(codnirstocparinte, 0) = 0' || coalesce(vWhereArt,'') || COALESCE(vWhereNirExt, '') || '
         UNION ALL
         SELECT n.codnirstoc, n.codnirstocparinte, a.rootcodnirstoc
         FROM nirstoc n INNER JOIN a ON a.codnirstoc = n.codnirstocparinte
        )
        SELECT *
        FROM a';
  sInsert := coalesce(sInsert,'') || ')
      SELECT
        NAO.DENUMIRE, NUM.DEN_UM, COUNT(1) OVER (PARTITION BY NAO.DENUMIRE ORDER BY LISTA.CODNIRSTOC, LISTA.DATA_DOC) ORD,
        LISTA.CANTIN, LISTA.CANTIES, SUM(LISTA.CANTIN - LISTA.CANTIES) OVER (PARTITION BY NAO.DENUMIRE, LISTA.CODNIRSTOC ORDER BY LISTA.DATA_DOC) STOC, LISTA.PRETIN, LISTA.PRETIES, LISTA.DATA_DOC' || gUserAlias || '
      FROM (
        SELECT NS.CODOBIECT, N.DATANIR DATA_DOC, NS.CODNIRSTOC, NS.CANTNIR CANTIN, 0 CANTIES, NS.PRET - NS.ADAOS PRETIN, 0 PRETIES
        FROM NIRSTOC NS INNER JOIN NIR N ON N.CODNIR = NS.CODNIR ' || coalesce(vJoinNir,'') || '
        WHERE NS.CODNIRSTOCPARINTE IS NULL ' || coalesce(vWhereNir,'') || coalesce(vWhereArt,'') || '
        UNION ALL
        SELECT I1.CODOBIECT, I.DATADOC DATA_DOC, NS.ROOTCODNIRSTOC CODNIRSTOC, 0 CANTIN, L1.CANT CANTIES, 0 PRETIN, I1.PU PRETIES
        FROM NSINTRARI NS
          INNER JOIN LIVR1   L1 ON L1.CODNIRSTOC = NS.CODNIRSTOC
          INNER JOIN LIVR    L  ON L.CODLIVR     = L1.CODLIVR AND L.CODIES IS NOT NULL
          INNER JOIN IESIRI1 I1 ON I1.CODIES1    = L1.CODIES1
          INNER JOIN IESIRI  I  ON I.CODIES      = I1.CODIES
      ) LISTA
        INNER JOIN NARTOBJ NAO ON NAO.CODOBIECT = LISTA.CODOBIECT
        INNER JOIN NART    NA  ON NA.CODARTICOL = NAO.CODARTICOL
        LEFT  JOIN NUM         ON NUM.CODUM     = NA.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_sitartfirma_setjoinuri</obj_name>
  <obj_hashval>f211706466dc647254a4aa8b46afa0ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitartfirma_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 11.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_SITARTFIRMA.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitbonretail_getguseralias</obj_name>
  <obj_hashval>63746446a5620257c32982a1f2eb6be9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitbonretail_getguseralias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_SITBONRETAIL.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_sitbonretail_getguserfields</obj_name>
  <obj_hashval>194320c8d5d71abe834591466028c880</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitbonretail_getguserfields(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_SITBONRETAIL.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_sitbonretail_gnullalias</obj_name>
  <obj_hashval>7844ee162be0ef6405c762fd66c67042</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitbonretail_gnullalias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_SITBONRETAIL.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_sitbonretail_gsuplcols</obj_name>
  <obj_hashval>bdea65e3f4a0e1b9f554cfa3677418c6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitbonretail_gsuplcols(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_SITBONRETAIL.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_sitbonretail_gsupljoins</obj_name>
  <obj_hashval>5b971ae4dac64497d501c9e9964060a8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitbonretail_gsupljoins(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_SITBONRETAIL.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_sitbonretail_guseralias</obj_name>
  <obj_hashval>fc350d185133abc03a83dede9abbabb6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitbonretail_guseralias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_SITBONRETAIL.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_sitbonretail_guserfields</obj_name>
  <obj_hashval>9d56c916e21893fe0fe324fb6ac2d197</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitbonretail_guserfields(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_SITBONRETAIL.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_sitbonretail_setguseralias</obj_name>
  <obj_hashval>8d9d79c19c753cb58fcb99258319a1da</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitbonretail_setguseralias(aguseralias character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_SITBONRETAIL.gUserAlias',agUserAlias,false);
end;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitbonretailsint_baga_dinamic_cols</obj_name>
  <obj_hashval>53d6846bb428e2029ddea0f072fc9634</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitbonretailsint_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 28.11.2022 - fixat 56407
  --Florin 23.11.2022
  if current_setting('PKG_LIST_SELECTPERIOADA.vOpt1', TRUE)::NUMERIC = 1 then
    delete FROM tmp_dinamic_cols;
    INSERT INTO tmp_dinamic_cols (FIELDNAME, DISPLAY)
    SELECT 'C'||CODCARD, DENUMIRE
    FROM CARDURI
    WHERE CODCARD &gt; 0;
  end if;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitbonretailsint_processlist</obj_name>
  <obj_hashval>df73a67f2edb9a624e8917164e1d3472</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitbonretailsint_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert      varchar;
  sSelect      varchar;
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplCols    VARCHAR := 'EMULARE E';
  gSuplJoins   VARCHAR := '';
  V_REC record;
BEGIN
  --Florin 21.12.2023 - fixat 60387
  --Florin 05.12.2023 - sinc. Oracle
  --Florin 28.11.2022 - fixat 56407
  --Florin 3.11.2022 - sinc. Oracle
  --Adina 08.06.2021
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_getsuplcols( aLISTID, aLISTVER, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_SITBONRETAILSINT.gSuplCols', gSuplCols, false);

  sInsert :=
  'INSERT INTO ' || coalesce(TMPNAME,'') || '(
          NAV_CODDOC,
          NRBON,
          DATABON,
          VALBON,
          VALDISCBON,
          CASAMARCAT,
          TVATOTAL,
          TVADISCOUNT,
          PARTENER,
          MONETAR,
          OPERATOR,
          SEDIU,
          AGENT,
          OBS,
          DELEGAT,
          INCASARE,
          INCASARE0,
          INCASARE1,
          INCASARE2,
          INCASARE3,
          INCASARE4,
          INCASARE5,
          INCASARE6,
          INCASARE7 ' || coalesce(gUserFields,'') || ')';

  sSelect := '
      SELECT
        E.CODEMULARE,
        E.NRBON,
        E.DATABON,
        E.VALOARE,
        E.VALOAREDISCOUNT,
        CM.DENUMIRE,
        E.TVATOTAL,
        E.TVADISCOUNT,
        P.DEN_PART,
        CASE WHEN I.CODIES &gt; 0 THEN coalesce(I.PREFIXDOC,'''')||coalesce(I.NRDOC::varchar,'''')||''/''||coalesce(TO_CHAR(I.DATADOC, ''DD.MM.YYYY''),'''') END,
        CASE WHEN OP.CODPERS &gt; 0 THEN OP.NUME||'' ''||OP.PRENUME END,
        AG.OBS,
        CASE WHEN AGE.CODPERS &gt; 0 THEN AGE.NUME||'' ''||AGE.PRENUME END,
        E.OBS,
        CASE WHEN DEL.CODPERS &gt; 0 THEN DEL.NUME||'' ''||DEL.PRENUME END,
        (SELECT string_agg(E2.DENUMIRE||'':''||E2.VALOARE::varchar, '' '') FROM EMULARE2 E2 WHERE E2.CODEMULARE = E.CODEMULARE AND coalesce(E2.VALOARE,0) &lt;&gt; 0),
        (SELECT SUM(VALOARE) FROM EMULARE2 E2 WHERE E2.CODEMULARE = E.CODEMULARE AND E2.TIPPLATA = 0),
        (SELECT SUM(VALOARE) FROM EMULARE2 E2 WHERE E2.CODEMULARE = E.CODEMULARE AND E2.TIPPLATA = 1),
        (SELECT SUM(VALOARE) FROM EMULARE2 E2 WHERE E2.CODEMULARE = E.CODEMULARE AND E2.TIPPLATA = 2),
        (SELECT SUM(VALOARE) FROM EMULARE2 E2 WHERE E2.CODEMULARE = E.CODEMULARE AND E2.TIPPLATA = 3),
        (SELECT SUM(VALOARE) FROM EMULARE2 E2 WHERE E2.CODEMULARE = E.CODEMULARE AND E2.TIPPLATA = 4),
        (SELECT SUM(VALOARE) FROM EMULARE2 E2 WHERE E2.CODEMULARE = E.CODEMULARE AND E2.TIPPLATA = 5),
        (SELECT SUM(VALOARE) FROM EMULARE2 E2 WHERE E2.CODEMULARE = E.CODEMULARE AND E2.TIPPLATA = 6),
        (SELECT SUM(VALOARE) FROM EMULARE2 E2 WHERE E2.CODEMULARE = E.CODEMULARE AND E2.TIPPLATA = 7)
        ' || coalesce(gUserAlias, '') || '
      FROM EMULARE E
           LEFT JOIN NCASEMARCAT CM  ON CM.CODCASEMARCAT = E.CODCASAMARCAT
           LEFT JOIN NPART       P   ON P.CODPART        = E.CODPART
           LEFT JOIN IESIRI      I   ON I.CODIES         = E.CODMONETAR
           LEFT JOIN NPERS       OP  ON OP.CODPERS       = E.CODPERS
           LEFT JOIN NAGENDA     AG  ON AG.CODAGENDA     = E.CODLOCATIE
           LEFT JOIN NPERS       AGE ON AGE.CODPERS      = E.CODAGENT
           LEFT JOIN NPERS       DEL ON DEL.CODPERS      = E.DELEGAT
           ' || coalesce(gSuplJoins, '') || '
      WHERE E.DATACREARE BETWEEN to_timestamp(''' || current_setting ('PKG_LIST_SELECTPERIOADA.vDataOraIni', true) || ''',''DD.MM.YYYY HH24:MI'') AND
                                 to_timestamp(''' || current_setting ('PKG_LIST_SELECTPERIOADA.vDataOraFin', true) || ''',''DD.MM.YYYY HH24:MI'')
      ORDER BY E.DATABON';

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

  if current_setting('PKG_LIST_SELECTPERIOADA.vOpt1', TRUE)::NUMERIC = 1 THEN
    FOR V_REC IN (SELECT CODCARD FROM CARDURI where codcard &gt; 0) LOOP
      EXECUTE 'UPDATE '||TMPNAME||' T SET C'||V_REC.CODCARD||' = (select M.valoare from emulare2 M where m.codemulare = T.NAV_CODDOC AND M.CODCARD = '||V_REC.CODCARD||')';
    END LOOP;
   END IF;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitconsum_setjoinuri</obj_name>
  <obj_hashval>000146de4eeea06d6f5f2d84af439046</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitconsum_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 07.08.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_SITCONSUM.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitconsumprod_setjoinuri</obj_name>
  <obj_hashval>7a0efe5057c850708de6799f6ebab92b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitconsumprod_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 14.09.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_SITCONSUMPROD.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitdatorii_processlist</obj_name>
  <obj_hashval>a2ed2e87836bd67291cfdd0a516340e8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitdatorii_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'PKG_LIST_BASE_SITDATORII TMP';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Florin 20.12.2021 - fixat 52357
  --Adina 16.10.2020 (??)
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_SITDATORII.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    Tab,
    Doc, NrDoc, DataDoc, Valoare, Rest, Termen, ZileScadente, SimbolCont, Den_Subunit, Sediu,
    CecNeincasat,
    Obs, Agent' || gUserFields || ')
  SELECT
    CASE TMP.Tab WHEN 1 THEN ''Documente'' WHEN 2 THEN ''Cecuri'' WHEN 3 THEN ''Comenzi'' END Tab,
    TMP.Doc, TMP.NrDoc, TMP.DataDoc, TMP.Valoare, TMP.Rest, TMP.Termen, TMP.ZileScadente, TMP.SimbolCont, TMP.Den_Subunit, TMP.Sediu,
    CASE TMP.CecNeincasat WHEN 1 THEN ''DA'' ELSE ''NU'' END CecNeincasat,
    TMP.Obs, TMP.Agent' || gUserAlias || '
  FROM TMP_LST_SITDATORII TMP' || gSuplJoins;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitdatorii_processparams</obj_name>
  <obj_hashval>705d7d2cb4bac64d84bd5812f4dc14c6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitdatorii_processparams()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Adina 16.10.2020
  FOR v_rec IN (SELECT Den_part FROM NPART WHERE CodPart = current_setting('PKG_LIST_BASE_SITDATORII.vCodPart', true)::numeric) LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener', v_rec.Den_part);
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT SIMBOL FROM NMONEDE WHERE CodMOneda = current_setting('PKG_LIST_BASE_SITDATORII.vCodMoneda', true)::numeric) LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Moneda', v_rec.SIMBOL);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitdatorii_setparams</obj_name>
  <obj_hashval>f47ccb17fe18fbe8d9b1f274e028e6d0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitdatorii_setparams(pcodpart numeric, pcodagenda numeric, pcodmoneda numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.10.2020
  perform set_config('PKG_LIST_BASE_SITDATORII.vCodPart'  ,(pCodPart)::varchar  ,false);
  perform set_config('PKG_LIST_BASE_SITDATORII.vCodAgenda',(pCodAgenda)::varchar,false);
  perform set_config('PKG_LIST_BASE_SITDATORII.vCodMoneda',(pCodMoneda)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitfin_inchid711cu121</obj_name>
  <obj_hashval>7431d1d73cba89e32180e2cdc4b2673a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitfin_inchid711cu121()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSelect varchar;
  vRez     numeric;
BEGIN
  --Florin 14.11.2025 - sinc. Oracle
  --Florin 04.11.2025 - sinc. Oracle
  --Adina 15.10.2020
  vRez := 0;

  sSelect := '
  WITH
    r as (
      SELECT
        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, rs.subunitatea, r.an, r.luna
      FROM ncontrul r
        INNER JOIN ncontrulsub rs ON rs.codcontrul = r.codcontrul
      WHERE r.an*12+r.luna = ' || coalesce(getANLUCRU()::varchar,'') || '*12 + getlunalucru() + 1 AND r.luna &gt; 1),
    n AS (
--          SELECT c.codcont
--          FROM ncont c
--          WHERE EXISTS (SELECT 1 FROM ncont1 c1 WHERE c1.codcont = c.codcont AND c1.anstart*12+c1.lunastart &lt;= getANLUCRU())
--          START WITH c.codcont IN (SELECT codcont from ncont where simbol = ''711'')
--          CONNECT BY PRIOR c.codcont = c.codparinte
          WITH RECURSIVE aa  AS(
            SELECT n.codcont, n.codparinte
            FROM ncont n
            where n.codcont IN (SELECT codcont from ncont where simbol = ''711'')
            UNION ALL
            SELECT o.codcont, o.codparinte
            FROM ncont O  inner join AA a ON a.codcont = o.codparinte
          )
          SELECT codcont FROM AA c WHERE EXISTS (SELECT 1 FROM ncont1 c1 WHERE c1.codcont = c.codcont AND c1.anstart*12+c1.lunastart &lt;= ' || coalesce(getANLUCRU()::varchar,'') || '*12)
         )
    select sum(coalesce(debit,0) - coalesce(credit,0)) from (
    SELECT
      0 nav_coddoc, 0 nav_tipdoc, sc.codcont, 0 codcoresp,
      0 debit, 0 credit, 0 debitv, 0 creditv, 0 valoare, 0 valoarev,
      coalesce(s.soldid,0) - coalesce(s.soldic,0) sold, coalesce(s.soldvid,0) - coalesce(s.soldvic,0) soldv,
      coalesce(s.soldi_ifrs,0) ifrs,  coalesce(s.soldvi_ifrs,0) ifrsv, coalesce(s.soldi_ifrs,0) sold_ifrs, coalesce(s.soldvi_ifrs,0) sold_ifrsv,
      coalesce(s.soldi_grup,0) grup,  coalesce(s.soldvi_grup,0) grupv, coalesce(s.soldi_grup,0) sold_grup, coalesce(s.soldvi_grup,0) sold_grupv,
      ''Sold initial'' obs, null as document, to_date(''01.''||sc.luna||''.''||sc.an,''dd.mm.yyyy'')  datadoc, s.subunitatea, 0 gest, sc.an, sc.luna,
      -1 ordine,
      0 codcentru, 0 indexlocal
    FROM ncontsold sc
      INNER JOIN ncontsoldsub s ON s.codcontsold = sc.codcontsold
      INNER JOIN n              ON n.codcont     = sc.codcont
    WHERE sc.an * 12 + sc.luna = ' || coalesce(getANLUCRU()::varchar,'') || '*12+1
    UNION ALL
    SELECT
      0 nav_coddoc, 0 nav_tipdoc, r.codcont, 0 codcoresp,
      coalesce(r.rulajpd,0) debit, coalesce(r.rulajpc,0) credit, coalesce(r.rulajvpd,0) debitv, coalesce(r.rulajvpc,0) creditv, 0 valoare, 0 valoarev,
      coalesce(r.rulajpd,0) - coalesce(r.rulajpc,0) sold, coalesce(r.rulajvpd,0) - coalesce(r.rulajvpc,0) soldv,
      coalesce(r.rulajp_ifrs,0) ifrs, coalesce(r.rulajvp_ifrs,0) ifrsv, coalesce(r.rulajp_ifrs,0) sold_ifrs, coalesce(r.rulajvp_ifrs,0) sold_ifrsv,
      coalesce(r.rulajp_grup,0) grup, coalesce(r.rulajvp_grup,0) grupv, coalesce(r.rulajp_grup,0) sold_grup, coalesce(r.rulajvp_grup,0) sold_grupv,
      ''Rulaj precedent'' obs, null as document, 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 indexlocal
    FROM r
      INNER JOIN n ON n.codcont = r.codcont
    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.valoarev= 0 then 1 else j.valoare/j.valoarev end),0) grupv, coalesce(j.valoaregrup,0) sold_grup, coalesce(j.valoaregrup/(case when j.valoarev= 0 then 1 else j.valoare/j.valoarev end),0) sold_grupv,
      j.obs, j.document, j.datadoc, j.subunitatea, j.gest, j.an, j.luna,
      CASE
        WHEN j.tipdoc = 81                                       THEN 10000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''SINCRONIZARE%'') THEN 20000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''INCHIDERE%'')    THEN 30000000000000000000
        ELSE 0
      END + j.codjurnal ordine,
      j.codcentru, j.indexlocal
    FROM jurnal j
      INNER JOIN n ON n.codcont = j.contd
    WHERE j.an *12 + j.luna BETWEEN ' || coalesce(getANLUCRU()::varchar,'') || '*12+1 AND ' || coalesce(getANLUCRU()::varchar,'') || '*12+12 +'|| getGetlunaLUCRU() ||' and j.contc in (select codcont from ncont where simbol like ''121%'')
    UNION ALL
    SELECT  -- tipinreg 1 credit
      j.coddoc nav_coddoc, j.tipdoc nav_coddoc, j.contc codcont,j.contd codcoresp,
      0 debit, j.valoare credit, 0 debitv, j.valoarev creditv, j.valoare, j.valoarev,
      coalesce(-j.valoare,0) sold, coalesce(-j.valoarev,0) soldv,
      -coalesce(j.valoare_ifrs,0) ifrs, -coalesce(j.valoarev_ifrs,0) ifrsv, -coalesce(j.valoare_ifrs,0) sold_ifrs, -coalesce(j.valoarev_ifrs,0) sold_ifrsv,
      -coalesce(j.valoaregrup,0) grup, -coalesce(j.valoaregrup/(case when j.valoarev= 0 then 1 else j.valoare/j.valoarev end),0) grupv, -coalesce(j.valoaregrup,0) sold_grup, -coalesce(j.valoaregrup/(case when j.valoarev= 0 then 1 else j.valoare/j.valoarev end),0) sold_grupv,
      j.obs, j.document, j.datadoc, j.subunitatea, j.gest, j.an, j.luna,
      CASE
        WHEN j.tipdoc = 81                                       THEN 10000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''SINCRONIZARE%'') THEN 20000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''INCHIDERE%'')    THEN 30000000000000000000
        ELSE 0
      END + j.codjurnal ordine,
      j.codcentru, j.indexlocal
    FROM jurnal j
      INNER JOIN n ON n.codcont = j.contc
    WHERE j.an *12 + j.luna BETWEEN ' || coalesce(getANLUCRU()::varchar,'') || '*12+1 AND ' || coalesce(getANLUCRU()::varchar,'') || '*12+12 +'|| getGetlunaLUCRU() ||'  and j.contd in (select codcont from ncont where simbol like ''121%'')
    ) AA_PG ';

  BEGIN
    EXECUTE sSelect INTO vRez;
  EXCEPTION WHEN others THEN
    vRez := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitfin_inchid765cu473</obj_name>
  <obj_hashval>9c0bc4765ec81ad3450d886f266957ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitfin_inchid765cu473()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSelect varchar;
  vRez     numeric;
BEGIN
  --Florin 14.11.2025 - sinc. Oracle
  --Adina 15.10.2020
  vRez := 0;

  sSelect := '
  WITH
    r as (
      SELECT
        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, rs.subunitatea, r.an, r.luna
      FROM ncontrul r
        INNER JOIN ncontrulsub rs ON rs.codcontrul = r.codcontrul
      WHERE r.an*12+r.luna = ' || coalesce(getANLUCRU()::varchar,'') || '*12+1 AND r.luna &gt; 1),
    n AS (
--          SELECT c.codcont
--          FROM ncont c
--          WHERE EXISTS (SELECT 1 FROM ncont1 c1 WHERE c1.codcont = c.codcont AND c1.anstart*12+c1.lunastart &lt;= getANLUCRU()*12)
--          START WITH c.codcont IN (SELECT codcont from ncont where simbol = ''765'')
--          CONNECT BY PRIOR c.codcont = c.codparinte
          WITH RECURSIVE aa  AS(
            SELECT n.codcont, n.codparinte
            FROM ncont n
            where n.codcont IN (SELECT codcont from ncont where simbol = ''665'')
            UNION ALL
            SELECT o.codcont, o.codparinte
            FROM ncont O  inner join AA a ON a.codcont = o.codparinte
          )
          SELECT codcont FROM AA c WHERE EXISTS (SELECT 1 FROM ncont1 c1 WHERE c1.codcont = c.codcont AND c1.anstart*12+c1.lunastart &lt;= ' || coalesce(getANLUCRU()::varchar,'') || '*12)
         )
    select sum(coalesce(credit,0)) from (
    SELECT
      0 nav_coddoc, 0 nav_tipdoc, sc.codcont, 0 codcoresp,
      0 debit, 0 credit, 0 debitv, 0 creditv, 0 valoare, 0 valoarev,
      coalesce(s.soldid,0) - coalesce(s.soldic,0) sold, coalesce(s.soldvid,0) - coalesce(s.soldvic,0) soldv,
      coalesce(s.soldi_ifrs,0) ifrs,  coalesce(s.soldvi_ifrs,0) ifrsv, coalesce(s.soldi_ifrs,0) sold_ifrs, coalesce(s.soldvi_ifrs,0) sold_ifrsv,
      coalesce(s.soldi_grup,0) grup,  coalesce(s.soldvi_grup,0) grupv, coalesce(s.soldi_grup,0) sold_grup, coalesce(s.soldvi_grup,0) sold_grupv,
      ''Sold initial'' obs, null as document, to_date(''01.''||sc.luna||''.''||sc.an,''dd.mm.yyyy'')  datadoc, s.subunitatea, 0 gest, sc.an, sc.luna,
      -1 ordine,
      0 codcentru, 0 indexlocal
    FROM ncontsold sc
      INNER JOIN ncontsoldsub s ON s.codcontsold = sc.codcontsold
      INNER JOIN n              ON n.codcont     = sc.codcont
    WHERE sc.an * 12 + sc.luna = ' || coalesce(getANLUCRU()::varchar,'') || '*12+1
    UNION ALL
    SELECT
      0 nav_coddoc, 0 nav_tipdoc, r.codcont, 0 codcoresp,
      coalesce(r.rulajpd,0) debit, coalesce(r.rulajpc,0) credit, coalesce(r.rulajvpd,0) debitv, coalesce(r.rulajvpc,0) creditv, 0 valoare, 0 valoarev,
      coalesce(r.rulajpd,0) - coalesce(r.rulajpc,0) sold, coalesce(r.rulajvpd,0) - coalesce(r.rulajvpc,0) soldv,
      coalesce(r.rulajp_ifrs,0) ifrs, coalesce(r.rulajvp_ifrs,0) ifrsv, coalesce(r.rulajp_ifrs,0) sold_ifrs, coalesce(r.rulajvp_ifrs,0) sold_ifrsv,
      coalesce(r.rulajp_grup,0) grup, coalesce(r.rulajvp_grup,0) grupv, coalesce(r.rulajp_grup,0) sold_grup, coalesce(r.rulajvp_grup,0) sold_grupv,
      ''Rulaj precedent'' obs, null as document, 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 indexlocal
    FROM r
      INNER JOIN n ON n.codcont = r.codcont
    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.valoarev= 0 then 1 else j.valoare/j.valoarev end),0) grupv, coalesce(j.valoaregrup,0) sold_grup, coalesce(j.valoaregrup/(case when j.valoarev= 0 then 1 else j.valoare/j.valoarev end),0) sold_grupv,
      j.obs, j.document, j.datadoc, j.subunitatea, j.gest, j.an, j.luna,
      CASE
        WHEN j.tipdoc = 81                                       THEN 10000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''SINCRONIZARE%'') THEN 20000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''INCHIDERE%'')    THEN 30000000000000000000
        ELSE 0
      END + j.codjurnal ordine,
      j.codcentru, j.indexlocal
    FROM jurnal j
      INNER JOIN n ON n.codcont = j.contd
    WHERE j.an *12 + j.luna BETWEEN ' || coalesce(getANLUCRU()::varchar,'') || '*12+1 AND ' || coalesce(getANLUCRU()::varchar,'') || '*12+12 +'|| getGetlunaLUCRU() ||' and j.contc in (select codcont from ncont where simbol like ''473.02%'')
    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.valoarev= 0 then 1 else j.valoare/j.valoarev end),0) grupv, -coalesce(j.valoaregrup,0) sold_grup, -coalesce(j.valoaregrup/(case when j.valoarev= 0 then 1 else j.valoare/j.valoarev end),0) sold_grupv,
      j.obs, j.document, j.datadoc, j.subunitatea, j.gest, j.an, j.luna,
      CASE
        WHEN j.tipdoc = 81                                       THEN 10000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''SINCRONIZARE%'') THEN 20000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''INCHIDERE%'')    THEN 30000000000000000000
        ELSE 0
      END + j.codjurnal ordine,
      j.codcentru, j.indexlocal
    FROM jurnal j
      INNER JOIN n ON n.codcont = j.contc
    WHERE j.an *12 + j.luna BETWEEN ' || coalesce(getANLUCRU()::varchar,'') || '*12+1 AND ' || coalesce(getANLUCRU()::varchar,'') || '*12+12 +'|| getGetlunaLUCRU() ||' and j.contd in (select codcont from ncont where simbol like ''473.02%'')
    ) AA_PG ';

  BEGIN
    EXECUTE sSelect INTO vRez;
  EXCEPTION WHEN others THEN
    vRez := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitfin_processlist</obj_name>
  <obj_hashval>6f48ab8967c4cefb4669e61e3507fd57</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitfin_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  sString varchar := '';
  sCols   varchar := '';
BEGIN
  --Adina 15.10.2020
  FOR V_REC IN (SELECT COLUMN_NAME
                FROM information_schema.columns
                WHERE TABLE_NAME = lower(current_setting('PKG_LIST_BASE_SITFIN.p_tabla', true))
               )
  LOOP
    SCOLS := SCOLS || V_REC.COLUMN_NAME || ',';
  END LOOP;

  SCOLS := SUBSTR(SCOLS, 1, LENGTH(SCOLS) - 1);

  sString := 'insert into ' || tmpName || '(' || scols || ')  select ' || scols || ' from ' || coalesce(current_setting('PKG_LIST_BASE_SITFIN.p_Tabla', true),'');
  EXECUTE (  sString) ;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitfin_setallsubunit</obj_name>
  <obj_hashval>bd3a68be467accbe984559341fdfd69f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitfin_setallsubunit()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  INSERT INTO tmp_manevra(codunic)
  SELECT codsubunit FROM nsubunit WHERE codsubunit &gt; 1;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitfin_setcod</obj_name>
  <obj_hashval>7e076eca82441a8e68ca23e463edc19e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitfin_setcod(v_codsitfin numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  perform set_config('PKG_LIST_BASE_SITFIN.p_CodSitFin',(v_CodSitFin)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitfin_setjoinuri</obj_name>
  <obj_hashval>8826843cd380ed839152c8cb556c31cf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitfin_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.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_sitfin_setparams</obj_name>
  <obj_hashval>e9db1d458bc057eed7826c51764ebd45</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitfin_setparams(v_tabla character varying, 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
  --Adona 15.10.2020
  perform set_config('PKG_LIST_BASE_SITFIN.vDataS',sDataS,false);
  perform set_config('PKG_LIST_BASE_SITFIN.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_SITFIN.p_Tabla',(upper(v_Tabla))::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitimob_getcodlivr1vanz</obj_name>
  <obj_hashval>dec8e4e9619f6557cccee6884df14965</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitimob_getcodlivr1vanz(pstare numeric, pcodnirstoc numeric, pan numeric, pluna numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vResult numeric;
begin
  --Bogdan 15.09.2020
  IF pStare = 4 THEN
    SELECT Min (l1.codlivr1)
    INTO vResult
    FROM nirstoc        ns
      INNER JOIN nir    n  ON n.codnir      = ns.codnir
      INNER JOIN livr1  l1 ON l1.codnirstoc = ns.codnirstoc
      INNER JOIN livr   l  ON l.codlivr     = l1.codlivr
      INNER JOIN IESIRI I  ON i.codies      = l.codies AND i.tipdoc = l.tiplivr
    WHERE
      ns.codnirstoc = pCodnirstoc
      AND i.an = pAn
      AND i.luna = pLuna
      AND l.codies &lt;&gt; Coalesce (n.codies, 0);
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitimob_setparams</obj_name>
  <obj_hashval>8233c7f77cab05a7e0de531f1bf79765</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitimob_setparams(plunaanini numeric, plunaanfin numeric, poldmf numeric, pallgest numeric, pallioart numeric, pallmf numeric, pcodjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vDataS date;
  vDataF date;

  sDataS varchar(10);
  sDataF varchar(10);

  vLunaAnIni numeric;
  vLunaAnFin numeric;
begin
  --Bogdan 15.09.2020
  vLunaAnIni := Coalesce (pLunaAnIni, 0);
  vLunaAnFin := Coalesce (pLunaAnFin, 0);
  perform set_config ('PKG_LIST_BASE_SITIMOB.vOldMF'   ,pOldMF::varchar   ,false);
  perform set_config ('PKG_LIST_BASE_SITIMOB.vAllGest' ,pAllGest::varchar ,false);
  perform set_config ('PKG_LIST_BASE_SITIMOB.vAllIOArt',pAllIOArt::varchar,false);
  perform set_config ('PKG_LIST_BASE_SITIMOB.vAllMF'   ,pAllMF::varchar   ,false);
  IF pCodJob1 &gt; 0 THEN
    select PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.adataini,PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.adatafin,
        PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.alunaanini, PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.alunaanfin
      from PKG_ORA_LISTS_SET_INTERVAL_DINAMIC (pCodJob1, vDataS, vDataF, vLunaAnIni, vLunaAnFin) into vDataS, vDataF, vLunaAnIni, vLunaAnFin;
  END IF;
  sDataS := to_char(vDataS,'dd.mm.yyyy');
  sDataF := to_char(vDataF,'dd.mm.yyyy');
  perform set_config ('PKG_LIST_BASE_SITIMOB.vLunaAnIni',vLunaAnIni ::varchar,false);
  perform set_config ('PKG_LIST_BASE_SITIMOB.vLunaAnFin',vLunaAnFin ::varchar,false);
  perform set_config ('PKG_LIST_BASE_SITIMOB.vDataS',sDataS,false);
  perform set_config ('PKG_LIST_BASE_SITIMOB.vDataF',sDataF,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitiniesluna_setjoinuri</obj_name>
  <obj_hashval>f4afb006e2b849234851b2089df91339</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitiniesluna_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 10.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_SITINIESLUNA.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitoninv_processlist</obj_name>
  <obj_hashval>03327c4ae7d70950187b2a67a4909a82</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitoninv_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;
begin
  --Bogdan 09.09.2020
  gSuplCols := 'npart p, nartobj nao, nart na, nclasea ca, nclasedisc clsd';

  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_SITONINV.gSuplCols',gSuplCols,false);

  sInsert := 'INSERT INTO '||tmpName
              || ' (
            Part, Art, ClasaA, Subunit, Disc, TipBazaC, ProcDisc, BazaDisc, ValDisc, ValADisc, Moneda'
              || coalesce (gUserFields ,'')
              || ')
            SELECT p.Den_Part,
              nao.Denumire,
              ca.Den_Clasea,
              sub.Den_Subunit,
              CASE
                WHEN tmp.codcriteriu &lt;&gt; 0 THEN cd.DenCriteriu
                WHEN Sign (tmp.proc) &gt; 0 THEN ''Majorare direct pe cont ''||c.simbol
                ELSE ''Discount direct pe cont ''||c.simbol
              END,
              (case CUMULAT
                  when 0 then ''NET = valoare articol cu toate disc.aplicate''
                  when 1 then ''BRUT = valoare articol''
                  when 2 then ''valoare articol cu disc. de tip BRUT si NET aplicate'' end) ,
              tmp.Proc,
              tmp.BazaDisc,
              tmp.ValDisc,
              tmp.ValDiscAnt,
              mon.simbol '
              || coalesce (gUserAlias ,'')|| '
            FROM tmp_list_sitoninv   tmp
              LEFT JOIN nmonede      mon  on tmp.codmoneda     = mon.codmoneda
              LEFT JOIN npart        p    ON p.codpart         = tmp.codpart
              LEFT JOIN nartobj      nao  ON nao.codobiect     = tmp.codobiect
              LEFT JOIN nart         na   ON na.codarticol     = nao.codarticol
              LEFT JOIN nclasea      ca   ON ca.codclasea      = na.clasa
              LEFT JOIN nsubunit     sub  ON sub.codsubunit    = tmp.subunitatea
              LEFT JOIN criteriidisc cd   ON cd.codcriteriu    = tmp.codcriteriu
              LEFT JOIN nclasedisc   clsd ON clsd.codclasedisc = cd.clasa
              LEFT JOIN ncont        c    ON c.codcont         = tmp.codcont'
              || coalesce (gSuplJoins ,'');
  PERFORM PKG_LIST_BASE_SITONINV_UmpleTmp (NULL);
  PERFORM LIST_EXECUTE_IMMEDIATE (sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitpen_processlist</obj_name>
  <obj_hashval>17ce4cb167c10adb48cdabd0e63c8d35</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitpen_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSQL             varchar := '';
  aCount           numeric;
  gSuplCols        VARCHAR := 'nmonede m,npartcodfisc pcf,npart p,nagenda ag';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 15.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_SITPEN.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sSQL :=
  'insert into ' || tmpName || '(
    CODOBLIGPIF,
    PREFIXDOC,
    NRDOC,
    DATADOC,
    VALDOC,
    TERMEN,
    REST,
    MAJORARI,
    LOCATIE,
    DEN_PART,
    DEN_SUBUNIT,
    MONEDA,
    MAJANTERIOARE,
    DATA_LAST_FACTMAJ,
    DATA_LAST_PLATA,
    GRATIEDOC,
    STORNO,
    SCADENTAV,
    RESTLADATA ' || gUserFields || ')
  select
    tmp.codobligpif,
    tmp.prefixdoc,
    tmp.nrdoc,
    tmp.datadoc,
    tmp.valdoc,
    tmp.termen,
    tmp.rest,
    tmp.majorari,
    tmp.locatie,
    tmp.den_part,
    tmp.den_subunit,
    m.den_moneda,
    tmp.majanterioare,
    tmp.data_last_factmaj,
    tmp.data_last_plata,
    tmp.gratiedoc,
    tmp.storno,
    tmp.scadentav,
    tmp.restladata ' || gUserAlias || '
  from TMP_LST_GENPEN tmp
       left join nmonede m  on tmp.moneda   = m.codmoneda
       left join npart p    on tmp.codpart  = p.codpart
       left join nagenda ag on ag.codagenda = tmp.codlocatie' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sSQL, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitpen_setparams</obj_name>
  <obj_hashval>19631ead35e97abc8c562211262d7c60</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitpen_setparams(v_tabla character varying, v_codjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  perform set_config('PKG_LIST_BASE_SITPEN.p_Tabla',(upper(v_Tabla))::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitpunctcli_processlist</obj_name>
  <obj_hashval>d20f3ac59713d85f8f8ffffee9a7e100</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitpunctcli_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;
  sCondSupl varchar;
  vDataIni  date := PKG_LIST_SELECTPERIOADA_DataOraIni();
  vDataFin  date := PKG_LIST_SELECTPERIOADA_DataOraFin();
  sDataIni  varchar;
  sDataFin  varchar;
begin
  --Bogdan 10.09.2020
  gSuplCols := 'iesiri i, iespuncte ip, 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_SITPUNCTCLI.gSuplCols',gSuplCols,false);

  sDataIni := 'To_date('''|| coalesce (To_Char (vDataIni,'dd.mm.yyyy hh24:mi') ,'')|| ''',''dd.mm.yyyy hh24:mi'')';
  sDataFin := 'To_date('''|| coalesce (To_Char (vDataFin,'dd.mm.yyyy hh24:mi') ,'')|| ''',''dd.mm.yyyy hh24:mi'')';

  sInsert := 'INSERT INTO '|| tmpName
          || '(
          NAV_CodDoc,
          NAV_TipDoc,
          PrefixDoc,
          NrDoc,
          DataDoc,
          Part,
          PctDoc,
          PctNull,
          PctStinse,
          Blocat,
          Obs '
          || coalesce (gUserFields ,'')
          || ')
      SELECT i.codies,
        i.tipdoc,
        i.prefixdoc,
        i.nrdoc,
        i.datadoc,
        p.den_part,
        ip.punctedoc,
        ip.puncteanulate,
        ip.punctestinse,
        case when ip.blocat = 1 then ''DA'' else ''NU'' end,
        i.obs '
          || coalesce (gUserAlias ,'')|| '
      from iesiri            i
        inner join iespuncte ip on ip.codies  = i.codies
        inner join npart     p  on i.partener = p.codpart '
          || coalesce (gSuplJoins ,'')|| '
      where
        i.anulat = 0
        and i.operat = 1
        and (ip.punctedoc &lt;&gt; 0
          or ip.puncteanulate &lt;&gt; 0
          or ip.punctestinse &lt;&gt; 0)
        and i.datadoc between '|| sDataIni|| ' AND '|| sDataFin
          || 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 (sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitpunctcli_setjoinuri</obj_name>
  <obj_hashval>1fc8886538c4e105a8ed241b88ed1342</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitpunctcli_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 10.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec (current_setting ('PKG_LIST_BASE_SITPUNCTCLI.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sittransp_processlist</obj_name>
  <obj_hashval>0a9c4f6515e072583bb60c07455c3979</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sittransp_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE sInsert VARCHAR(15000);
BEGIN
  --Florin 03.05.2022
    sInsert :=
    'INSERT INTO ' || tmpName || '(
       Traseu, Client, SerieDoc, NrDoc, DataDoc, Sofer, MijlTransp, NrTransp,
       MasaDoc, VolumDoc, MasaTraseu, VolumTraseu, MasaUtila, VolumUtil,
       CodTraseu, LungTransp, LatTransp, InaltTransp)
    SELECT
      TL.DenTraseu Traseu, case when C.TipDoc = 18 then P.Den_Part when  C.TipDoc = 43 then G.Den_Gest when  C.TipDoc = 44 then S.Den_Subunit end Client,
      C.SeriaDoc SerieDoc, C.NrDoc, C.DataDoc,
      NumePrenume( PERS.Prenume, PERS.Nume) Sofer, A.Den_Articol MijlTransp, PA.NrInreg,
      SUM(TTC.Masa) MasaDoc, SUM(TTC.Volum) VolumDoc, 0 MasaTraseu, 0 VolumTraseu, PA.MasaU MasaUtila, PA.VolumU VolumUtil,
      TL.CodTraseuLivr CodTraseu, PA.Lung LungTransp, PA.Lat LatTransp, PA.Inalt InaltTransp
    FROM tmp_traseulivr_allcmd_baza TTC
      LEFT JOIN TraseuLivr TL ON TL.CodTraseuLivr = TTC.CodTraseu
      LEFT JOIN Comanda C ON C.CodComanda = TTC.CodComanda
      LEFT JOIN NPart P ON P.CodPart = C.partener
      LEFT JOIN NSubunit S ON S.CodSubunit = C.Subunitatea
      LEFT JOIN NGest G ON G.CodGest = C.CodGest
      LEFT JOIN NParcAut PA on PA.CodNParcAut = C.MIJLTRANSP
      LEFT JOIN NArtObj AO ON AO.CodObiect = PA.CodArt
      LEFT JOIN NArt A ON A.CodArticol = AO.CodArticol
      LEFT JOIN NPers PERS ON PERS.CodPers = PA.Sofer
    GROUP BY
      TL.DenTraseu, case when C.TipDoc = 18 then P.Den_Part when  C.TipDoc = 43 then G.Den_Gest when  C.TipDoc = 44 then S.Den_Subunit end, C.SeriaDoc, C.NrDoc, C.DataDoc,
      PERS.Prenume, PERS.Nume, A.Den_Articol, PA.NrInreg, PA.MasaU, PA.VolumU, TL.CodTraseuLivr, PA.Lung, PA.Lat, PA.Inalt';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

    sInsert := 'update '||tmpname||' tmp set masatraseu = (select sum(t.masa) from TMP_TraseuLivr_Comenzi t where tmp.codtraseu = t.codtraseu),
                                             volumtraseu = (select sum(t.volum) from TMP_TraseuLivr_Comenzi t where tmp.codtraseu = t.codtraseu)';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sittransp_setjoinuri</obj_name>
  <obj_hashval>031d79a837b9a2fffbb17e99aecc9645</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sittransp_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 03.05.2022
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_SITTRANSP.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_situtilaje_setparams</obj_name>
  <obj_hashval>f140d2a803540cd2e0ae2b94b7306dcb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_situtilaje_setparams(p_toateu numeric DEFAULT 1)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16 septembrie 2020
  perform set_config('PKG_LIST_BASE_SITUTILAJE.v_ToateU',( p_ToateU = 1)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitvanzretail_processlist</obj_name>
  <obj_hashval>b7e51813830d46f42faca9afa1a3f03d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitvanzretail_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';
  sWithDC          varchar := '';
  sJoinSer         varchar := '';
  sDenDisc         varchar := '';
  sJoinAux         varchar := '';
  gSuplCols        VARCHAR := 'iesiriretail i, iesiri1retail i1, nartobj nao, nart na, num1 um, nclasea c, nclaseas cs, npart prod, ncont nc, ntva1 tmp_tva';
   gUserFields     VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Florin 10.04.2024 - getAdresa
  --Adina 15.10.2020
  --Bogdan 25.01.2021
  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_SITVANZRETAIL.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 OR length(sDenDisc)=0 THEN
    sDenDisc := 'Discount';
  ELSE
    sDenDisc := REPLACE(sDenDisc, '''', '''''');
  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, TotalVal,
    PROCADAOS,
    PROCTVA,
    PROCTVAART,
    PROCDISC,
    PretMaximal,
    GARIES, GARART,
    DenClasaA,
    SimbClasaA,
    DiscAfis,
    DenClaseAS,
    IDX, NrUnic,
    NRCOLETE,
    DENATRIB,
    CantUMPrinc,
    TipIncVal,
    TipInc,
    Intocmit_nume, Intocmit_prenume, Intocmit_CNP, Intocmit_BI,
    client_den, carnet_simbol, carnet_serie, carnet_den, client_codext, client_codfisc, client_reg,
    doc_nr, doc_data,
    sediu, sediu_adresa, sediu_loc, sediu_judet, sediu_tara,
    username' || gUserFields || ')';

  sSelect := '
  WITH
    MAN_IESIRI1 AS (
    SELECT
      I1.codiesretail, I1.CODOBIECT, I1.UMSEC, I1.codies1retail, I1.CANT, I1.PRETORIG, I1.PU, I1.PRETORIG*Coalesce(NullIf(I1.COEFDISCMAJ,0),1) 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 INNER JOIN IESIRIRETAIL I ON I1.CODIESRETAIL = I.CODIESRETAIL
    WHERE Coalesce(I.ANULAT,0) = 0
      AND I.DATACREARE BETWEEN TO_DATE(''' || coalesce(To_Char(PKG_LIST_SELECTPERIOADA_DATAORAINI(),'dd.mm.yyyy HH24:MI'),'') || ''',''DD.MM.YYYY HH24:MI'') AND TO_DATE(''' || coalesce(To_Char(PKG_LIST_SELECTPERIOADA_DATAORAFIN(),'dd.mm.yyyy HH24:MI'),'') || ''',''DD.MM.YYYY HH24:MI'')
  )
  SELECT
    CASE
      WHEN Coalesce(i1.CODCRITERIU,0) = 2 AND i1.TIPLINIE IN (''G'',''T'') AND i1.CANT &lt;=0 THEN '' ' || 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 '' ' || 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 '' ' || 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 '' ' || 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,
    mi1.vu VAL, mi1.pu - mi1.pretorig VALADAOS, mi1.tva VALTVA, mi1.vu * Coalesce(i.curs,1) VAL_LEI,
    (mi1.vu - mi1.vorig) * Coalesce(i.curs,1) VALADAOS_LEI, mi1.tva * Coalesce(i.curs,1) VALTVA_LEI, I.VALDOC TotalVal,
    CASE WHEN mi1.minaddim = mi1.maxaddim THEN mi1.minaddim WHEN mi1.vorig = 0 THEN 0 ELSE (mi1.vu-mi1.vorig)*100/mi1.vorig 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 WHEN mi1.vu = 0 THEN 0 ELSE (mi1.viesl-mi1.vu)*100/mi1.vu END PROCDISC,
    CASE
      WHEN Coalesce(nao1.tippretmax,0) IN (1,2) AND Coalesce(i1.pumaximal    , 0) &lt;&gt; 0 THEN i1.pumaximal
      WHEN Coalesce(nao1.tippretmax,0) IN (4,5) AND Coalesce(nao1.pretmaximal, 0) &lt;&gt; 0 THEN nao1.pretmaximal
      WHEN Coalesce(nao1.tippretmax,0) IN (1,2,4,5)                                    THEN -1
      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 '' ' || 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,
    (SELECT string_agg(CASE Coalesce(TIPPLATA,0) WHEN 0 THEN ''CASH'' WHEN 1 THEN ''CEC'' WHEN 2 THEN ''CARD'' WHEN 3 THEN ''CREDIT'' END||'':''||VALOARE::varchar||'' '','''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''') FROM MODPLATAIESRETAIL WHERE CODIESRETAIL = I.CODIESRETAIL) TipIncVal,
    (SELECT string_agg(CASE Coalesce(TIPPLATA,0) WHEN 0 THEN ''CASH'' WHEN 1 THEN ''CEC'' WHEN 2 THEN ''CARD'' WHEN 3 THEN ''CREDIT'' END||'' '','''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''') FROM MODPLATAIESRETAIL WHERE CODIESRETAIL = I.CODIESRETAIL) TipInc,
    Coalesce(U.Nume,''...nedefinit...'') Intocmit_nume, Coalesce(U.Prenume,''...nedefinit...'') Intocmit_prenume,
    Coalesce(U.CNP,''...nedefinit...'') Intocmit_CNP, U.BISERIA||'' ''||U.BINR Intocmit_BI,
    P.DEN_PART client_den, CAR.SIMBOL carnet_simbol, I.SERIADOC carnet_serie, CAR.DENUMIRE carnet_den, P.CODEXTERN client_codext,
    CODF.CODFISCAL client_codfisc, P.REGCOM client_reg,
    I.NRDOC doc_nr, I.DATADOC doc_data,
    SFACT.Denumire sediu,
    fnc_GetAdresa(SFACT.sector, SFACT.strada, SFACT.nr1, SFACT.nr2, SFACT.bloc, SFACT.scara, SFACT.etaj, SFACT.apart, SFACT.codpostal) sediu_adresa,
    LFACT.DEN_LOCALIT sediu_loc, JFACT.Den_Judet sediu_judet, TFACT.Den_Tara sediu_tara,
    ut.username' || 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 NCODFISCRETAIL CODF    ON CODF.COD         = I.CODFISCALRETAIL
    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 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 NPERS U                ON U.LOGONNAME      = I.USERID
    LEFT JOIN DOCCARNETE CAR         ON CAR.CODCARNET    = I.CARNETDOC
    LEFT JOIN NSEDIIPARTRETAIL SFACT ON SFACT.CODSEDIU   = I.CODSEDIURETAIL
    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 tmp_utilizator ut on i.userid = ut.codutilizator ' || gSuplJoins || '
  ORDER BY i1.indexlocal';

  CALL PRC_AL_CHECK('NART1');
  CALL PRC_AL_CHECK('NARTOBJ1');
  CALL PRC_AL_CHECK('NTVA1');

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitvanzretail_setjoinuri</obj_name>
  <obj_hashval>5c19717d2fcdb06136b2885eae127ff8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitvanzretail_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_SITVANZRETAIL.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitvanzretsint_processlist</obj_name>
  <obj_hashval>39bc3bec80de217cfa4cf89ee3cc7a86</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitvanzretsint_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSelect         varchar := '';
  sWithDC         varchar := '';
  sJoinAux         varchar := '';
  gSuplCols        VARCHAR := 'iesiriretail i, emulare e';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Florin 10.04.2024 - getAdresa
  --Adina 16.10.2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_SITVANZRETSINT.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
      VAL,
      VALTVA,
      VAL_LEI,
      VALTVA_LEI,
      TipIncVal,
      TipInc,
      Intocmit_nume,
      Intocmit_prenume,
      Intocmit_CNP,
      Intocmit_BI,
      client_den,
      carnet_simbol,
      carnet_serie,
      carnet_den,
      client_codext,
      client_codfisc,
      client_reg,
      doc_nr,
      doc_data,
      sediu,
      sediu_adresa,
      sediu_loc,
      sediu_judet,
      sediu_tara,
      username' || gUserFields || ')';

  sSelect := '
  WITH
    MAN_IESIRI AS (
    SELECT
      I1.codiesretail,
      sum(I1.TVA) tva,
      sum(CASE WHEN i1.tiplinie IN (''T'',''G'') THEN i1.RESTFACT ELSE I1.CANT*I1.PU END) VU
    FROM IESIRI1RETAIL I1
         INNER JOIN IESIRIRETAIL I ON I1.CODIESRETAIL = I.CODIESRETAIL
    WHERE coalesce(I.ANULAT,0) = 0 AND I.DATACREARE BETWEEN TO_DATE(''' || coalesce(TO_CHAR(PKG_LIST_SELECTPERIOADA_DATAORAINI(), 'DD.MM.YYYY HH24:MI'),'') || ''',''DD.MM.YYYY HH24:MI'') AND
                                                            TO_DATE(''' || coalesce(TO_CHAR(PKG_LIST_SELECTPERIOADA_DATAORAFIN(), 'DD.MM.YYYY HH24:MI'),'') || ''',''DD.MM.YYYY HH24:MI'')
    GROUP BY I1.CODIESRETAIL
    )
  SELECT
    mi.vu VAL,
    mi.tva VALTVA,
    mi.vu * coalesce(i.curs,1) VAL_LEI,
    mi.tva * coalesce(i.curs,1) VALTVA_LEI,
    (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||'':''||VALOARE::varchar||'' '','''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''')
     FROM MODPLATAIESRETAIL
     WHERE CODIESRETAIL = I.CODIESRETAIL) TipIncVal,
    (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(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''')
     FROM MODPLATAIESRETAIL
     WHERE CODIESRETAIL = I.CODIESRETAIL
    ) TipInc,
    coalesce(U.Nume,''...nedefinit...'') Intocmit_nume,
    coalesce(U.Prenume,''...nedefinit...'') Intocmit_prenume,
    coalesce(U.CNP,''...nedefinit...'') Intocmit_CNP,
    U.BISERIA||'' ''||U.BINR Intocmit_BI,
    P.DEN_PART client_den,
    CAR.SIMBOL carnet_simbol,
    I.SERIADOC carnet_serie,
    CAR.DENUMIRE carnet_den,
    P.CODEXTERN client_codext,
    CODF.CODFISCAL client_codfisc,
    P.REGCOM client_reg,
    I.NRDOC doc_nr,
    I.DATADOC doc_data,
    SFACT.Denumire sediu,
    fnc_GetAdresa(SFACT.sector, SFACT.strada, SFACT.nr1, SFACT.nr2, SFACT.bloc, SFACT.scara, SFACT.etaj, SFACT.apart, SFACT.codpostal) sediu_adresa,
    LFACT.DEN_LOCALIT sediu_loc,
    JFACT.Den_Judet sediu_judet,
    TFACT.Den_Tara sediu_tara, ut.username' || gUserAlias || '
  FROM   man_iesiri mi
        LEFT JOIN iesiriretail i         ON i.codiesretail   = mi.codiesretail
        LEFT JOIN emulare e              on e.codiesretail   = mi.codiesretail
        LEFT JOIN NCODFISCRETAIL CODF    ON CODF.COD         = I.CODFISCALRETAIL
        LEFT JOIN npart p                ON p.codpart        = i.partener
        LEFT JOIN NPERS U                ON U.LOGONNAME      = I.USERID
        LEFT JOIN DOCCARNETE CAR         ON CAR.CODCARNET    = I.CARNETDOC
        LEFT JOIN NSEDIIPARTRETAIL SFACT ON SFACT.CODSEDIU   = I.CODSEDIURETAIL
        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 tmp_utilizator ut      on i.userid         = ut.codutilizator ' || 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_sitvanzretsint_setjoinuri</obj_name>
  <obj_hashval>b0ea87cda211e1326b0d0e94694e2b1d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitvanzretsint_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_SITVANZRETSINT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_soldpart_getgnullalias</obj_name>
  <obj_hashval>52d2b81766560863f8be066c1f9c8670</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_soldpart_getgnullalias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_SOLDPART.gNullAlias'));
  RETURN ;
  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_soldpart_getgsuplcols</obj_name>
  <obj_hashval>008bd5ee1b89c6f8911e8ce024f31c82</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_soldpart_getgsuplcols(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_SOLDPART.gSuplCols'));
  RETURN ;
  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_soldpart_getgsupljoins</obj_name>
  <obj_hashval>580ffd46aca713d04b2c023dab742792</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_soldpart_getgsupljoins(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_SOLDPART.gSuplJoins'));
  RETURN ;
  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_soldpart_getguseralias</obj_name>
  <obj_hashval>67bd6daabaa7a6958263d16599720165</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_soldpart_getguseralias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_SOLDPART.gUserAlias'));
  RETURN ;
  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_soldpart_getguserfields</obj_name>
  <obj_hashval>c95ae781b4b9e57df68f2eb69b770608</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_soldpart_getguserfields(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_SOLDPART.gUserFields'));
  RETURN ;
  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_soldpart_gnullalias</obj_name>
  <obj_hashval>cf2e46d306aa586aeea3d1d99a24b5ca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_soldpart_gnullalias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_SOLDPART.gNullAlias'));
  RETURN ;
  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_soldpart_gsuplcols</obj_name>
  <obj_hashval>4dde950a755edece314c891858c73c9f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_soldpart_gsuplcols(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_SOLDPART.gSuplCols'));
  RETURN ;
  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_soldpart_gsupljoins</obj_name>
  <obj_hashval>83656c017630631a1481a0f92a9a87a5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_soldpart_gsupljoins(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_SOLDPART.gSuplJoins'));
  RETURN ;
  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_soldpart_guseralias</obj_name>
  <obj_hashval>30ff30f7d295be2d4d4d561df51ba419</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_soldpart_guseralias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_SOLDPART.gUserAlias'));
  RETURN ;
  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_soldpart_guserfields</obj_name>
  <obj_hashval>98a9bbe299f79384f3434728f5aa9c46</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_soldpart_guserfields(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_SOLDPART.gUserFields'));
  RETURN ;
  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_soldpart_setgsuplcols</obj_name>
  <obj_hashval>d82b4a34e2d0abb07d2298d25462fcae</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_soldpart_setgsuplcols(agsuplcols character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_SOLDPART.gSuplCols',agSuplCols,false);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_soldpart_setguseralias</obj_name>
  <obj_hashval>433be8423e2012a9ad9b52be66e693cc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_soldpart_setguseralias(aguseralias character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_SOLDPART.gUserAlias',agUserAlias,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_soldpart_setjoinuri</obj_name>
  <obj_hashval>831bf3a4f9295e0faa26664bc6fa5aa1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_soldpart_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 24 august 2020
  PERFORM PKG_LIST_STRUCT_SetTableSpec( (current_setting('PKG_LIST_BASE_SOLDPART.gSuplCols')));
  PERFORM PKG_LIST_STRUCT_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_soldpartini_setjoinuri</obj_name>
  <obj_hashval>af6d80c918286da0761861db9e90ba16</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_soldpartini_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 11 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_stoc_getfurn</obj_name>
  <obj_hashval>6961e9783ed0d2fa8b4c7a8a465c61cf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stoc_getfurn(INOUT wme_result numeric, INOUT pcodobiect numeric, INOUT pcodnirstoc numeric, INOUT pfurn numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
DECLARE
  vRES numeric;
BEGIN
  --Adina august 2020
  IF pCodNirstoc IS NOT NULL THEN
    vRES := pFurn;
  ELSE
    SELECT  DISTINCT LAST_VALUE(Furn) OVER (  ORDER BY DATAACHIZ , CODNIRSTOC range between unbounded preceding and unbounded following)
      INTO vRES
    FROM NirStoc
    WHERE CodObiect = pCodObiect;
  END IF;
  WME_Result :=  Coalesce(vRES, 0);
  RETURN;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stoc_pregatireserii</obj_name>
  <obj_hashval>97124bb47218da12595637c09efbd04c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stoc_pregatireserii()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Stef 12.05.2022 - curatenie PKG_LIST_BASE_UTILS CT_XXX
  DELETE FROM TMP_MANEVRA_SERII;
  DELETE FROM TMP_MANEVRA_NIRSER;
  IF (SELECT WME_RESULT FROM pkg_list_selfisamag_areSerii(NULL,NULL)) THEN
    IF (SELECT WME_RESULT FROM pkg_list_selfisamag_StocLaZi(NULL,NULL)) THEN
      INSERT INTO TMP_MANEVRA_NIRSER(CODNIRSER, CODNIRSTOC, TIPSERIE, TG, SERIE, REST)
      SELECT NSER.CodNirSer, NSER.CodNirStoc, NS.TipSerie, Coalesce(NSER.TG, NS.TG), S.Serie, NSER.Rest
      FROM nirstoc ns
        INNER JOIN nirser nser ON  nser.codnirstoc = ns.codnirstoc
        INNER JOIN nserii s    ON  s.codserie      = nser.codserie
      WHERE
            ((SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_isToateArt(NULL,NULL)) = 1 OR NS.CODOBIECT::varchar IN (SELECT valoare FROM tmp_manevra_liste WHERE filtru = 'CODOBIECT'))
        AND ((SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_getNumToateCont(NULL,NULL)) = 1 OR NS.CODIOART::varchar IN (SELECT valoare FROM tmp_manevra_liste WHERE filtru = 'CODIOART')) ;
    ELSE
      INSERT INTO TMP_MANEVRA_NIRSER(CODNIRSER, CODNIRSTOC, TIPSERIE, TG, SERIE, REST)
      WITH
        S AS
        (
          SELECT NSER.CodNirSer, NSER.CodNirStoc, NS.TipSerie, Coalesce(NSER.TG, NS.TG) TG, S.Serie, NSER.CANTNIR REST
          FROM nirstoc ns
            INNER JOIN nirser nser ON  nser.codnirstoc = ns.codnirstoc
            INNER JOIN nserii s    ON  s.codserie      = nser.codserie
          WHERE
                  ((SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_isToateArt(NULL,NULL)) = 1 OR NS.CODOBIECT::varchar IN (SELECT valoare FROM tmp_manevra_liste WHERE filtru = 'CODOBIECT'))
              AND ((SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_getNumToateCont(NULL,NULL)) = 1 OR NS.CODIOART::varchar IN (SELECT valoare FROM tmp_manevra_liste WHERE filtru = 'CODIOART'))
          UNION ALL
          SELECT NSER.CodNirSer, NSER.CodNirStoc, NS.TipSerie, Coalesce(NSER.TG, NS.TG) TG, S.Serie, CASE WHEN  L.TIPLIVR=15 THEN 1 ELSE  -1 END  * L1.CANT REST
          FROM livr l
            INNER JOIN livr1   l1   ON  l1.codlivr     = l.codlivr
            INNER JOIN nirser  nser ON  nser.codnirser = l1.codnirser
            INNER JOIN nirstoc ns   ON  ns.codnirstoc  = l1.codnirstoc
            INNER JOIN nserii  s    ON  s.codserie     = nser.codserie
          WHERE
                ((SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_isToateArt(NULL,NULL)) = 1 OR NS.CODOBIECT::varchar IN (SELECT valoare FROM tmp_manevra_liste WHERE filtru = 'CODOBIECT'))
            AND ((SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_getNumToateCont(NULL,NULL)) = 1 OR NS.CODIOART::varchar IN (SELECT valoare FROM tmp_manevra_liste WHERE filtru = 'CODIOART'))
        )
        SELECT * FROM (
          SELECT CODNIRSER, CODNIRSTOC, TIPSERIE, TG, SERIE, Sum(REST) REST
          FROM S
          GROUP BY CODNIRSER, CODNIRSTOC, TIPSERIE, TG, SERIE
        ) A_PG
        WHERE REST &lt;&gt; 0;
    END IF;
    PERFORM pkg_list_base_utils_baga_serii_in_tmp(PKG_LIST_BASE_UTILS_CT_STOC_M());
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stoc_processlist</obj_name>
  <obj_hashval>64cb1ec9d9ce5669229087beda78adc7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gSuplCols    VARCHAR := 'NART1 NART1, NARTOBJ NOBJ, NGEST NG, NART NART, NPART PROD, NUM NUM, NUM1 NUM1, NARTOBJ1 NOBJ1, NSUBUNIT SUB, NPART FURN, NMONEDE MDOC,'||
    'NLOCATII NLOC, NCONT NCONT, NUM UMALT1, NUM UMALT2, NCLASEAS NCLS, NGEST NGPROD, NCLASEA NCLA, IOART IO, TMP_LST_STOC S';

  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplJoins   VARCHAR := '';
  sWithRezUM1     TEXT := '';
  sInsert         TEXT := '';
  sInsTmpFields   TEXT := '';
  sInsTmp         TEXT := '';
  sUpdTmp         TEXT := '';
  sInsTmpNedesIes TEXT := '';
  sInsTmpNedesIn  TEXT := '';
  sInsTmpNedesTr  TEXT := '';
  sCursRef     VARCHAR := ', 1 curs_ref, 1 curs_refa';
  sInsDC       VARCHAR := '';
  sSelDC       VARCHAR := '';
  sJoinDC      VARCHAR := '';
  wmeRes       BOOLEAN;
  aSitV        NUMERIC;
  aBancaV      NUMERIC;
  aMonedaV     NUMERIC;
  sSubunitate  VARCHAR := CASE getsubunitate() WHEN 1 THEN 'ng.codsubunit' ELSE getsubunitate()::varchar END ;
  DataStoc     DATE    := pkg_list_selfisamag_getdatastoc();
  AnLunaMin    NUMERIC;
  AnLunaMax    NUMERIC;
  AnLunaLista  NUMERIC;
  AnLista      NUMERIC;
  LunaLista    NUMERIC;
  AnPrec       NUMERIC;
  LunaPrec     NUMERIC;
  vMaxCl       NUMERIC;
  vTabla1      VARCHAR := 'tmp_lst_stoc s';
  vTabla2      VARCHAR := 'nartobj nobj';
  sJoinRezUM1  VARCHAR := '';
  sColRezUM1   VARCHAR := '';
  vCount       NUMERIC;
  sVal         VARCHAR := '';
  sLimbaDenArt VARCHAR := Coalesce(fnc_GetValConstanta('LIMBADENART',GETANLUCRU(),GETLUNALUCRU()),'0');
  vGestAcces   INTEGER;
  sALL         VARCHAR := To_Char(getAnLunaLucru(), 'fm99999');
  sTipPMP      VARCHAR := '';
  sNeconforme  VARCHAR := '';
BEGIN
  --Florin 19.06.2025 - sinc. Oracle
  --Florin 23.11.2023 - sinc. Oracle
  --Florin 28.06.2023 - fixat 58710
  --Stef 27.06.2023
  CALL create_wm_temps_flag('TMP_LST_STOC');

  vGestAcces := to_number(Coalesce(fnc_getvalconstanta('GestAccesListeStoc',GETANLUCRU(),GETLUNALUCRU()),'2'));
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTVA'           , 'NTVA'        , 'NTVA.CODTVA = NART1.CODTVA',NULL,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTAMB'        , 'AA'          , 'AA.CODOBIECT = NOBJ.CODOBIECT AND AA.UMSEC = num1.codum1',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, 'NARTOBJTRAD'    , 'TRAD'        , 'TRAD.CODOBIECT = NOBJ.CODOBIECT AND TRAD.CODLIMBA = ' || sLimbaDenArt);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJ1'       , 'NOBJ1_CURENT', 'NOBJ1_CURENT.CODOBIECT = NOBJ.CODOBIECT AND ' || coalesce(sALL,'0') || ' BETWEEN NOBJ1_CURENT.ALSTART AND NOBJ1_CURENT.ALSTOP',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'PRETM'          , 'PM'          , 'PM.CODOBIECT = NOBJ.CODOBIECT AND PM.IMPLICIT = 1 AND PM.SUBUNITATEA = ' || sSubunitate,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJSUBUNIT' , 'NOBJSUB'     , 'NOBJSUB.CODOBIECT = NOBJ.CODOBIECT AND (NOBJSUB.codgest is null or NOBJSUB.codgest = 0) AND NOBJSUB.SUBUNITATE = ' || sSubunitate,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCARSUPART'     , 'NCARSUPART'  , 'NCARSUPART.CODCARSUPART = NOBJ.CODCARACT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTRECOST'     , 'CCINTR'      , 'CCINTR.CODCENTRU = Coalesce(S.ROOTCC,0)', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IOART1'         , 'IO1_CURENT'  , 'IO1_CURENT.CODIOART = IO.CODIOART AND ' || coalesce(sALL,'0') || ' BETWEEN IO1_CURENT.ALSTART AND IO1_CURENT.ALSTOP',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONT'          , 'C_CURENT'    , 'C_CURENT.CODCONT = IO1_CURENT.CONT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TRANSF'         , 'XTR'         , 'XTR.CODTRANSF = S.XCODTRANSF', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TRANSFEXT'      , 'XTREXT'      , 'XTREXT.CODTRANSF = XTR.CODTRANSF',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARI'        , 'XINTR'       , 'XINTR.CODINTR = S.XCODINTR', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARIF'       , 'XINTRF'      , 'XINTRF.CODINTR = XINTR.CODINTR',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARIP'       , 'XINTRP'      , 'XINTRP.CODINTR = XINTR.CODINTR',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI'         , 'XIES'        , 'XIES.CODIES = S.XCODIES', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRIEXT'      , 'XIESEXT'     , 'XIESEXT.CODIES = XIES.CODIES',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_STOC.gSuplCols',gSuplCols,false);

  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 := ',
    PKG_LIST_BASE_UTILS_GETCURSREFERINTA('||aMonedaV::varchar||','||aBancaV::varchar||', s.datadoc::varchar) curs_ref,
    PKG_LIST_BASE_UTILS_GETCURSREFERINTA('||aMonedaV::varchar||','||aBancaV::varchar||', s.IntratLa::varchar) curs_refa';
  END IF;

  IF (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_inclArtStoc0(NULL,NULL)) THEN
    vTabla1 := 'nartobj nobj';
    vTabla2 := 'tmp_lst_stoc s';
  END IF;

  IF (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_exclneconform(NULL,NULL)) THEN
    sNeconforme := ' and coalesce(ng.tip,0) &lt;&gt; 4 ';
  END IF;

  sWithRezUM1 := '
  WITH RUM1 AS (
    SELECT
      Sum((select coalesce(wme_result,0) from pkg_jurnal_GetSpecificCantUM1(null,Coalesce(art.relatieum1,0), ns.D1, ns.D2, ns.D3, r.rest))) cant,
      ns.codnirstoc, Coalesce(nse.codnirser,0) codnirser
    FROM nirstoc ns
      INNER JOIN nartobj   obj ON obj.codobiect = ns.codobiect
      INNER JOIN nart      art ON art.codarticol = obj.codarticol
      LEFT  JOIN nirser    nse ON nse.codnirstoc = ns.codnirstoc
      LEFT  JOIN rezervats r   ON ns.codnirstoc = r.codnirstoc AND Coalesce(nse.codnirser,0) = Coalesce(r.codnirser,0)
    GROUP BY ns.codnirstoc, Coalesce(nse.codnirser,0)
  ) ';
  sJoinRezUM1 := '';
  sColRezUM1  := 'null rezervatum1,';

  IF (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_RezUM1(NULL,NULL)) THEN
    sColRezUM1 := 'rum1.cant rezervatum1,';
    sJoinRezUM1 := 'LEFT JOIN RUM1 ON RUM1.CODNIRSTOC = NS.CODNIRSTOC AND RUM1.CODNIRSER = Coalesce(NSER.CODNIRSER,0)';
  ELSE
    sWithRezUM1 := '';
  END IF;

  SELECT AnMaxim * 12 + LunaMaxima, AnInitial * 12 + LunaInitiala INTO AnLunaMax, AnLunaMin FROM firmaluni;

  IF (SELECT WME_RESULT FROM pkg_list_selfisamag_StocLaZi(NULL,NULL)) THEN
    AnLunaLista := AnLunaMax;
  ELSE
    AnLunaLista := EXTRACT( YEAR FROM DataStoc) * 12 + EXTRACT( MONTH FROM DataStoc);
    IF  AnLunaLista &lt; AnLunaMin THEN
      AnLunaLista := AnLunaMin;
    ELSIF AnLunaLista &gt; AnLunaMax THEN
      AnLunaLista := AnLunaMax;
    END IF;
  END IF;

  SELECT pan,pluna into AnLista, LunaLista FROM PKG_LIST_BASE_UTILS_ExtractAnLuna(AnLunaLista, AnLista, LunaLista);
  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);

  sTipPMP := Coalesce(fnc_GetValConstanta('TipPMP', AnLista, LunaLista), '1');

  SELECT sInsertUMA, sSelectUMA, sJoinUMA FROM PKG_LIST_BASE_UTILS_UMA_UTILS('s.rest', 's.CodObiect', sInsDC, sSelDC, sJoinDC,NULL) INTO sInsDC, sSelDC, sJoinDC;

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

  IF  vMaxCL &gt; 0 THEN
    sJoinDC := coalesce(sJoinDC,'') || '
      LEFT JOIN (
        SELECT
          CODCLASEA ';
    FOR i in 1..vMaxCL loop
      sInsDC  := sInsDC||', CL'||i::varchar  ||', CS'||i::varchar;
      sSelDC  := sSelDC||', CL.D'||i::varchar||', CL.S'||i::varchar;
      sJoinDC := sJoinDC ||',
        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;
    sJoinDC := coalesce(sJoinDC,'') || '
        FROM TMP_PROFIT_NCLASEA
        GROUP BY CODCLASEA
      ) CL ON CL.CodClasea = NART.Clasa ';
  END IF;

  sInsTmpFields :=
  'INSERT INTO tmp_lst_stoc (
    codnirstoc, codnirser, codcertif, coddoc, tipdoc, codlocatie, gest, codgestprod, umsec, codioart, codobiect,
    intratla, anluna,
    datadoc, nrdoc, prefixdoc,
    nridoc, obsdoc, obsdoc1,
    doc, xcodtransf, xcodies, xcodintr,
    pret, pretachiz, pumaximal, adaosunitar,
    procentadaos,
    tva, tipserie, furn, codioart1, aretvaneex, mg, cont,
    d1, d2, d3, provizion, serielot, puval, prdoc, monedadoc,
    rezervat, rezervatum1, rest, restum1, restum2,
    cantser,
    serie, obsser, nrcertifser, dataprimire, dataprod, provenienta, den_tara, obscertif, stare,
    tg, zileexp,
    staredd,
    rootcc, pretorig, cursdoc
  )';

  sInsTmp := sInsTmpFields||
    sWithRezUM1||'
  SELECT
    ns.codnirstoc, nser.codnirser, c.codcertif, COALESCE(ies.codies, t.codtransf, intr.codintr) coddoc, n.tipnir tipdoc, ns.codlocatie, n.gest, ns.codgestprod,ns.umsec,ns.codioart,ns.codobiect,
    COALESCE(ns.dataachiz, n.datanir, intr.datadoc) IntratLa, COALESCE(intr.an*12+intr.luna,ies.an*12+ies.luna,t.an*12+t.luna) AnLuna,
    COALESCE(ies.datadoc,t.datadoc,intr.datadoc) datadoc, COALESCE(ies.nrdoc,t.nrdoc,intr.nrdoc) nrdoc, COALESCE(ies.prefixdoc,t.prefixdoc,intr.prefixdoc) prefixdoc,
    COALESCE(ies.nri,intr.nri) nridoc, COALESCE(ies.obs,t.obs,intr.obs) obsdoc,COALESCE(ies1.obs,substr(t1.obs,1,500),intr1.obs) obsdoc1,  --dbms_lob.substr(t1.obs,500,1)
    CASE
      WHEN n.tipnir IN (12, 13) THEN coalesce(t.prefixdoc,'''')||''.''||coalesce(t.nrdoc::varchar,'''')||''/''||coalesce(TO_CHAR(t.datadoc,''DD.MM.YYYY''),'''')
      WHEN n.tipnir IN (14,15,19,20) THEN coalesce(ies.prefixdoc,'''')||''.''||coalesce(ies.nrdoc::varchar,'''')||''/''||coalesce(TO_CHAR(Ies.datadoc,''DD.MM.YYYY''),'''')
      ELSE coalesce(intr.prefixdoc,'''')||''.''||coalesce(intr.nrdoc::varchar,'''')||''/''||coalesce(TO_CHAR(intr.datadoc,''DD.MM.YYYY''),'''')
    END doc,
    CASE WHEN n.tipnir IN (12, 13)   THEN t.codtransf  ELSE 0 END xcodtransf,
    CASE WHEN n.tipnir IN (14,15,19) THEN ies.codies   ELSE 0 END xcodies,
    CASE WHEN n.tipnir = intr.tipdoc THEN intr.codintr ELSE 0 END xcodintr,
    ns.pret, ns.pret - Coalesce(ns.adaos,0) pretachiz, ns.pumaximal, CASE WHEN (ioa1.difpret = 1) and (ioa1.aretvaneex = 1) THEN (ns.adaos -((ns.PRET*ns.tva*100)/(100+ns.tva*100))) ELSE ns.adaos END adaosunitar,
      Round(
      CASE
        WHEN ioa1.difpret &lt;&gt; 1   THEN 0
        WHEN ioa1.aretvaneex = 0 THEN 100*(Coalesce(ns.adaos,0))/(case when (ROUND(ns.pret, 4) - ROUND(Coalesce(ns.adaos,0),4))=0 then 1 else (ns.pret - Coalesce(ns.adaos,0)) end)
        WHEN ioa1.aretvaneex = 1 THEN 100*(ns.pret/(1+ns.tva)-(ROUND(ns.pret,4) - ROUND(COALESCE( ns.adaos, 0),4)))/(case when ROUND(ns.pret,4) -ROUND(COALESCE( ns.adaos,0),4)=0 then 1 else (ns.pret - ns.adaos) end)
        WHEN ioa1.aretvaneex = 2 THEN 100*((ROUND(ns.pret,4)-(ROUND(Coalesce(ns.adaos,0),4)/(1+ns.tva) )-(ROUND(ns.pret,4) - ROUND(Coalesce(ns.adaos,0),4)))/(case when ROUND(ns.pret,4) - ROUND(Coalesce(ns.adaos,0),4) = 0 then 1 else(ns.pret - Coalesce(ns.adaos,0))      end))
    end, 2) procentadaos,
    CASE WHEN (IOA1.DIFPRET = 1) AND (IOA1.ARETVANEEX = 1) THEN ns.TVA*100 ELSE 0 END tva, ns.tipserie, ns.furn, ioa1.codioart1,ioa1.aretvaneex, ioa1.mg, ioa1.cont,
    ns.d1,ns.d2,ns.d3,ns.provizion, ns.serielot,ns.puval,COALESCE(intr1root.pu,intr1.pu,ies1.pu,t1.pu) prdoc, COALESCE(intrroot.moneda, intr.moneda, ies.moneda, 0) monedadoc,
    (SELECT SUM(Coalesce(r.rest,0)) FROM REZERVATS R WHERE R.CODNIRSTOC = NS.CODNIRSTOC AND Coalesce(R.CODNIRSER,0) = COALESCE(NSER.CODNIRSER,R.CODNIRSER,0) AND Coalesce(R.REST,0) &lt;&gt; 0) rezervat,
    ' || coalesce(sColRezUM1,'') || '
    ' || coalesce(CASE WHEN (SELECT WME_RESULT FROM pkg_list_selfisamag_StocLaZi(NULL,NULL)) THEN 'Coalesce(NSER.REST,NS.REST)' ELSE 'VS.REST' END ,'') || ' REST,
    ' || coalesce(CASE WHEN (SELECT WME_RESULT FROM pkg_list_selfisamag_StocLaZi(NULL,NULL)) THEN 'Coalesce(NSER.RESTUM1,NS.RESTUM1)' ELSE 'VS.RESTUM1' END ,'') || ' RESTUM1,
    ' || coalesce(CASE WHEN (SELECT WME_RESULT FROM pkg_list_selfisamag_StocLaZi(NULL,NULL)) THEN 'Coalesce(NSER.RESTUM2,NS.RESTUM2)' ELSE 'VS.RESTUM2' END ,'') || ' RESTUM2,
    ' || coalesce(CASE WHEN  NOT (SELECT WME_RESULT FROM pkg_list_selfisamag_StocLaZi(NULL,NULL)) AND (SELECT WME_RESULT FROM pkg_list_selfisamag_areSerii(NULL,NULL)) THEN 'VS.REST' ELSE 'NSER.REST' END ,'') || ' CANTSER,
    SER.SERIE, NSER.OBS OBSSER, C.NRCERTIF NRCERTIFSER, C.DATAPRIMIRE, NSER.DATAPROD, C.PROVENIENTA, TARA.DEN_TARA, C.OBS OBSCERTIF,
    CASE NSER.STARE
      WHEN 1 THEN ''Liber''
      WHEN 2 THEN ''Restrictionat DI''
      WHEN 3 THEN ''Restrictionat DD''
      WHEN 4 THEN ''Blocat''
      WHEN 5 THEN ''Complet-verificat''
      WHEN 6 THEN ''Complet-neverificat''
      WHEN 7 THEN ''Incomplet-verificat''
      WHEN 8 THEN ''Incomplet-neverificat''
      WHEN 9 THEN ''Aprobat cant si dim''
      WHEN 10 THEN ''Aprobat documentatie''
    END stare,
    Coalesce(nser.tg,ns.tg) tg, Coalesce(nser.tg,ns.tg) - pkg_list_selfisamag_getDataRef() zileexp,
    CASE
      WHEN (Coalesce(nser.tg,ns.tg) - pkg_list_selfisamag_getDataRef() &gt; 30) OR Coalesce(nser.tg,ns.tg) IS NULL THEN ''Liber''
      WHEN Coalesce(nser.tg,ns.tg) - pkg_list_selfisamag_getDataRef() &lt; 0 THEN ''Blocat''
      ELSE ''Restrictionat''
    END staredd,
    COALESCE(intr1root.codcentru,intr1.codcentru,ies1.codcentru,t1.codcentru) rootcc, Coalesce(intr1.pu,ies1.pu,t1.pu) pretorig,
    (case when Coalesce(intr.curs,ies.curs,0)= 0 then  1 else  Coalesce(intr.curs,ies.curs,0) end) cursdoc
  FROM ';

  IF (SELECT WME_RESULT FROM pkg_list_selfisamag_StocLaZi(NULL,NULL)) THEN
    sInsTmp := coalesce(sInsTmp,'') || 'nirstoc ns ';
  ELSE
    sInsTmp := coalesce(sInsTmp,'') ||
               coalesce(CASE WHEN (SELECT WME_RESULT FROM pkg_list_selfisamag_areSerii(NULL,NULL)) THEN '('||v_stoc_luna_ser()||')' ELSE '('||v_stoc_luna()||')' END ,'') || ' vs
    INNER JOIN nirstoc ns ON ns.codnirstoc = vs.codnirstoc';
  END IF;

  sInsTmp := coalesce(sInsTmp,'') || '
    INNER JOIN nir n             ON n.codnir          = ns.codnir
    INNER JOIN ngest ng          ON ng.codgest        = n.gest' || coalesce((SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG', 'CODSUBUNIT',NULL,NULL))::varchar ,'') || '
    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 nirser nser        ON ' ||
    coalesce(CASE WHEN  NOT (SELECT WME_RESULT FROM pkg_list_selfisamag_areSerii(NULL,NULL)) THEN 'nser.codnirser = (ns.codnirstoc - ns.codnirstoc)'
                  WHEN (SELECT WME_RESULT FROM pkg_list_selfisamag_StocLaZi(NULL,NULL)) THEN 'nser.codnirstoc = ns.codnirstoc'
                  ELSE 'nser.codnirser = vs.codnirser'
             END ::varchar ,'') || '
    ' || coalesce(sJoinRezUM1::varchar ,'') || '
    LEFT JOIN nserii ser  ON ser.codserie  = nser.codserie
    LEFT JOIN certif c    ON c.codcertif   = nser.codcertif
    LEFT JOIN ntari  tara ON tara.codtara  = c.codtara
    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 ' ||
  coalesce(CASE WHEN  NOT (SELECT WME_RESULT FROM pkg_list_selfisamag_StocLaZi(NULL,NULL)) THEN '(coalesce(VS.REST, 0) &lt;&gt; 0 OR coalesce(VS.RESTUM2, 0) &lt;&gt; 0)'
                WHEN (SELECT WME_RESULT FROM pkg_list_selfisamag_areSerii(NULL,NULL)) THEN '(COALESCE(NSER.REST,NS.REST,0) &lt;&gt; 0 OR COALESCE(NSER.RESTUM2,NS.RESTUM2,0) &lt;&gt; 0)'
                ELSE '(COALESCE(NS.REST,0) &lt;&gt; 0 OR COALESCE(NS.RESTUM2,0) &lt;&gt; 0)'
           END ,'') || '
    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)';
    if vGestAcces &lt;&gt; 1 THEN
      sInsTmp := sInsTmp||' and (select PKG_NOMGEST_GESTIUNE_DEDICATA.WME_RESULT from PKG_NOMGEST_GESTIUNE_DEDICATA(null, N.GEST)) &gt; 0 ';
    end if;
    sInsTmp := sInsTmp||sNeconforme;

  IF  NOT (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_isAllTipCont(NULL,NULL)) THEN
    SELECT Max(Valoare), Count(1) INTO sVal, vCount FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODIOART';
    sInsTmp := coalesce(sInsTmp,'') || '
    AND NS.CODIOART';
    IF  vCount = 1 THEN
      sInsTmp := coalesce(sInsTmp,'') || '= ' || coalesce(sVal,'');
    ELSE
      sInsTmp := coalesce(sInsTmp,'') || '::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
    END IF;
  END IF;

  IF  NOT (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_isAllGest(NULL,NULL)) THEN
    SELECT Max(Valoare), Count(1) INTO sVal, vCount FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODGEST';
    sInsTmp := coalesce(sInsTmp,'') || '
    AND N.GEST';
    IF  vCount = 1 THEN
      sInsTmp := coalesce(sInsTmp,'') || '= ' || coalesce(sVal::varchar,'');
    ELSE
      sInsTmp := coalesce(sInsTmp,'') || '::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
    END IF;
  END IF;

  IF  (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_isToateArt(NULL,NULL)) = 0 THEN
    SELECT Max(Valoare), Count(1) INTO sVal, vCount FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODOBIECT';
    sInsTmp := coalesce(sInsTmp,'') || '
    AND NS.CODOBIECT';
    IF  vCount = 1 THEN
      sInsTmp := coalesce(sInsTmp,'') || '= ' || coalesce(sVal::varchar,'');
    ELSE
      sInsTmp := coalesce(sInsTmp,'') || '::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'') ';
    END IF;
  END IF;

if (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_inclNedes(NULL,NULL)) then
    sInsTmpNedesIes := sInsTmpFields||'
    SELECT
      0 codnirstoc, 0 codnirser, 0 codcertif, i.codies coddoc, i.tipdoc, 0 codlocatie, lv.gest, i.codgestprod, i1.umsec, lv.codioart, lv.codobiect,
      i.datadoc IntratLa, i.an*12+i.luna AnLuna,
      i.datadoc, i.nrdoc, i.prefixdoc,
      i.nri nridoc, i.obs obsdoc,i1.obs obsdoc1,
      i.prefixdoc||''.''||i.nrdoc||''/''||TO_CHAR(I.datadoc,''DD.MM.YYYY'') doc, 0 xcodtransf, 0 xcodies, 0 xcodintr,
      lv.pretinreg, lv.pretachiz, NULL pumaximal, lv.pretinreg - lv.pretachiz adaosunitar,
      CASE WHEN coalesce(lv.pretinreg,0) = 0 THEN 0 ELSE (lv.pretinreg - lv.pretachiz)/lv.pretinreg *100 END procentadaos,
      i1.tva, 0 tipserie, 0 furn, ioa1.codioart1,ioa1.aretvaneex, ioa1.mg, ioa1.cont,
      NULL d1, NULL d2, NULL d3, NULL provizion, NULL serielot, 0 puval, NULL prdoc, 0 monedadoc,
      0 rezervat, NULL rezervatum1, -L1.RESTIESVAL REST, 0 RESTUM1, 0 RESTUM2,
      0 CANTSER,
      NULL SERIE, NULL OBSSER, NULL NRCERTIFSER, NULL DATAPRIMIRE, NULL DATAPROD, NULL PROVENIENTA, NULL DEN_TARA, NULL OBSCERTIF, NULL stare,
      NULL tg, 0 zileexp,
      NULL staredd,
      0 rootcc, i1.pu pretorig,i.curs
    FROM LIVRVAL LV,
         LIVR1 L1,
         LIVR L,
         IESIRI1 I1,
         IESIRI I,
         IOART1 IOA1,
         NARTOBJ O,
         NART A,
         NGEST G
    WHERE
      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
      IOA1.CODIOART = LV.CODIOART AND I.AN*12+I.LUNA BETWEEN IOA1.ALSTART AND IOA1.ALSTOP AND
      O.CODOBIECT = LV.CODOBIECT AND
      A.CODARTICOL = O.CODARTICOL AND
      G.CodGest = LV.Gest AND
      COALESCE(L1.CODPRODCOMP, 0) + COALESCE(L1.CODPROIECT, 0) = 0 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
      COALESCE(IOA1.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 '||(SELECT wme_result FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL, 'G','CODSUBUNIT', NULL, NULL));
    if vGestAcces &lt;&gt; 1 THEN
      sInsTmpNedesIes := sInsTmpNedesIes||' AND (select PKG_NOMGEST_GESTIUNE_DEDICATA.WME_RESULT from PKG_NOMGEST_GESTIUNE_DEDICATA(null, LV.GEST)) &gt; 0 ';
    END IF;

    IF NOT (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_isAllGest(NULL,NULL)) THEN
      SELECT Max(Valoare), Count(1) INTO sVal, vCount FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODGEST';
      IF vCount = 1
      THEN sInsTmpNedesIes := sInsTmpNedesIes|| ' AND LV.GEST' ||'= '|| coalesce(sVal::varchar,'');
      ELSE sInsTmpNedesIes := sInsTmpNedesIes|| ' AND LV.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
      END IF;
    END IF;

    IF (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_isToateArt(NULL,NULL)) = 0 THEN
      SELECT Max(Valoare), Count(1) INTO sVal, vCount FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODOBIECT' ;
      IF vCount = 1
      THEN sInsTmpNedesIes := sInsTmpNedesIes||' AND LV.CODOBIECT = '|| coalesce(sVal::varchar,'');
      ELSE sInsTmpNedesIes := sInsTmpNedesIes||' AND LV.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'') ';
      END IF;
    END IF;

    sInsTmpNedesIn := sInsTmpFields||'
    SELECT
      0 codnirstoc, 0 codnirser, 0 codcertif, i.codintr coddoc, i.tipdoc, 0 codlocatie, lv.gest, i.codgestprod, i1.umsec, lv.codioart, lv.codobiect,
      i.datadoc IntratLa, i.an*12+i.luna AnLuna,
      i.datadoc, i.nrdoc, i.prefixdoc,
      i.nri nridoc, i.obs obsdoc,i1.obs obsdoc1,
      i.prefixdoc||''.''||i.nrdoc||''/''||TO_CHAR(I.datadoc,''DD.MM.YYYY'') doc, 0 xcodtransf, 0 xcodies, 0 xcodintr,
      lv.pretinreg, lv.pretachiz, NULL pumaximal, lv.pretinreg - lv.pretachiz adaosunitar,
      CASE WHEN coalesce(lv.pretinreg,0) = 0 THEN 0 ELSE (lv.pretinreg - lv.pretachiz)/lv.pretinreg *100 END procentadaos,
      i1.tva, 0 tipserie, 0 furn, ioa1.codioart1,ioa1.aretvaneex, ioa1.mg, ioa1.cont,
      NULL d1, NULL d2, NULL d3, NULL provizion, NULL serielot,0 puval, NULL prdoc, 0 monedadoc,
      0 rezervat, NULL rezervatum1, -L1.RESTIESVAL REST, 0 RESTUM1, 0 RESTUM2, 0 CANTSER,
      NULL SERIE, NULL OBSSER, NULL NRCERTIFSER, NULL DATAPRIMIRE, NULL DATAPROD, NULL PROVENIENTA, NULL DEN_TARA, NULL OBSCERTIF, NULL stare,
      NULL tg, 0 zileexp,
      NULL staredd,
      0 rootcc, i1.pu pretorig, i.curs
    FROM LIVRVAL LV,
         LIVR1 L1,
         INTRARI1 I1,
         LIVR L,
         INTRARI I,
         IOART1 IOA1,
         NARTOBJ O,
         NART A,
         NGEST G
    WHERE
      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
      IOA1.CODIOART = LV.CODIOART AND I.AN*12+I.LUNA BETWEEN IOA1.ALSTART AND IOA1.ALSTOP AND
      O.CODOBIECT = LV.CODOBIECT AND
      A.CODARTICOL = O.CODARTICOL AND
      G.CodGest = LV.Gest AND
      COALESCE(L1.CODPRODCOMP, 0) + COALESCE(L1.CODPROIECT, 0) = 0 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
      COALESCE(IOA1.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 '||(SELECT wme_result FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL, 'G','CODSUBUNIT', NULL, NULL));
   if vGestAcces &lt;&gt; 1 THEN
     sInsTmpNedesIn := sInsTmpNedesIn||' AND (select PKG_NOMGEST_GESTIUNE_DEDICATA.WME_RESULT from PKG_NOMGEST_GESTIUNE_DEDICATA(null, LV.GEST)) &gt; 0 ';
   END IF;

    IF NOT (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_isAllGest(NULL,NULL)) THEN
      SELECT Max(Valoare), Count(1) INTO sVal, vCount FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODGEST' ;
      IF vCount = 1
      THEN sInsTmpNedesIn := sInsTmpNedesIn||' AND LV.GEST = '||coalesce(sVal::varchar,'');
      ELSE sInsTmpNedesIn := sInsTmpNedesIn||' AND LV.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
      END IF;
    END IF;

    IF (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_isToateArt(NULL,NULL)) = 0 THEN
      SELECT Max(Valoare), Count(1) INTO sVal, vCount FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODOBIECT' ;
      IF vCount = 1
      THEN sInsTmpNedesIn := sInsTmpNedesIn||' AND LV.CODOBIECT = '||coalesce(sVal::varchar,'');
      ELSE sInsTmpNedesIn := sInsTmpNedesIn||' AND LV.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'') ';
      END IF;
    END IF;

    sInsTmpNedesTr := sInsTmpFields||'
    SELECT
      0 codnirstoc, 0 codnirser, 0 codcertif, T.codtransf coddoc, t.tipdoc, 0 codlocatie, lv.gest, 0 codgestprod, t1.umsec, lv.codioart, lv.codobiect,
      t.datadoc IntratLa, t.an*12+t.luna AnLuna,
      t.datadoc, t.nrdoc, t.prefixdoc,
      NULL nridoc, t.obs obsdoc,t1.obs obsdoc1,
      t.prefixdoc||''.''||t.nrdoc||''/''||TO_CHAR(t.datadoc,''DD.MM.YYYY'') doc, 0 xcodtransf, 0 xcodies, 0 xcodintr,
      lv.pretinreg, lv.pretachiz, NULL pumaximal, lv.pretinreg - lv.pretachiz adaosunitar,
      CASE WHEN coalesce(lv.pretinreg,0) = 0 THEN 0 ELSE (lv.pretinreg - lv.pretachiz)/lv.pretinreg *100 END procentadaos,
      t1.tva, 0 tipserie, 0 furn, ioa1.codioart1,ioa1.aretvaneex, ioa1.mg, ioa1.cont,
      NULL d1, NULL d2, NULL d3, NULL provizion, NULL serielot,0 puval,NULL prdoc, 0 monedadoc,
      0 rezervat, NULL rezervatum1, -L1.RESTIESVAL REST, 0 RESTUM1, 0 RESTUM2,
      0 CANTSER,
      NULL SERIE, NULL OBSSER, NULL NRCERTIFSER, NULL DATAPRIMIRE, NULL DATAPROD, NULL PROVENIENTA, NULL DEN_TARA, NULL OBSCERTIF, NULL stare,
      NULL tg, 0 zileexp,
      NULL staredd,
      0 rootcc, t1.pu pretorig, 0 curs
    FROM LIVRVAL LV,
         LIVR1 L1,
         TRANSF1 T1,
         LIVR L,
         TRANSF T,
         IOART1 IOA1,
         NARTOBJ O,
         NART A,
         NGEST G
    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
      IOA1.CODIOART = LV.CODIOART AND
      IOA1.CODIOART = LV.CODIOART AND T.AN*12+T.LUNA BETWEEN IOA1.ALSTART AND IOA1.ALSTOP AND
      O.CODOBIECT = LV.CODOBIECT AND
      A.CODARTICOL = O.CODARTICOL AND
      G.CodGest = LV.Gest AND
      COALESCE(L1.CODPRODCOMP, 0) + COALESCE(L1.CODPROIECT, 0) = 0 AND
      T.OPERAT = 1 AND T.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,'')||' AND
      COALESCE(IOA1.DESCARCAREG, 0) = 0 AND
      COALESCE(LV.CODIOART, 0) &lt;&gt; coalesce(fnc_GetValConstanta(''ContIncasareFactura'', t.An, t.Luna)::numeric, 0) AND
      L1.RESTIESVAL &lt;&gt; 0 '||(SELECT wme_result FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL, 'G','CODSUBUNIT', NULL, NULL));
    if vGestAcces &lt;&gt; 1 THEN
      sInsTmpNedesTr := sInsTmpNedesTr||' AND (select PKG_NOMGEST_GESTIUNE_DEDICATA.WME_RESULT from PKG_NOMGEST_GESTIUNE_DEDICATA(null, LV.GEST)) &gt; 0 ';
    END IF;

    IF NOT (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_isAllGest(NULL,NULL)) THEN
      SELECT Max(Valoare), Count(1) INTO sVal, vCount FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODGEST' ;
      IF vCount = 1
      THEN sInsTmpNedesTr := sInsTmpNedesTr||' AND LV.GEST = '||coalesce(sVal::varchar,'');
      ELSE sInsTmpNedesTr := sInsTmpNedesTr||' AND LV.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
      END IF;
    END IF;

    IF (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_isToateArt(NULL,NULL)) = 0 THEN
      SELECT Max(Valoare), Count(1) INTO sVal, vCount FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODOBIECT' ;
      IF vCount = 1
      THEN sInsTmpNedesTr := sInsTmpNedesTr||' AND LV.CODOBIECT = '||coalesce(sVal::varchar,'');
      ELSE sInsTmpNedesTr := sInsTmpNedesTr||'  AND LV.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'') ';
      END IF;
    END IF;
  end if;

sInsert := 'INSERT INTO ' || coalesce(TMPNAME,'') || '(
    NAV_CODDOC, NAV_TIPDOC, NAV_NIRSTOC, CODOBIECT, DEN_ARTICOL, UMSEC, DEN_IOART,DEN_GEST,LOCATIE,PRETACHIZ,PRET,TVA,
    TIPSERIE, PROCENTADAOS,DATADOC,NRDOC,PREFIXDOC, NRIDOC,OBSDOC,OBSLIN, DOCUMENT, INTRATLA,
    DEN_PART,PUMAXIMAL,
    PRODUCATOR,CODINTERN,CODEXTERN,UM_PRINC,UMALT1,UMALT2,SUBUNITATEA,CONT,DIM1,DIM2,DIM3,PUVAL,PRDOC,MONDOC,
    CLASAS,CLASA_ART,SIMBCLASA,PROVIZION, SERIELOT,REZERVAT,REZERVATUM1,VALSTOC,VALACHIZ,PROCTVA,
    VALTVA,
    TVA_UNITAR,
    PMP,PMPVALUTA,
    ADAOS,SERIE,CANTSER,OBSSER,NRCERTIFSER,DATAPRIMIRE,DATAPROD,PROVENIENTA,DEN_TARA,OBSCERTIF,STARE,
    STOC,CANT_UM_PRINC,STOC_UMALT1,STOC_UMALT2, TG,ZILEEXP, StareDD,PRETORIG, CURSDOC,
    CURS_REF, CURS_REFA' || coalesce(sInsDC,'') || gUserFields || ')
  SELECT
    s.coddoc, s.tipdoc, s.codnirstoc, nobj.codobiect, nobj.denumire, num1.den_um1, io.den_ioart, ng.den_gest, nloc.denumire locatie, s.pretachiz * num1.paritate pretachiz, s.pret * num1.paritate pret, s.tva,
    (case when s.TIPSERIE=0 then ''fara serie'' when s.TIPSERIE=1 then ''serie pe bucata'' when s.TIPSERIE=2 then ''serie pe lot'' end) tipserie,
    s.procentadaos, s.datadoc, s.nrdoc, s.prefixdoc, s.nridoc, s.obsdoc, s.obsdoc1, s.doc, s.intratla,
    (case when furn.codpart=0 then ngprod.den_gest else furn.den_part end),
    CASE
      WHEN Coalesce(nobj1.tippretmax,0) IN (1,2,3) AND Coalesce(s.pumaximal,0) &gt; 0       THEN s.pumaximal
      WHEN Coalesce(nobj1.tippretmax,0) IN (4,5,6) AND Coalesce(nobj1.pretmaximal,0) &gt; 0 THEN nobj1.pretmaximal
      ELSE 0
    END pumaximal,
    prod.den_part, nobj.codintern, nobj.codextern, num.den_um, umalt1.den_um umalt1, umalt2.den_um umalt2, sub.den_subunit, ncont.simbol, s.d1,s.d2,s.d3,s.puval,s.prdoc,mdoc.simbol,
    ncls.den_claseas,ncla.den_clasea,ncla.simbol,s.provizion, s.serielot, Coalesce(s.rezervat,0), Coalesce(s.rezervatum1,0), s.pret * s.rest valstoc, s.pretachiz*s.rest valachiz, ntva1.procent,
    CASE WHEN s.aretvaneex = 1 THEN (s.pret*ntva1.procent)* s.rest/(100+ntva1.procent) ELSE 0 END valtva,
    CASE WHEN s.aretvaneex = 1 THEN (s.pret*ntva1.procent)/(100+ntva1.procent) * num1.paritate ELSE 0 END tva_unitar,
    CASE WHEN s.mg = 3 THEN Coalesce(PKG_PMP_GET_PMP_LEI(s.codobiect,' ||
    coalesce(CASE WHEN  sTipPMP = '1' THEN '1' ELSE 'ng.codsubunit' END ::varchar ,'') || ',' || coalesce(AnLista::varchar,'') || ',' || coalesce(LunaLista::varchar,'') || '),0) ELSE 0 END pmp,
    CASE WHEN s.mg = 3 THEN Coalesce((select wme_result from PKG_PMP_GET_PMP_VALUTA_FROM_VAR(null,null)),0) ELSE 0 END pmpv,
    Coalesce(s.rest * s.adaosunitar,0), s.serie, s.cantser, s.obsser, s.nrcertifser, s.dataprimire, s.dataprod, s.provenienta, s.den_tara, s.obscertif, s.stare,
    Coalesce(s.rest/num1.paritate,0), Coalesce(s.rest,0), Coalesce(s.restum1,0), Coalesce(s.restum2,0), s.tg, s.zileexp, s.staredd, s.pretorig, s.cursdoc' || coalesce(sCursRef,'') || coalesce(sSelDC,'') || gUserAlias || '
  FROM ' || coalesce(vTabla1,'') || '
    LEFT JOIN ' || coalesce(vTabla2,'') || ' ON nobj.codobiect = s.codobiect
    LEFT JOIN nart             ON nart.codarticol  = nobj.codarticol
    LEFT JOIN ngest    ng      ON ng.codgest       = Coalesce(s.gest,nart.gestimplicita)
     LEFT JOIN ioart    io      ON io.codioart      = Coalesce(s.codioart,nart.contimplicit)
    LEFT JOIN num1             ON num1.codum1      = s.umsec
    LEFT JOIN num              ON num1.codum       = num.codum
    LEFT JOIN nartobj1 nobj1   ON nobj1.codobiect  = nobj.codobiect AND Coalesce(s.AnLuna,0) BETWEEN nobj1.alstart AND nobj1.alstop
    LEFT JOIN nart1    nart1   ON nart1.codarticol = nart.codarticol AND Coalesce(s.AnLuna,0) BETWEEN nart1.alstart AND nart1.alstop
    LEFT JOIN ntva1    ntva1   ON ntva1.codtva     = nart1.codtva AND Coalesce(s.AnLuna,0) BETWEEN ntva1.alstart AND ntva1.alstop
    LEFT JOIN nsubunit sub     ON sub.codsubunit   = ng.codsubunit
    LEFT JOIN nmonede  mdoc    ON mdoc.codmoneda   = Coalesce(s.monedadoc,0)
    LEFT JOIN npart    furn    ON furn.codpart     = (select wme_result from pkg_list_base_stoc_GetFurn(null,nobj.codobiect, s.codnirstoc, s.furn) )
    LEFT JOIN npart    prod    ON prod.codpart     = nobj.codproducator
    LEFT JOIN nlocatii nloc    ON nloc.codlocatie  = s.codlocatie
    LEFT JOIN ncont    ncont   ON ncont.codcont    = s.cont
    LEFT JOIN num      umalt1  ON nart.um1         = umalt1.codum
    LEFT JOIN num      umalt2  ON nart.um2         = umalt2.codum
    LEFT JOIN nclaseas ncls    ON ncls.codclaseas  = nart.clasastatist
    LEFT JOIN ngest    ngprod  ON ngprod.codgest   = s.codgestprod
    LEFT JOIN nclasea  ncla    ON ncla.codclasea   = nart.clasa' || coalesce(sJoinDC,'') || gSuplJoins || '
  WHERE 1 = 1';

  IF  (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_isToateArt(NULL,NULL)) = 0 AND (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_inclArtStoc0(NULL,NULL)) THEN
    sInsert := coalesce(sInsert,'') || '
      AND NOBJ.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'') ';
  END IF;
  PERFORM pkg_list_base_stoc_PregatireSerii();
  CALL PRC_AL_CHECK('NART1');
  CALL PRC_AL_CHECK('NARTOBJ1');
  CALL PRC_AL_CHECK('NTVA1');
  CALL PRC_AL_CHECK('IOART1');

  PERFORM LIST_EXECUTE_IMMEDIATE('TRUNCATE TABLE tmp_lst_stoc', aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsTmp, aListID, aListVer);
   IF (SELECT WME_RESULT FROM pkg_list_selfisamag_inclNedes(NULL,NULL)) then
     PERFORM LIST_EXECUTE_IMMEDIATE(sInsTmpNedesIes, aListID, aListVer);
     PERFORM LIST_EXECUTE_IMMEDIATE(sInsTmpNedesIn,  aListID, aListVer);
     PERFORM LIST_EXECUTE_IMMEDIATE(sInsTmpNedesTr,  aListID, aListVer);
  END IF;

  IF NOT (SELECT WME_RESULT FROM pkg_list_selfisamag_areSerii(NULL,NULL)) AND (Instr(Upper(gUserAlias), 'S.SERII') &gt; 0) THEN
    sUpdTmp :=
    'UPDATE tmp_lst_stoc tmp
    SET SERII =
        (
          SELECT fnc_array_to_vc3200(array_agg(ser.serie||CASE WHEN nser.rest &lt;&gt; 1 THEN ''(''||nser.rest::varchar||'')'' ELSE '''' END ORDER BY ser.serie, nser.rest ))
          FROM';
    IF (SELECT WME_RESULT FROM pkg_list_selfisamag_StocLaZi(NULL,NULL)) THEN
      sUpdTmp := sUpdTmp||' nirser nser LEFT JOIN nserii ser ON ser.codserie = nser.codserie';
    ELSE
      sUpdTmp := sUpdTmp||' ( '||v_stoc_luna_ser()||' ) nser
            LEFT JOIN nirser xser ON xser.codnirser = nser.codnirser
            LEFT JOIN nserii ser  ON ser.codserie = xser.codserie';
    END IF;
    sUpdTmp := sUpdTmp||'
          WHERE nser.codnirstoc = tmp.codnirstoc AND nser.rest &lt;&gt; 0
        )';
    PERFORM LIST_EXECUTE_IMMEDIATE(sUpdTmp, aListID, aListVer);
  END IF;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  PERFORM pkg_list_Struct_GOLESTE_PARAM();
  PERFORM pkg_list_Struct_ADAUGA_PARAM('DATA STOC', to_char(DataStoc, 'DD.MM.YYYY'));
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stoc_processlist_faratuning</obj_name>
  <obj_hashval>8494a7c806b511564be1efd5297984b3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stoc_processlist_faratuning(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gSuplCols    VARCHAR := 'NART1 NART1, NARTOBJ NOBJ, NGEST NG, NART NART, NPART PROD, NUM NUM, NUM1 NUM1, NARTOBJ1 NOBJ1, NSUBUNIT SUB, NPART FURN, NMONEDE MDOC,'||
                           'NLOCATII NLOC, NCONT NCONT, NUM UMALT1, NUM UMALT2, NCLASEAS NCLS, NGEST NGPROD, NCLASEA NCLA, IOART IO, TMP_LST_STOC S';
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplJoins   VARCHAR := '';
  sInsert      VARCHAR := '';
  sInsTmp      VARCHAR := '';
  sCursRef     VARCHAR := ', 1 curs_ref, 1 curs_refa';
  sInsDC       VARCHAR := '';
  sSelDC       VARCHAR := '';
  sJoinDC      VARCHAR := '';
  aSitV        NUMERIC;
  aBancaV      NUMERIC;
  aMonedaV     NUMERIC;
  sSubunitate  VARCHAR := CASE getsubunitate() WHEN 1 THEN 'ng.codsubunit' ELSE getsubunitate()::varchar END ;
  DataStoc     DATE    := pkg_list_selfisamag_getdatastoc();
  AnLunaMin    NUMERIC;
  AnLunaMax    NUMERIC;
  AnLunaLista  NUMERIC;
  AnLista      NUMERIC;
  LunaLista    NUMERIC;
  AnPrec       NUMERIC;
  LunaPrec     NUMERIC;
  vMaxCl       NUMERIC;
  vTabla1      VARCHAR := 'tmp_lst_stoc s';
  vTabla2      VARCHAR := 'nartobj nobj';
  sJoinRezUM1  VARCHAR := '';
  sColRezUM1   VARCHAR := '';
  vCount       NUMERIC;
  sVal         VARCHAR := '';
  sLimbaDenArt VARCHAR := Coalesce(fnc_GetValConstanta('LIMBADENART',GETANLUCRU(),GETLUNALUCRU()),'0');
  sALL         VARCHAR := To_Char(getAnLunaLucru(), 'fm99999');
  sTipPMP      VARCHAR := '';
  wmeRes       BOOLEAN;
  sUpdTmp      varchar;
BEGIN
  --Stef 12.05.2022
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTVA'            , 'NTVA', 'NTVA.CODTVA = NART1.CODTVA',NULL,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTAMB'         , 'AA', 'AA.CODOBIECT = NOBJ.CODOBIECT AND AA.UMSEC = num1.codum1',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, 'NARTOBJTRAD'     , 'TRAD', 'TRAD.CODOBIECT = NOBJ.CODOBIECT AND TRAD.CODLIMBA = ' || sLimbaDenArt);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJ1'        , 'NOBJ1_CURENT', 'NOBJ1_CURENT.CODOBIECT = NOBJ.CODOBIECT AND ' || coalesce(sALL,'0') || ' BETWEEN NOBJ1_CURENT.ALSTART AND NOBJ1_CURENT.ALSTOP',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'PRETM'           , 'PM'     , 'PM.CODOBIECT = NOBJ.CODOBIECT AND PM.IMPLICIT = 1 AND PM.SUBUNITATEA = ' || sSubunitate,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJSUBUNIT'  , 'NOBJSUB', 'NOBJSUB.CODOBIECT = NOBJ.CODOBIECT AND NOBJSUB.SUBUNITATE = ' || sSubunitate,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCARSUPART'      , 'NCARSUPART', 'NCARSUPART.CODCARSUPART = NOBJ.CODCARACT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTRECOST'      , 'CCINTR', 'CCINTR.CODCENTRU = Coalesce(S.ROOTCC,0)', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IOART1'          , 'IO1_CURENT', 'IO1_CURENT.CODIOART = IO.CODIOART AND ' || coalesce(sALL,'0') || ' BETWEEN IO1_CURENT.ALSTART AND IO1_CURENT.ALSTOP',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONT'           , 'C_CURENT', 'C_CURENT.CODCONT = IO1_CURENT.CONT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TRANSF'          , 'XTR', 'XTR.CODTRANSF = S.XCODTRANSF', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TRANSFEXT'       , 'XTREXT', 'XTREXT.CODTRANSF = XTR.CODTRANSF',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARI'         , 'XINTR', 'XINTR.CODINTR = S.XCODINTR', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARIF'        , 'XINTRF', 'XINTRF.CODINTR = XINTR.CODINTR',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARIP'        , 'XINTRP', 'XINTRP.CODINTR = XINTR.CODINTR',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI'          , 'XIES', 'XIES.CODIES = S.XCODIES', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRIEXT'       , 'XIESEXT', 'XIESEXT.CODIES = XIES.CODIES',NULL);

  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_STOC.gSuplCols',gSuplCols,false);

  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''))) curs_ref,
      (select wme_result from PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null, ' || coalesce(aMonedaV::varchar,'') || ',' || coalesce(aBancaV::varchar,'') || ', to_char(s.IntratLa,''dd.mm.yyyy''))) curs_refa';
  END IF;

  IF (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_inclArtStoc0(NULL,NULL)) THEN
    vTabla1 := 'nartobj nobj';
    vTabla2 := 'tmp_lst_stoc s';
  END IF;

  sJoinRezUM1 := '';
  sColRezUM1 := 'null rezervatum1,';

  IF (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_RezUM1(NULL,NULL)) THEN
    sColRezUM1 := 'rum1.cant rezervatum1,';
    sJoinRezUM1 := 'LEFT JOIN (select sum((select coalesce(wme_result,0) from pkg_jurnal_GetSpecificCantUM1(null,Coalesce(nart.relatieum1,0), ns.D1, ns.D2, ns.D3, r.rest))) cant, ns.codnirstoc, Coalesce(nse.codnirser,0) codnirser
                               from nirstoc ns
                                    inner join nartobj obj on obj.codobiect = ns.codobiect
                                    inner join nart        on nart.codarticol = obj.codarticol
                                    left  join nirser nse  on nse.codnirstoc = ns.codnirstoc
                                    left  join rezervats r on ns.codnirstoc = r.codnirstoc and Coalesce(nse.codnirser,0) = Coalesce(r.codnirser,0)
                               group by ns.codnirstoc, Coalesce(nse.codnirser,0)
                               ) RUM1 ON RUM1.CODNIRSTOC = NS.CODNIRSTOC AND RUM1.CODNIRSER = Coalesce(NSER.CODNIRSER,0)';
  END IF;

  SELECT AnMaxim * 12 + LunaMaxima, AnInitial * 12 + LunaInitiala INTO AnLunaMax, AnLunaMin FROM firmaluni;

  IF (SELECT WME_RESULT FROM pkg_list_selfisamag_StocLaZi(NULL,NULL)) THEN
    AnLunaLista := AnLunaMax;
  ELSE
    AnLunaLista := EXTRACT( YEAR FROM DataStoc) * 12 + EXTRACT( MONTH FROM DataStoc);
    IF  AnLunaLista &lt; AnLunaMin THEN
      AnLunaLista := AnLunaMin;
    ELSIF
      AnLunaLista &gt; AnLunaMax
    THEN
      AnLunaLista := AnLunaMax;
    END IF;
  END IF;

  SELECT pan,pluna into AnLista, LunaLista FROM PKG_LIST_BASE_UTILS_ExtractAnLuna(AnLunaLista, AnLista, LunaLista);
  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);

  --sTipPMP := Coalesce((SELECT PKG_CATEGCONST_GetValConstanta.WME_RESULT FROM PKG_CATEGCONST_GetValConstanta(NULL,'TipPMP', AnLista, LunaLista)), '1');
  sTipPMP := Coalesce(fnc_GetValConstanta('TipPMP', AnLista, LunaLista), '1');

  --PERFORM PKG_LIST_BASE_UTILS_UMA_UTILS('s.rest', 's.CodObiect', sInsDC, sSelDC, sJoinDC,NULL);
  SELECT sInsertUMA, sSelectUMA, sJoinUMA FROM PKG_LIST_BASE_UTILS_UMA_UTILS('s.rest', 's.CodObiect', sInsDC, sSelDC, sJoinDC,NULL) INTO sInsDC, sSelDC, sJoinDC;

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

  IF  vMaxCL &gt; 0 THEN
    sJoinDC := coalesce(sJoinDC,'') || '
      LEFT JOIN (
        SELECT
          CODCLASEA ';
    FOR i in 1..vMaxCL loop
      sInsDC  := sInsDC||', CL'||i::varchar  ||', CS'||i::varchar;
      sSelDC  := sSelDC||', CL.D'||i::varchar||', CL.S'||i::varchar;
      sJoinDC := sJoinDC ||',
        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;
    sJoinDC := coalesce(sJoinDC,'') || '
        FROM TMP_PROFIT_NCLASEA
        GROUP BY CODCLASEA
      ) CL ON CL.CodClasea = NART.Clasa ';
  END IF;

sInsTmp := 'INSERT INTO tmp_lst_stoc (
    codnirstoc, coddoc, tipdoc, codlocatie, gest, codgestprod,
    umsec, codioart, codobiect, intratla, anluna, datadoc, nrdoc,
    prefixdoc, nridoc, obsdoc, obsdoc1, doc, xcodtransf, xcodies,
    xcodintr, pret, pretachiz, pumaximal, adaosunitar,
    procentadaos, tva, tipserie, furn, codioart1, aretvaneex, mg,
    cont, d1, d2, d3, provizion, serielot, puval, prdoc,
    monedadoc, rezervat, rezervatum1, rest, restum1, restum2,
    cantser, serie, obsser, nrcertifser, dataprimire, dataprod,
    provenienta, den_tara, obscertif, stare, tg, zileexp,
    staredd, rootcc, pretorig, cursdoc
  )
  SELECT
    ns.codnirstoc, COALESCE(ies.codies, t.codtransf, intr.codintr) coddoc, n.tipnir tipdoc, ns.codlocatie, n.gest, ns.codgestprod,ns.umsec,ns.codioart,ns.codobiect,
    COALESCE(ns.dataachiz, n.datanir, intr.datadoc) IntratLa, COALESCE(intr.an*12+intr.luna,ies.an*12+ies.luna,t.an*12+t.luna) AnLuna,
    COALESCE(ies.datadoc,t.datadoc,intr.datadoc) datadoc, COALESCE(ies.nrdoc,t.nrdoc,intr.nrdoc) nrdoc, COALESCE(ies.prefixdoc,t.prefixdoc,intr.prefixdoc) prefixdoc,
    COALESCE(ies.nri,intr.nri) nridoc, COALESCE(ies.obs,t.obs,intr.obs) obsdoc,COALESCE(ies1.obs,substr(t1.obs,1,500),intr1.obs) obsdoc1,  --dbms_lob.substr(t1.obs,500,1)
    CASE
      WHEN n.tipnir IN (12, 13) THEN coalesce(t.prefixdoc,'''')||''.''||coalesce(t.nrdoc::varchar,'''')||''/''||coalesce(TO_CHAR(t.datadoc,''DD.MM.YYYY''),'''')
      WHEN n.tipnir IN (14,15,19) THEN coalesce(ies.prefixdoc,'''')||''.''||coalesce(ies.nrdoc::varchar,'''')||''/''||coalesce(TO_CHAR(Ies.datadoc,''DD.MM.YYYY''),'''')
      ELSE coalesce(intr.prefixdoc,'''')||''.''||coalesce(intr.nrdoc::varchar,'''')||''/''||coalesce(TO_CHAR(intr.datadoc,''DD.MM.YYYY''),'''')
    END doc,
    CASE WHEN n.tipnir IN (12, 13)   THEN t.codtransf  ELSE 0 END xcodtransf,
    CASE WHEN n.tipnir IN (14,15,19) THEN ies.codies   ELSE 0 END xcodies,
    CASE WHEN n.tipnir = intr.tipdoc THEN intr.codintr ELSE 0 END xcodintr,
    ns.pret, ns.pret - Coalesce(ns.adaos,0) pretachiz, ns.pumaximal, CASE WHEN (ioa1.difpret = 1) and (ioa1.aretvaneex = 1) THEN (ns.adaos -((ns.PRET*ns.tva*100)/(100+ns.tva*100))) ELSE ns.adaos END adaosunitar,
    Round(
      CASE
        WHEN ioa1.difpret &lt;&gt; 1   THEN 0
        WHEN ioa1.aretvaneex = 0 THEN 100*(Coalesce(ns.adaos,0))/(case when (ns.pret - Coalesce(ns.adaos,0))=0 then 1 else (ns.pret - Coalesce(ns.adaos,0)) end)
        WHEN ioa1.aretvaneex = 1 THEN 100*(ns.pret/(1+ns.tva)-(ns.pret - ns.adaos))/(case when (ns.pret - ns.adaos)=0 then 1 else (ns.pret - ns.adaos) end)
        WHEN ioa1.aretvaneex = 2 THEN 100*((ns.pret-(Coalesce(ns.adaos,0)/(1+ns.tva) )-(ns.pret - Coalesce(ns.adaos,0)))/(case when (ns.pret - Coalesce(ns.adaos,0))=0 then 1 else (ns.pret - Coalesce(ns.adaos,0)) end) )
      END,2) procentadaos,
    CASE WHEN (IOA1.DIFPRET = 1) AND (IOA1.ARETVANEEX = 1) THEN ns.TVA*100 ELSE 0 END tva, ns.tipserie, ns.furn, ioa1.codioart1,ioa1.aretvaneex, ioa1.mg, ioa1.cont,
    ns.d1,ns.d2,ns.d3,ns.provizion, ns.serielot,ns.puval,COALESCE(intr1root.pu,intr1.pu,ies1.pu,t1.pu) prdoc, COALESCE(intrroot.moneda, intr.moneda, ies.moneda, 0) monedadoc,
    (SELECT SUM(Coalesce(r.rest,0)) FROM REZERVATS R WHERE R.CODNIRSTOC = NS.CODNIRSTOC AND Coalesce(R.CODNIRSER,0) = COALESCE(NSER.CODNIRSER,R.CODNIRSER,0) AND Coalesce(R.REST,0) &lt;&gt; 0) rezervat,
    ' || coalesce(sColRezUM1,'') || '
    ' || coalesce(CASE WHEN (SELECT WME_RESULT FROM pkg_list_selfisamag_StocLaZi(NULL,NULL)) THEN 'Coalesce(NSER.REST,NS.REST)' ELSE 'VS.REST' END ,'') || ' REST,
    ' || coalesce(CASE WHEN (SELECT WME_RESULT FROM pkg_list_selfisamag_StocLaZi(NULL,NULL)) THEN 'Coalesce(NSER.RESTUM1,NS.RESTUM1)' ELSE 'VS.RESTUM1' END ,'') || ' RESTUM1,
    ' || coalesce(CASE WHEN (SELECT WME_RESULT FROM pkg_list_selfisamag_StocLaZi(NULL,NULL)) THEN 'Coalesce(NSER.RESTUM2,NS.RESTUM2)' ELSE 'VS.RESTUM2' END ,'') || ' RESTUM2,
    ' || coalesce(CASE WHEN  NOT (SELECT WME_RESULT FROM pkg_list_selfisamag_StocLaZi(NULL,NULL)) AND (SELECT WME_RESULT FROM pkg_list_selfisamag_areSerii(NULL,NULL)) THEN 'VS.REST' ELSE 'NSER.REST' END ,'') || ' CANTSER,
    SER.SERIE, NSER.OBS OBSSER, C.NRCERTIF NRCERTIFSER, C.DATAPRIMIRE, NSER.DATAPROD, C.PROVENIENTA, TARA.DEN_TARA, C.OBS OBSCERTIF,
    (case when NSER.STARE=1 then ''Liber'' when NSER.STARE=2 then ''Restrictionat DI'' when NSER.STARE=3 then ''Restrictionat DD'' when NSER.STARE=4 then ''Blocat'' end) stare,
    Coalesce(nser.tg,ns.tg) tg, Coalesce(nser.tg,ns.tg) - pkg_list_selfisamag_getDataRef() zileexp,
    CASE
      WHEN (Coalesce(nser.tg,ns.tg) - pkg_list_selfisamag_getDataRef() &gt; 30) OR Coalesce(nser.tg,ns.tg) IS NULL THEN ''Liber''
      WHEN Coalesce(nser.tg,ns.tg) - pkg_list_selfisamag_getDataRef() &lt; 0 THEN ''Blocat''
      ELSE ''Restrictionat''
    END staredd,
    COALESCE(intr1root.codcentru,intr1.codcentru,ies1.codcentru,t1.codcentru) rootcc, Coalesce(intr1.pu,ies1.pu,t1.pu) pretorig,
    (case when Coalesce(intr.curs,ies.curs,0)= 0 then  1 else  Coalesce(intr.curs,ies.curs,0) end) cursdoc
  FROM ';

  IF (SELECT WME_RESULT FROM pkg_list_selfisamag_StocLaZi(NULL,NULL))
  THEN
    sInsTmp := coalesce(sInsTmp,'') || 'nirstoc ns ';
  ELSE
    sInsTmp := coalesce(sInsTmp,'') ||
               coalesce(CASE WHEN (SELECT WME_RESULT FROM pkg_list_selfisamag_areSerii(NULL,NULL)) THEN '('||v_stoc_luna_ser()||')' ELSE '('||v_stoc_luna()||')' END ,'') || ' vs
    INNER JOIN nirstoc ns ON ns.codnirstoc = vs.codnirstoc';
  END IF;
  sInsTmp := coalesce(sInsTmp,'') || '
    INNER JOIN nir n    ON n.codnir = ns.codnir
    INNER JOIN ngest ng ON ng.codgest = n.gest' ||
    coalesce((SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG', 'CODSUBUNIT',NULL,NULL))::varchar ,'') || '
    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 nirser nser        ON ' ||
    coalesce(CASE WHEN  NOT (SELECT WME_RESULT FROM pkg_list_selfisamag_areSerii(NULL,NULL)) THEN 'nser.codnirser = (ns.codnirstoc - ns.codnirstoc)'
                  WHEN (SELECT WME_RESULT FROM pkg_list_selfisamag_StocLaZi(NULL,NULL)) THEN 'nser.codnirstoc = ns.codnirstoc'
                  ELSE 'nser.codnirser = vs.codnirser'
             END ::varchar ,'') || '
    ' || coalesce(sJoinRezUM1::varchar ,'') || '
    LEFT JOIN nserii ser   ON ser.codserie = nser.codserie
    LEFT JOIN certif c     ON c.codcertif = nser.codcertif
    LEFT JOIN ntari tara   ON tara.codtara = c.codtara
     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 ' ||
  coalesce(CASE WHEN  NOT (SELECT WME_RESULT FROM pkg_list_selfisamag_StocLaZi(NULL,NULL)) THEN '(VS.REST &lt;&gt; 0 OR VS.RESTUM2 &lt;&gt; 0)'
                WHEN (SELECT WME_RESULT FROM pkg_list_selfisamag_areSerii(NULL,NULL)) THEN '(COALESCE(NSER.REST,NS.REST,0) &lt;&gt; 0 OR COALESCE(NSER.RESTUM2,NS.RESTUM2,0) &lt;&gt; 0)'
                ELSE '(COALESCE(NS.REST,0) &lt;&gt; 0 OR COALESCE(NS.RESTUM2,0) &lt;&gt; 0)'
           END ,'') || '
    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)';

  IF  NOT (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_isAllTipCont(NULL,NULL)) THEN
    SELECT Max(Valoare), Count(1) INTO sVal, vCount FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODIOART';
    sInsTmp := coalesce(sInsTmp,'') || '
    AND NS.CODIOART';
    IF  vCount = 1 THEN
      sInsTmp := coalesce(sInsTmp,'') || '= ' || coalesce(sVal,'');
    ELSE
      sInsTmp := coalesce(sInsTmp,'') || '::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
    END IF;
  END IF;

  IF  NOT (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_isAllGest(NULL,NULL)) THEN
    SELECT Max(Valoare), Count(1) INTO sVal, vCount FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODGEST';
    sInsTmp := coalesce(sInsTmp,'') || '
    AND N.GEST';
    IF  vCount = 1
    THEN
      sInsTmp := coalesce(sInsTmp,'') || '= ' || coalesce(sVal::varchar,'');
    ELSE
      sInsTmp := coalesce(sInsTmp,'') || '::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
    END IF;
  END IF;

  IF  (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_isToateArt(NULL,NULL)) = 0 THEN
    SELECT Max(Valoare), Count(1) INTO sVal, vCount FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODOBIECT';
    sInsTmp := coalesce(sInsTmp,'') || '
    AND NS.CODOBIECT';
    IF  vCount = 1 THEN
      sInsTmp := coalesce(sInsTmp,'') || '= ' || coalesce(sVal::varchar,'');
    ELSE
      sInsTmp := coalesce(sInsTmp,'') || '::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'') ';
    END IF;
  END IF;

sInsert := 'INSERT INTO ' || coalesce(TMPNAME,'') || '(
    NAV_CODDOC, NAV_TIPDOC, NAV_NIRSTOC, CODOBIECT, DEN_ARTICOL, UMSEC, DEN_IOART,DEN_GEST,LOCATIE,PRETACHIZ,PRET,TVA,
    TIPSERIE, PROCENTADAOS,DATADOC,NRDOC,PREFIXDOC, NRIDOC,OBSDOC,OBSLIN, DOCUMENT, INTRATLA,
    DEN_PART,PUMAXIMAL,
    PRODUCATOR,CODINTERN,CODEXTERN,UM_PRINC,UMALT1,UMALT2,SUBUNITATEA,CONT,DIM1,DIM2,DIM3,PUVAL,PRDOC,MONDOC,
    CLASAS,CLASA_ART,SIMBCLASA,PROVIZION, SERIELOT,REZERVAT,REZERVATUM1,VALSTOC,VALACHIZ,PROCTVA,
    VALTVA,
    TVA_UNITAR,
    PMP,PMPVALUTA,
    ADAOS,SERIE,CANTSER,OBSSER,NRCERTIFSER,DATAPRIMIRE,DATAPROD,PROVENIENTA,DEN_TARA,OBSCERTIF,STARE,
    STOC,CANT_UM_PRINC,STOC_UMALT1,STOC_UMALT2, TG,ZILEEXP, StareDD,PRETORIG, CURSDOC,
    CURS_REF, CURS_REFA' || coalesce(sInsDC,'') || gUserFields || ')
  SELECT
    s.coddoc, s.tipdoc, s.codnirstoc, nobj.codobiect, nobj.denumire, num1.den_um1, io.den_ioart, ng.den_gest, nloc.denumire locatie, s.pretachiz * num1.paritate pretachiz, s.pret * num1.paritate pret, s.tva,
    (case when s.TIPSERIE=0 then ''fara serie'' when s.TIPSERIE=1 then ''serie pe bucata'' when s.TIPSERIE=2 then ''serie pe lot'' end) tipserie,
    s.procentadaos, s.datadoc, s.nrdoc, s.prefixdoc, s.nridoc, s.obsdoc, s.obsdoc1, s.doc, s.intratla,
    (case when furn.codpart=0 then ngprod.den_gest else furn.den_part end),
    CASE
      WHEN Coalesce(nobj1.tippretmax,0) IN (1,2,3) AND Coalesce(s.pumaximal,0) &gt; 0       THEN s.pumaximal
      WHEN Coalesce(nobj1.tippretmax,0) IN (4,5,6) AND Coalesce(nobj1.pretmaximal,0) &gt; 0 THEN nobj1.pretmaximal
      ELSE 0
    END pumaximal,
    prod.den_part, nobj.codintern, nobj.codextern, num.den_um, umalt1.den_um umalt1, umalt2.den_um umalt2, sub.den_subunit, ncont.simbol, s.d1,s.d2,s.d3,s.puval,s.prdoc,mdoc.simbol,
    ncls.den_claseas,ncla.den_clasea,ncla.simbol,s.provizion, s.serielot, Coalesce(s.rezervat,0), Coalesce(s.rezervatum1,0), s.pret * s.rest valstoc, s.pretachiz*s.rest valachiz, ntva1.procent,
    CASE WHEN s.aretvaneex = 1 THEN (s.pret*ntva1.procent)* s.rest/(100+ntva1.procent) ELSE 0 END valtva,
    CASE WHEN s.aretvaneex = 1 THEN (s.pret*ntva1.procent)/(100+ntva1.procent) * num1.paritate ELSE 0 END tva_unitar,
    CASE WHEN s.mg = 3 THEN Coalesce(PKG_PMP_GET_PMP_LEI(s.codobiect,' ||
    coalesce(CASE WHEN  sTipPMP = '1' THEN '1' ELSE 'ng.codsubunit' END ::varchar ,'') || ',' || coalesce(AnLista::varchar,'') || ',' || coalesce(LunaLista::varchar,'') || '),0) ELSE 0 END pmp,
    CASE WHEN s.mg = 3 THEN Coalesce((select wme_result from PKG_PMP_GET_PMP_VALUTA_FROM_VAR(null,null)),0) ELSE 0 END pmpv,
    Coalesce(s.rest * s.adaosunitar,0), s.serie, s.cantser, s.obsser, s.nrcertifser, s.dataprimire, s.dataprod, s.provenienta, s.den_tara, s.obscertif, s.stare,
    Coalesce(s.rest/num1.paritate,0), Coalesce(s.rest,0), Coalesce(s.restum1,0), Coalesce(s.restum2,0), s.tg, s.zileexp, s.staredd, s.pretorig, s.cursdoc' || coalesce(sCursRef,'') || coalesce(sSelDC,'') || gUserAlias || '
  FROM ' || coalesce(vTabla1,'') || '
    LEFT JOIN ' || coalesce(vTabla2,'') || ' ON nobj.codobiect = s.codobiect
    LEFT JOIN nart     ON nart.codarticol = nobj.codarticol
    LEFT JOIN ngest ng ON ng.codgest = Coalesce(s.gest,nart.gestimplicita)
     LEFT JOIN ioart io ON io.codioart = Coalesce(s.codioart,nart.contimplicit)
    LEFT JOIN num1     ON num1.codum1 = s.umsec
    LEFT JOIN num      ON num1.codum = num.codum
    LEFT JOIN nartobj1 nobj1 ON nobj1.codobiect = nobj.codobiect AND Coalesce(s.AnLuna,0) BETWEEN nobj1.alstart AND nobj1.alstop
    LEFT JOIN nart1 nart1 ON nart1.codarticol = nart.codarticol AND Coalesce(s.AnLuna,0) BETWEEN nart1.alstart AND nart1.alstop
    LEFT JOIN ntva1 ntva1 ON ntva1.codtva = nart1.codtva AND Coalesce(s.AnLuna,0) BETWEEN ntva1.alstart AND ntva1.alstop
    LEFT JOIN nsubunit sub  ON sub.codsubunit = ng.codsubunit
    LEFT JOIN nmonede mdoc  ON mdoc.codmoneda = Coalesce(s.monedadoc,0)
    LEFT JOIN npart furn    ON furn.codpart = (select wme_result from pkg_list_base_stoc_GetFurn(null,nobj.codobiect, s.codnirstoc, s.furn) )
    LEFT JOIN npart prod    ON prod.codpart = nobj.codproducator
    LEFT JOIN nlocatii nloc ON nloc.codlocatie = s.codlocatie
    LEFT JOIN ncont ncont   ON ncont.codcont = s.cont
    LEFT JOIN num umalt1    ON nart.um1 = umalt1.codum
    LEFT JOIN num umalt2    ON nart.um2 = umalt2.codum
    LEFT JOIN nclaseas ncls ON ncls.codclaseas = nart.clasastatist
    LEFT JOIN ngest ngprod  ON ngprod.codgest = s.codgestprod
    LEFT JOIN nclasea ncla  ON ncla.codclasea = nart.clasa' || coalesce(sJoinDC,'') || gSuplJoins || '
  WHERE 1 = 1';

  IF  (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_isToateArt(NULL,NULL)) = 0 AND (SELECT WME_RESULT FROM PKG_LIST_SELFISAMAG_inclArtStoc0(NULL,NULL))
  THEN
    sInsert := coalesce(sInsert,'') || '
      AND NOBJ.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'') ';
  END IF;

  PERFORM pkg_list_base_stoc_PregatireSerii();
  CALL PRC_AL_CHECK('NART1');
  CALL PRC_AL_CHECK('NARTOBJ1');
  CALL PRC_AL_CHECK('NTVA1');
  CALL PRC_AL_CHECK('IOART1');

  PERFORM LIST_EXECUTE_IMMEDIATE('TRUNCATE TABLE tmp_lst_stoc', aListID, aListVer);
--INSERT INTO x(view_name,test) values('bs1',sInsTmp);
--INSERT INTO x(view_name,test) values('bs2',sInsert);
--RETURN;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsTmp, aListID, aListVer);

  IF NOT (SELECT WME_RESULT FROM pkg_list_selfisamag_areSerii(NULL,NULL)) AND (Instr(Upper(gUserAlias), 'S.SERII') &gt; 0) THEN
    sUpdTmp :=
    'UPDATE tmp_lst_stoc tmp
    SET SERII =
        (
          SELECT fnc_array_to_vc3200(array_agg(ser.serie||CASE WHEN nser.rest &lt;&gt; 1 THEN ''(''||nser.rest::varchar||'')'' ELSE '''' END ORDER BY ser.serie, nser.rest ))
          FROM';
    IF (SELECT WME_RESULT FROM pkg_list_selfisamag_StocLaZi(NULL,NULL)) THEN
      sUpdTmp := sUpdTmp||' nirser nser LEFT JOIN nserii ser ON ser.codserie = nser.codserie';
    ELSE
      sUpdTmp := sUpdTmp||' ( '||v_stoc_luna_ser()||' ) nser
            LEFT JOIN nirser xser ON xser.codnirser = nser.codnirser
            LEFT JOIN nserii ser  ON ser.codserie = xser.codserie';
    END IF;
    sUpdTmp := sUpdTmp||'
          WHERE nser.codnirstoc = tmp.codnirstoc AND nser.rest &lt;&gt; 0
        )';
    PERFORM LIST_EXECUTE_IMMEDIATE(sUpdTmp, aListID, aListVer);
    COMMIT;
  END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  PERFORM pkg_list_Struct_GOLESTE_PARAM();
  PERFORM pkg_list_Struct_ADAUGA_PARAM('DATA STOC', to_char(DataStoc, 'DD.MM.YYYY'));
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stoc_setjoinuri</obj_name>
  <obj_hashval>0dc895425f49d0dc1b8b3462be4ceb9b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stoc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina august 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_STOC.gSuplCols', true));
  PERFORM Pkg_List_Struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stoccontrol_processlist</obj_name>
  <obj_hashval>e8b24e28c386cbf78a51bdded629fa1e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stoccontrol_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSelect         varchar := '';
  sFiltruI         varchar := '';
  sFiltruS         varchar := '';
  sCondCantP       varchar := '';
  sIJoin           varchar := '';
  sICant           varchar := '';
  sIGest           varchar := '';
  gSuplCols        VARCHAR := 'NPERS AG, NGEST G, NARTOBJ O, NART A, NUM U, NCLASEA CA';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vDupaData        boolean := current_setting('PKG_LIST_SELPERART.vDupaData' , true)::boolean;
  vDataFin        varchar := current_setting('PKG_LIST_SELPERART.vDataFin'  , true);
  vDataIni        varchar := current_setting('PKG_LIST_SELPERART.vDataIni'  , true);
  vLunaAnFin      NUMERIC := current_setting('PKG_LIST_SELPERART.vLunaAnFin', true)::numeric;
  vLunaAnIni      NUMERIC := current_setting('PKG_LIST_SELPERART.vLunaAnIni', true)::numeric;
  vFiltruArt      NUMERIC := current_setting('PKG_LIST_SELPERART.vFiltruArt', true)::numeric;
  vExtra1          boolean := current_setting('PKG_LIST_SELPERART.vExtra1'   , true)::boolean;
BEGIN
  --Adina 04 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_STOCCONTROL.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  IF vDupaData THEN
    sFiltruI := '
    WHERE i.datadoc &lt;= To_Date(''' || coalesce(vDataFin,'') || ''',''dd.mm.yyyy'')';
    sCondCantP := 'i.datadoc &gt;= To_Date(''' || coalesce(vDataIni,'') || ''',''dd.mm.yyyy'')';
  ELSE
    sFiltruI := '
      WHERE i.an*12+i.luna &lt;= ' || coalesce(vLunaAnFin::varchar,'0');
    sCondCantP := 'i.an*12+i.luna &gt;= ' || coalesce(vLunaAnIni::varchar,'0');
  END IF;

  IF  vFiltruArt = 2 THEN
    sFiltruS := '
    WHERE a.clasa::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODCLASEA'')';
    sFiltruI := sFiltruI || '
        AND a.clasa::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODCLASEA'')';
  ELSIF vFiltruArt = 1 THEN
    sFiltruS := '
    WHERE o.codobiect::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')';
    sFiltruI := sFiltruI || '
        AND o.codobiect::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')';
  END IF;

  IF vExtra1 THEN
    sIGest := 'coalesce(n.gest, 0)';
    sICant := 'l1.cant';
    sIJoin := '
        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 nirstoc ns ON ns.codnirstoc = l1.codnirstoc
        INNER JOIN nir     n  ON n.codnir      = ns.codnir
        INNER JOIN iesiri1 i1 ON i1.codies1    = l1.codies1';
  ELSE
    sIGest := 'coalesce(ag.codgest, 0)';
    sICant := 'i1.cant';
    sIJoin := '
        INNER JOIN iesiri1 i1 ON i1.codies = i.codies';
  END IF;

  sFiltruI := sFiltruI || '
        AND i1.tiplinie = ''=''';
  sInsert := 'INSERT INTO ' || tmpName || '(AGENT, ART, UM, CANTIESPER, DATANIR1, STOCMOM, NRSEDII, NRSEDIIX, CANTLIVR1, CANTLIVRX, MEDLUNVANZ, NRZILE' || gUserFields || ')';
  sSelect := '
  WITH
  S AS (
    SELECT n.gest, ns.codobiect, Min(n.datanir) datanir1, Sum(ns.rest) stocmom
    FROM nartobj o
      INNER JOIN nart    a  ON a.codarticol = o.codarticol
      INNER JOIN nirstoc ns ON ns.codobiect = o.codobiect
      INNER JOIN nir     n  ON n.codnir     = ns.codnir ' || sFiltruS || '
    GROUP BY n.gest, ns.codobiect
  ),
  AA AS
  (
   select agent, codgest, codobiect, codlocatie, persoanafizica, sum(cantlivr1) cantlivr1
   from
    (
     SELECT
        coalesce(i.agent, 0) agent, ' || sIGest || ' codgest, i1.codobiect, i.codlocatie, p.persoanafizica,
        case when p.persoanafizica=1 then 0 else ' || sICant || ' end cantlivr1,
        dense_rank() over(partition by coalesce(i.agent, 0), ' || sIGest || ', i1.codobiect, i.codlocatie, p.persoanafizica order by i.datadoc asc, i.codies asc) NR
      FROM iesiri i
        INNER JOIN npart   p  ON p.codpart    = i.partener
        INNER JOIN npers   ag ON ag.codpers   = i.agent ' || sIJoin || '
        INNER JOIN nartobj o  ON o.codobiect  = i1.codobiect
        INNER JOIN nart    a  ON a.codarticol = o.codarticol ' || sFiltruI || '
    ) AA_PG
    WHERE NR=1
    GROUP BY agent, codgest, codobiect, codlocatie, persoanafizica
  ),
  I AS (
    SELECT A_PG.agent, Sum(Sediu1) NRSEDII, Sum(SediuX) NRSEDIIX, A_PG.codgest, A_PG.codobiect, Min(primaies) primaies, Sum(cantiesper) cantiesper,
           Sum(a.cantlivr1) cantlivr1,
           Sum(cantlivr) cantlivr
    FROM (
      SELECT
        coalesce(i.agent, 0) agent, ' || sIGest || ' codgest, i1.codobiect, i.codlocatie, p.persoanafizica,
        Min(i.datadoc) primaies,
        (case when p.persoanafizica=1 then 0 else 1 end) Sediu1,
        CASE WHEN p.persoanafizica = 1 THEN 0 WHEN Min(i.codies) = Max(i.codies) THEN 0 ELSE 1 END SediuX,
        Sum(CASE WHEN ' || sCondCantP || ' THEN ' || sICant || ' ELSE 0 END) cantiesper, '||
      --aa  Sum((case when p.persoanafizica=1 then 0 else ' || sICant || ' end)) KEEP (Dense_Rank first ORDER BY i.datadoc, i.codies) cantlivr1,
        'Sum(' || sICant || ') cantlivr
      FROM iesiri i
        INNER JOIN npart   p  ON p.codpart    = i.partener
        INNER JOIN npers   ag ON ag.codpers   = i.agent' || sIJoin || '
        INNER JOIN nartobj o  ON o.codobiect  = i1.codobiect
        INNER JOIN nart    a  ON a.codarticol = o.codarticol' || sFiltruI || '
      GROUP BY coalesce(i.agent, 0), ' || sIGest || ', i1.codobiect, i.codlocatie, p.persoanafizica
      ) A_PG
        inner join aa a on  a.agent=A_PG.agent and a.codgest=A_PG.codgest and a.codobiect=A_PG.codobiect and a.codlocatie=A_PG.codlocatie and a.persoanafizica=A_PG.persoanafizica
    GROUP BY A_PG.agent, A_PG.codgest, A_PG.codobiect
  )
  SELECT
    AG.NUme||(case when AG.CodPers is NULL then '''' else '' ''||AG.PRENUME end) Agent,
    O.Denumire ART, U.Den_UM UM, coalesce(I.CANTIESPER, 0) CANTIESPER, S.DATANIR1, S.STOCMOM, coalesce(I.NRSEDII,0) NRSEDII, coalesce(I.NRSEDIIX,0) NRSEDIIX,
    coalesce(I.CANTLIVR1,0) CANTLIVR1, coalesce(CANTLIVR-CANTLIVR1,0) CANTLIVRX,
    CASE WHEN to_date('''||coalesce(vDataFin,'')||''',''dd.mm.yyyy'') &gt; S.DATANIR1 THEN coalesce(CANTLIVR-CANTLIVR1,0)*30/(to_date('''||coalesce(vDataFin,'')||''',''dd.mm.yyyy'') - S.DATANIR1) ELSE 0 END MEDLUNVANZ,
    To_Date(''' || coalesce(vDataFin,'') || ''',''dd.mm.yyyy'') - S.DATANIR1 NRZILE ' || gUserAlias || '
  FROM S
    LEFT JOIN i          ON i.codobiect  = s.codobiect AND i.codgest = s.gest
    LEFT JOIN npers   ag ON ag.codpers   = i.agent
    LEFT JOIN nartobj o  ON o.codobiect  = s.codobiect
    LEFT JOIN nart    a  ON a.codarticol = o.codarticol
    LEFT JOIN num     u  ON u.codum      = a.um
    LEFT JOIN nclasea ca On ca.codclasea = a.clasa
    LEFT JOIN ngest   g  ON g.codgest    = s.gest' || gSuplJoins;
--INSERT INTO x(view_name,test) values('na',sInsert || sSelect); RETURN;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stoccritic_processlist</obj_name>
  <obj_hashval>3f3a2ececaf0200db94860485311b3f2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stoccritic_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       varchar := '';
  sColMinMax     varchar := ', NAOS.STOCMIN, NAOS.STOCMED, NAOS.STOCMAX';
  gSuplCols      VARCHAR := 'NARTOBJ NAO, NARTOBJSUBUNIT NAOS, NPART NP, NART NA, NUM NUM';
   gUserFields    VARCHAR := '';
  gUserAlias     VARCHAR := '';
  gNullAlias     VARCHAR := '';
  gSuplJoins     VARCHAR := '';
BEGIN
  --Adina 20.04.2021 - sinc.Oracle
  --Adina 03 septembrie 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_STOCCRITIC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  IF  getSUBUNITATE() = 1 THEN
    sColMinMax := ', NAO.STOCMIN, NAO.STOCMED, NAO.STOCMAX';
  END IF;

  sInsert :=
  'INSERT INTO ' || tmpName || '(ART, UM, STOC, STOCMIN, STOCMED, STOCMAX, DIF, COMENZI, REZERVARI, PROD, CODEXTERN, CODINTERN' || gUserFields || ')
  WITH
    STOCART AS (
      SELECT NS.CODOBIECT, SUM(NS.REST) STOC
      FROM NIRSTOC NS
            INNER JOIN NIR       ON NIR.CODNIR  = NS.CODNIR
            LEFT  JOIN INTRARI I ON I.CODINTR   = NIR.CODINTR
            LEFT  JOIN TRANSF  T ON T.CODTRANSF = NIR.CODTRANSF ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL, 'coalesce(I.SUBUNITATEA, T.SUBUNITATEA)', 'WHERE',NULL),'') || '
      GROUP BY CODOBIECT),
    STOCREZ AS (
      SELECT CODOBIECT, SUM((case when C.TIPDOC= 8 then C1.RESTACCEPTAT else 0 end)) COMENZI, SUM((case when C.TIPDOC= 18 then C1.RESTACCEPTAT else 0 end)) REZERVARI
      FROM COMANDA1 C1 INNER JOIN COMANDA C ON C.CODCOMANDA = C1.CODCOMANDA
      WHERE C1.RESTACCEPTAT &lt;&gt; 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || '
            AND C.OPERAT = 1 AND COALESCE(C.ANULAT,0) = 0 AND COALESCE(C.INCHISA,0) = 0
            AND COALESCE(C.DISPLIVRARE,0) = 0
      GROUP BY C1.CODOBIECT)
  SELECT
    NAO.DENUMIRE , NUM.DEN_UM ,S.STOC' || sColMinMax;

  IF  getSUBUNITATE() = 1 THEN
    sInsert := sInsert || ',
    CASE
      WHEN coalesce(NAO.STOCMIN,0) &lt;&gt; 0 AND S.STOC &lt; coalesce(NAO.STOCMIN,0) THEN S.STOC - coalesce(NAO.STOCMIN,0)
      WHEN coalesce(NAO.STOCMAX,0) &lt;&gt; 0 AND S.STOC &gt; coalesce(NAO.STOCMAX,0) THEN S.STOC - coalesce(NAO.STOCMAX,0)
      ELSE 0
    END DIFERENTA,';
  ELSE
    sInsert := sInsert || ',
    CASE
      WHEN coalesce(NAOS.STOCMIN,0) &lt;&gt; 0 AND S.STOC &lt; coalesce(NAOS.STOCMIN,0) THEN S.STOC - coalesce(NAOS.STOCMIN,0)
      WHEN coalesce(NAOS.STOCMAX,0) &lt;&gt; 0 AND S.STOC &gt; coalesce(NAOS.STOCMAX,0) THEN S.STOC - coalesce(NAOS.STOCMAX,0)
      ELSE 0
    END DIFERENTA,';
  END IF;

  sInsert := sInsert || '
    coalesce(SR.COMENZI,0) COMENZI, coalesce(SR.REZERVARI,0) REZERVARI, NP.DEN_PART PRODUCATOR, NAO.CODEXTERN, NAO.CODINTERN' || gUserAlias || '
  FROM STOCART S
    INNER JOIN NARTOBJ        NAO  ON NAO.CODOBIECT  = S.CODOBIECT
    LEFT  JOIN NARTOBJSUBUNIT NAOS ON NAOS.CODOBIECT = NAO.CODOBIECT and (NAOS.codgest is null or NAOS.codgest = 0) AND NAOS.SUBUNITATE = ' || coalesce(getSUBUNITATE()::varchar,'') || '
    LEFT  JOIN STOCREZ        SR   ON SR.CODOBIECT   = S.CODOBIECT
    LEFT  JOIN NPART          NP   ON NP.CODPART     = NAO.CODPRODUCATOR
    LEFT  JOIN NART           NA   ON NA.CODARTICOL  = NAO.CODARTICOL
    LEFT  JOIN NUM                 ON NUM.CODUM      = NA.UM' || gSuplJoins;

  IF  getSUBUNITATE() &lt; 2 THEN
    sInsert := sInsert || '
    WHERE (coalesce(NAO.STOCMIN,0) &lt;&gt; 0 AND S.STOC &lt; coalesce(NAO.STOCMIN,0)) OR (coalesce(NAO.STOCMAX,0) &lt;&gt; 0 AND S.STOC &gt; coalesce(NAO.STOCMAX,0))  ';
  ELSE
    sInsert := sInsert || '
    WHERE (coalesce(NAOS.STOCMIN,0) &lt;&gt; 0 AND S.STOC &lt; coalesce(NAOS.STOCMIN,0)) OR (coalesce(NAOS.STOCMAX,0) &lt;&gt; 0 AND S.STOC &gt; coalesce(NAOS.STOCMAX,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_stoccritic_setjoinuri</obj_name>
  <obj_hashval>9247dfceb8c27321c5f0ea43bb3248ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stoccritic_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 03 septembrie 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_STOCCRITIC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_getdatafin</obj_name>
  <obj_hashval>db4413801b526c96bb2d3ca851fd3ff1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_getdatafin(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Adina iulie 2020
WME_Result :=  to_char( current_setting('PKG_LIST_BASE_STOCEP.vDataFin', true)::date, 'dd.mm.yyyy');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_getdataini</obj_name>
  <obj_hashval>1a0efa4bd73bab496052e17f6d9158dc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_getdataini(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
  --Adina iulie 2020
WME_Result :=  to_char( current_setting('PKG_LIST_BASE_STOCEP.vDataIni', true)::date, 'dd.mm.yyyy');
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_getgnullalias</obj_name>
  <obj_hashval>cced0c4c46a91628a1661773ade23aa8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_getgnullalias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.gNullAlias'));
  RETURN ;
  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_stocep_getgsuplcols</obj_name>
  <obj_hashval>39a4b67049d25530dabfe5c5a8377ada</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_getgsuplcols(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.gSuplCols'));
  RETURN ;
  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_stocep_getgsupljoins</obj_name>
  <obj_hashval>8f9bf79e081cbbf3354b5af7beec8f60</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_getgsupljoins(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.gSuplJoins'));
  RETURN ;
  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_stocep_getguseralias</obj_name>
  <obj_hashval>2af3cc6da1fca3b1b636786afabcdf01</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_getguseralias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.gUserAlias'));
  RETURN ;
  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_stocep_getguserfields</obj_name>
  <obj_hashval>716d0b731d0d73397d82e6fcd0560582</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_getguserfields(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.gUserFields'));
  RETURN ;
  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_stocep_getjoinfilterart</obj_name>
  <obj_hashval>381ed0fdc650f88fd7969bd0fd5a2215</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_getjoinfilterart(aliasobj character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  jnArtFilter   VARCHAR(3000) := '';
  vToateClaseArt     boolean := current_setting('PKG_LIST_BASE_STOCEP.vTClaseArt', true)::boolean;
BEGIN
  --Florin 19.10.2022 - fixat 55962
  --Florin 26.07.2022 - sinc. Oracle
  IF not vToateClaseArt THEN
    jnArtFilter := ' INNER JOIN NARTOBJ NAO ON NAO.CODOBIECT = '||aliasObj||'.CODOBIECT
                     LEFT JOIN NART NA ON NA.CODARTICOL = NAO.CODARTICOL ' ;
  END IF;
  return jnArtFilter;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_getsdatafin</obj_name>
  <obj_hashval>2871a4a2991fe3dcbf72ccc05768de85</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_getsdatafin(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.sDataFin'));
  RETURN ;
  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_stocep_getsdataini</obj_name>
  <obj_hashval>1df314f65f0d879f79b4508776ced971</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_getsdataini(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.sDataIni'));
  RETURN ;
  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_stocep_getvdatafin</obj_name>
  <obj_hashval>0dd3505fd0f7607ba105f3858882e4ea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_getvdatafin(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.vDataFin'));
  RETURN ;
  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_stocep_getvdataini</obj_name>
  <obj_hashval>872243f664046baf92b0bad949bd5fd3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_getvdataini(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.vDataIni'));
  RETURN ;
  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_stocep_getvinclepuiz</obj_name>
  <obj_hashval>c72d886579f15805bfbaceb0830c65af</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_getvinclepuiz(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.vInclEpuiz'));
  RETURN ;
  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_stocep_getvindcrest</obj_name>
  <obj_hashval>cec02c3e5f627b836c0e925d1bce4249</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_getvindcrest(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_LIST_BASE_STOCEP.vIndCrest')),'999999999999999999');
  RETURN ;
  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_stocep_getvtipmedie</obj_name>
  <obj_hashval>326702a50b03fe8f064cbb76342394ef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_getvtipmedie(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_LIST_BASE_STOCEP.vTipMedie')),'999999999999999999');
  RETURN ;
  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_stocep_getvtoategest</obj_name>
  <obj_hashval>34318d2c3226fd3c696762085042345b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_getvtoategest(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.vToateGest'));
  RETURN ;
  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_stocep_getvultachiz</obj_name>
  <obj_hashval>e800828c5b6d7a391de02ce2052640d5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_getvultachiz(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.vUltAchiz'));
  RETURN ;
  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_stocep_getwherefilterart</obj_name>
  <obj_hashval>df1dd357b7eac167405e6152dc6f9715</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_getwherefilterart(aliasobj character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  whArtFilter VARCHAR(3000) := '';
  vToateClaseArt     boolean := current_setting('PKG_LIST_BASE_STOCEP.vToateClaseArt', true)::boolean;
  vToateArticole     boolean := current_setting('PKG_LIST_BASE_STOCEP.vToateArt', true)::boolean;
BEGIN
  --Florin 28.09.2022 - fixat 55716
  --Florin 26.07.2022 - sinc. Oracle
  IF not vToateClaseArt THEN
    whArtFilter := ' AND NA.CLASA::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODCLASEA'') ';
  ELSE
    IF not vToateArticole THEN
      whArtFilter := ' AND '||aliasObj||'.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'') ';
    END IF;
  END IF;
  return whArtFilter;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_gnullalias</obj_name>
  <obj_hashval>242dafededa16c84192b77e5270083db</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_gnullalias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.gNullAlias'));
  RETURN ;
  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_stocep_gsuplcols</obj_name>
  <obj_hashval>357f679a1ce06f7060fb1c15c4acdd2e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_gsuplcols(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.gSuplCols'));
  RETURN ;
  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_stocep_gsupljoins</obj_name>
  <obj_hashval>f1f09733ae13df4673f475d4afeac0e3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_gsupljoins(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.gSuplJoins'));
  RETURN ;
  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_stocep_guseralias</obj_name>
  <obj_hashval>9aed7b0b883ab1da5c98300126d24220</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_guseralias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.gUserAlias'));
  RETURN ;
  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_stocep_guserfields</obj_name>
  <obj_hashval>b015826d1fbd6aa1b4f9e90fbbb312f0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_guserfields(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.gUserFields'));
  RETURN ;
  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_stocep_sdatafin</obj_name>
  <obj_hashval>7f64d748711a18c5a86a4a2372e799b1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_sdatafin(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.sDataFin'));
  RETURN ;
  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_stocep_sdataini</obj_name>
  <obj_hashval>e1cb3ea5c94cee3f93a3dfec1993885b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_sdataini(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.sDataIni'));
  RETURN ;
  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_stocep_setgnullalias</obj_name>
  <obj_hashval>b61a5938c33f5ce6217cedfb8bab08c1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_setgnullalias(agnullalias character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_STOCEP.gNullAlias',agNullAlias,false);
end;
$function$
</obj_text>
</row>

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

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_setjoinuri</obj_name>
  <obj_hashval>0a32ff4fa7854474af7a0b174274f72b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 03 septembrie 2020 -aranjat
  PERFORM Pkg_List_Struct_SetTableSpec( (current_setting('PKG_LIST_BASE_STOCEP.gSuplCols')));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_setparams</obj_name>
  <obj_hashval>4b3422adc96d9975503067f5318380ed</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_setparams(pdataini character varying, pdatafin character varying, ptipmedie numeric, pindcrest numeric, ptoatafirma boolean DEFAULT (1)::boolean, ptoategest boolean DEFAULT (1)::boolean, pinclepuiz boolean DEFAULT (0)::boolean, pultachiz boolean DEFAULT (0)::boolean, ptoateart boolean DEFAULT (0)::boolean, pcodjob1 numeric DEFAULT 0, ptoateclaseart numeric DEFAULT 1, ptoatearticole numeric DEFAULT 1)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vALIni numeric := 0;
  vALFin numeric := 0;
BEGIN
  --Florin 19.10.2022 - fixat 55962
  --Florin 25.07.2022 - sinc. Oracle
  --Laura 13.10.2021 - sinc Oracle 13.10.2021
  --Adina iulie + 03 septembrie 2020
  perform set_config('PKG_LIST_BASE_STOCEP.sDataIni',pDataIni,false);
  perform set_config('PKG_LIST_BASE_STOCEP.sDataFin',pDataFin,false);

  IF  COALESCE( pCodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC( pCodJob1, current_setting('PKG_LIST_BASE_STOCEP.sDataIni', true), current_setting('PKG_LIST_BASE_STOCEP.sDataFin', true), vALIni, vALFin);
  END IF;

  perform set_config('PKG_LIST_BASE_STOCEP.vDataIni'        , To_Date(current_setting('PKG_LIST_BASE_STOCEP.sDataIni', true), 'dd.mm.yyyy')::varchar,false);
  perform set_config('PKG_LIST_BASE_STOCEP.vDataFin'        , To_Date(current_setting('PKG_LIST_BASE_STOCEP.sDataFin', true), 'dd.mm.yyyy')::varchar,false);
  perform set_config('PKG_LIST_BASE_STOCEP.sDataIni'        , 'To_date(''' || (current_setting('PKG_LIST_BASE_STOCEP.sDataIni', true)) || ''',''dd.mm.yyyy'')',false);
  perform set_config('PKG_LIST_BASE_STOCEP.sDataFin'        , 'To_date(''' || (current_setting('PKG_LIST_BASE_STOCEP.sDataFin', true)) || ''',''dd.mm.yyyy'')',false);
  perform set_config('PKG_LIST_BASE_STOCEP.vTipMedie'       , to_char(pTipMedie,'999999999999999999'),false);
  perform set_config('PKG_LIST_BASE_STOCEP.vIndCrest'       , to_char(pIndCrest,'999999999999999999'),false);
  perform set_config('PKG_LIST_BASE_STOCEP.vToataFirma'     , pToataFirma::varchar,false);
  perform set_config('PKG_LIST_BASE_STOCEP.vToateGest'      , pToateGest::varchar, false);
  perform set_config('PKG_LIST_BASE_STOCEP.vInclEpuiz'      , pInclEpuiz::varchar, false);
  perform set_config('PKG_LIST_BASE_STOCEP.vToateArt'       , pToateArt::varchar, false);
  perform set_config('PKG_LIST_BASE_STOCEP.vTClaseArt'      , (pToateClaseArt = 1)::varchar, false);
  perform set_config('PKG_LIST_BASE_STOCEP.vTArticole'      , (pToateArticole = 1)::varchar, false);
  perform set_config('PKG_LIST_BASE_STOCEP.vUltAchiz'       , pUltAchiz::varchar,  false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_setparams_x</obj_name>
  <obj_hashval>c4f6cd8587a04e22394aee0a27b093b9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_setparams_x(pdataini character varying, pdatafin character varying, ptipmedie numeric, pindcrest numeric, ptoatafirma boolean DEFAULT (1)::boolean, ptoategest boolean DEFAULT (1)::boolean, pinclepuiz boolean DEFAULT (0)::boolean, pultachiz boolean DEFAULT (0)::boolean, pcodjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vALIni numeric := 0;
  vALFin numeric := 0;
BEGIN
  --Adina iulie + 03 septembrie 2020
  perform set_config('PKG_LIST_BASE_STOCEP.sDataIni',pDataIni,false);
  perform set_config('PKG_LIST_BASE_STOCEP.sDataFin',pDataFin,false);

  IF  COALESCE( pCodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC( pCodJob1, current_setting('PKG_LIST_BASE_STOCEP.sDataIni', true), current_setting('PKG_LIST_BASE_STOCEP.sDataFin', true), vALIni, vALFin);
  END IF;

  perform set_config('PKG_LIST_BASE_STOCEP.vDataIni'   , To_Date(current_setting('PKG_LIST_BASE_STOCEP.sDataIni', true), 'dd.mm.yyyy')::varchar,false);
  perform set_config('PKG_LIST_BASE_STOCEP.vDataFin'   , To_Date(current_setting('PKG_LIST_BASE_STOCEP.sDataFin', true), 'dd.mm.yyyy')::varchar,false);
  perform set_config('PKG_LIST_BASE_STOCEP.sDataIni'   , 'To_date(''' || (current_setting('PKG_LIST_BASE_STOCEP.sDataIni', true)) || ''',''dd.mm.yyyy'')',false);
  perform set_config('PKG_LIST_BASE_STOCEP.sDataFin'   , 'To_date(''' || (current_setting('PKG_LIST_BASE_STOCEP.sDataFin', true)) || ''',''dd.mm.yyyy'')',false);
  perform set_config('PKG_LIST_BASE_STOCEP.vTipMedie'  , to_char(pTipMedie,'999999999999999999'),false);
  perform set_config('PKG_LIST_BASE_STOCEP.vIndCrest'  , to_char(pIndCrest,'999999999999999999'),false);
  perform set_config('PKG_LIST_BASE_STOCEP.vToataFirma', pToataFirma::varchar,false);
  perform set_config('PKG_LIST_BASE_STOCEP.vToateGest' , pToateGest::varchar, false);
  perform set_config('PKG_LIST_BASE_STOCEP.vInclEpuiz' , pInclEpuiz::varchar, false);
  perform set_config('PKG_LIST_BASE_STOCEP.vUltAchiz'  , pUltAchiz::varchar,  false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_setsdatafin</obj_name>
  <obj_hashval>741a6b193c335c5374f20347bcf9c6a8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_setsdatafin(asdatafin character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_STOCEP.sDataFin',asDataFin,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_setsdataini</obj_name>
  <obj_hashval>2a04257194dfeb324ee4a113d2c4239f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_setsdataini(asdataini character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_STOCEP.sDataIni',asDataIni,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_setvdatafin</obj_name>
  <obj_hashval>a76f67b8af91913e796eaad55f5117e4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_setvdatafin(avdatafin date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_STOCEP.vDataFin',avDataFin,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_setvdataini</obj_name>
  <obj_hashval>802c79fc76644cc9af7522476175c1e2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_setvdataini(avdataini date)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_STOCEP.vDataIni',avDataIni,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_setvinclepuiz</obj_name>
  <obj_hashval>0942d5011588277ed6b35ba8e5c43099</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_setvinclepuiz(avinclepuiz boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_STOCEP.vInclEpuiz',avInclEpuiz,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_setvindcrest</obj_name>
  <obj_hashval>5188f42e582eef541bf7310d560d5442</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_setvindcrest(avindcrest numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_STOCEP.vIndCrest',to_char(avIndCrest,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_setvtipmedie</obj_name>
  <obj_hashval>0b3fdabbfa2a478d8b1950e040fd7399</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_setvtipmedie(avtipmedie numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_STOCEP.vTipMedie',to_char(avTipMedie,'999999999999999999'),false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_setvtoatafirma</obj_name>
  <obj_hashval>9fe2341003d64978f1047fcc8248536c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_setvtoatafirma(avtoatafirma boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_STOCEP.vToataFirma',avToataFirma,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_setvtoategest</obj_name>
  <obj_hashval>ad7cc51c3f9c862e24a63e8488b11d87</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_setvtoategest(avtoategest boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_STOCEP.vToateGest',avToateGest,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_setvultachiz</obj_name>
  <obj_hashval>390bfea5de2172cf14b793320e1aaad1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_setvultachiz(avultachiz boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_STOCEP.vUltAchiz',avUltAchiz,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_vdatafin</obj_name>
  <obj_hashval>4c35da807b3f6b7ee4c5a6852064bcb7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_vdatafin(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.vDataFin'));
  RETURN ;
  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_stocep_vdataini</obj_name>
  <obj_hashval>73ed5dcca1fc75fed6e05dc34908c2dd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_vdataini(INOUT wme_result date, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.vDataIni'));
  RETURN ;
  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_stocep_vinclepuiz</obj_name>
  <obj_hashval>df5a32c1dbddae3c110cc40692ae7c66</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_vinclepuiz(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.vInclEpuiz'));
  RETURN ;
  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_stocep_vindcrest</obj_name>
  <obj_hashval>187d8a0db7dc94dc38fb5903e6d9a7da</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_vindcrest(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_LIST_BASE_STOCEP.vIndCrest')),'999999999999999999');
  RETURN ;
  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_stocep_vtipmedie</obj_name>
  <obj_hashval>cf5c44b78baff364fd00090f2a003b3f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_vtipmedie(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := TO_NUMBER((current_setting('PKG_LIST_BASE_STOCEP.vTipMedie')),'999999999999999999');
  RETURN ;
  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_stocep_vultachiz</obj_name>
  <obj_hashval>91e9ef5bb4057999b57c376a5f4fe1a9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_vultachiz(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.vUltAchiz'));
  RETURN ;
  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_stocexp_getrootcodnir</obj_name>
  <obj_hashval>fae2daeb6fcb2f83335119dffdcd2c69</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocexp_getrootcodnir(pcodnirstoc numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  vCodNir numeric;
BEGIN
  --Adina 03 septembrie 2020
  SELECT CODNIR INTO vCodNir
  FROM
  (
    with recursive cte (CODNIRSTOC, CODNIRSTOCPARINTE, nivel, visited, root_id, CODNIR) AS
    (
     select CODNIRSTOC,
            CODNIRSTOCPARINTE,
             0 as nivel,
             CODNIRSTOC::varchar as visited,
             CODNIRSTOC as root_id,
             CODNIR
     from   NIRSTOC e
     where  CODNIRSTOC = pCODNIRSTOC
     union all
     select c.CODNIRSTOC,
            c.CODNIRSTOCPARINTE,
            p.nivel + 1,
            p.visited ||';'|| c.CODNIRSTOC::varchar,
            p.root_id,
            c.CODNIR
     from NIRSTOC c
          join cte p on p.CODNIRSTOCPARINTE = c.CODNIRSTOC
     where instr(p.visited,c.CODNIRSTOC::varchar)=0
    )
   SELECT e.* FROM cte e
   WHERE not exists (select * from cte p where p.CODNIRSTOC = e.CODNIRSTOCPARINTE)
  ) A_PG
  ;

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

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocofe_baga_dinamic_cols</obj_name>
  <obj_hashval>5c09089cf1c2313aa58f8beafbf30ba7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocofe_baga_dinamic_cols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  K     NUMERIC := 0;
begin
  --Bogdan 09.09.2020
  delete FROM tmp_dinamic_cols;

  IF current_setting ('PKG_LIST_BASE_STOCOFE.vTipPret', true) ::numeric = 1 THEN
    FOR v_rec IN (SELECT CODCATPRET, DEN_CATPRET FROM ncatpret WHERE CODCATPRET &lt;&gt; 0 ORDER BY CODCATPRET) LOOP
      k := k + 1;
      INSERT INTO tmp_dinamic_cols (FieldName, Display, Cod, IndexLocal)
      VALUES ('P'|| coalesce ( (k) ::varchar,'') , v_rec.DEN_CATPRET, v_rec.CODCATPRET, k);

      IF PKG_LIST_BASE_STOCOFE_vAllAdaos() THEN
        k := k + 1;
        INSERT INTO tmp_dinamic_cols (FieldName, Display, Cod, IndexLocal)
        VALUES ('P'|| coalesce ( (k) ::varchar,'') , '%Adaos/'|| coalesce (v_rec.DEN_CATPRET,'') , v_rec.CODCATPRET, k);
      END IF;
    END LOOP;
  END IF;

  perform set_config ('PKG_LIST_BASE_STOCOFE.vNrCol',k::varchar,false);
end;
$function$
</obj_text>
</row>

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

  sInsert    varchar;
  sSelect1   varchar;
  sSelect2   varchar;
  sUpdate1   varchar := '';
  sUpdate2   varchar := '';
  sUpd1Col1  varchar := '';
  sUpd1Col2  varchar := '';
  sUpd2Col1  varchar := '';
  sCondStoc  varchar := '';
  sCondServ  varchar := '';
  sCondPM    varchar := '';
  vLeiVal    varchar := '';
  sTempPret  varchar := '';
  vCateGest  NUMERIC := 0;
  vCateLGest NUMERIC := 0;
  k          NUMERIC := 0;
begin
  --Adina 21.12.2020 tichet 41770 - lipsea elsif de la linia 81
  --Adina 18.12.2020 tichet 41649 - add  nir.codnir la linia 101 (order by ...) - ca sa ia ult.pret de achiz daca in aceeasi zi am mai multe nir-uri pt.acelasi produs
  --Bogdan 10.09.2020
  gSuplCols := 'nart a, nartobj o';

  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_STOCOFE.gSuplCols',gSuplCols,false);

  IF current_setting ('PKG_LIST_BASE_STOCOFE.vCodMoneda', true) ::numeric = 0 THEN
    vLeiVal := 'lei';
  ELSE
    vLeiVal := 'valuta';
  END IF;

  IF NOT pkg_list_base_stocofe_vallgest() 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 NOT pkg_list_base_stocofe_vallart() THEN
    sCondStoc := sCondStoc || '
      AND ns.codobiect in ( SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' ) ';
    sCondServ := sCondServ || '
      AND o.codobiect in ( SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' ) ';
  END IF;

  IF NOT pkg_list_base_stocofe_vallioart() THEN
    sCondStoc := sCondStoc || '
      AND ns.codioart IN ( SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' ) ';
  END IF;

  IF vCateGest &gt; 0 AND vCateLGest = 0 THEN
    sCondStoc := sCondStoc || '
      AND nir.gest IN ( SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
  ELSIF vCateGest    = 0 AND vCateLGest &gt; 0 THEN
    sCondStoc := sCondStoc || '
      AND EXISTS ( SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND VALOARE::numeric = ns.codlocatie) ';
  ELSIF vCateGest &gt; 0 AND vCateLGest &gt; 0 THEN
    sCondStoc := sCondStoc||'
      AND (NIR.GEST IN ( SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') OR NS.CODLOCATIE IN ( SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'')) ';
  END IF;

  IF vCateGest &gt; 0 THEN
    sCondServ := sCondServ || '
      AND a.gestimplicita IN ( SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' ) ';
  END IF;

  CASE current_setting ('PKG_LIST_BASE_STOCOFE.vTipCalcul', true) ::numeric
    WHEN 0 THEN
      sTempPret := 'sum(ns.rest) over (partition by ns.codobiect,  ng.codsubunit)  cantstoc,
                    max(ns.pret-ns.adaos) over (partition by ns.codobiect,  ng.codsubunit)';
    WHEN 1 THEN
      sTempPret := 'sum(ns.rest) over (partition by ns.codobiect,  ng.codsubunit) cantstoc,
                    LAST_VALUE(ns.pret-ns.adaos) over (partition by ns.codobiect,  ng.codsubunit order by nir.datanir, nir.codnir range between unbounded preceding and unbounded following) ';
    WHEN 2 THEN
      sTempPret := 'sum(ns.rest) over (partition by ns.codobiect,  ng.codsubunit) cantstoc,
                    max(ns.pret) over (partition by ns.codobiect,  ng.codsubunit)';
  END CASE;

  IF current_setting ('PKG_LIST_BASE_STOCOFE.vCodMoneda', true) ::numeric &lt;&gt; 0 THEN
    sCondPM := sCondPM || ' AND pm.moneda = ' || coalesce (current_setting ('PKG_LIST_BASE_STOCOFE.vCodMoneda', true) ::numeric::varchar ,'');
  END IF;

  sInsert := 'INSERT INTO ' || coalesce (tmpName,'') || '(Art, UM, CatPr, PrImplicit, PrInreg, Stoc, ValStoc, ValLivr, Subunit, CodObiect, CodSubunit' || coalesce (gUserFields ,'') || ')';

  sSelect1 := '
         WITH stoc as
          ( SELECT distinct ns.codobiect,
              ng.codsubunit, ' || coalesce (sTempPret,'') || ' temppret
            FROM nirstoc       ns
              inner join nir      on nir.codnir = ns.codnir
              inner join ngest ng on ng.codgest = nir.gest ' || coalesce ( (PKG_LIST_BASE_UTILS_COND_SUBUNIT ('ng', 'codsubunit',NULL,NULL)) ::varchar ,'') || '
            WHERE rest &lt;&gt; 0 ' || coalesce (sCondStoc,'') || '
          )
         SELECT o.denumire,
          u.den_um,
          cp.den_catpret,
          pm.' || coalesce (vLeiVal,'') || ',
          s.temppret,
          s.cantstoc,
          pm.' || coalesce (vLeiVal,'') || ' * s.cantstoc,
          s.temppret * s.cantstoc,
          sub.den_subunit,
          o.codobiect,
          sub.codsubunit ' || coalesce (gUserAlias ,'') || '
         FROM stoc            s
          INNER JOIN nartobj  o   on o.codobiect    = s.codobiect
          INNER JOIN nart     a   on a.codarticol   = o.codarticol
          INNER JOIN num      u   on u.codum        = a.um
          INNER JOIN pretm    pm  on pm.codobiect   = s.codobiect AND pm.subunitatea = s.codsubunit AND pm.implicit = 1 ' || coalesce (sCondPM,'') || '
          INNER JOIN ncatpret cp  on cp.codcatpret  = pm.codcatpret
          INNER JOIN nsubunit sub ON sub.codsubunit = s.codsubunit' || coalesce (gSuplJoins ,'');

  sSelect2 := '
         SELECT o.denumire,
          u.den_um,
          cp.den_catpret,
          pm.' || coalesce (vLeiVal,'') || ' ,
          0,
          0,
          0,
          0,
          sub.den_subunit,
          o.codobiect,
          sub.codsubunit ' || coalesce (gUserAlias ,'') || '
         FROM nart           a
          INNER JOIN nartobj o   on o.codarticol   = a.codarticol
          INNER JOIN num     u   on u.codum        = a.um
          LEFT JOIN ngest    ng  on ng.codgest     = a.gestimplicita
          LEFT JOIN pretm    pm  on pm.codobiect   = o.codobiect AND pm.subunitatea = ng.codsubunit AND pm.implicit = 1 ' || coalesce (sCondPM,'') || '
          LEFT JOIN ncatpret cp  on cp.codcatpret  = pm.codcatpret
          LEFT JOIN nsubunit sub ON sub.codsubunit = coalesce (ng.codsubunit,0) ' || coalesce (gSuplJoins ,'') || '
         WHERE a.tiparticol::numeric = 1 ' || coalesce (sCondServ,'');

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

  IF pkg_list_base_stocofe_vservicii() THEN
    PERFORM LIST_EXECUTE_IMMEDIATE (coalesce (sInsert,'') || coalesce (sSelect2,'') , aListID, aListVer);
  END IF;

  IF current_setting ('PKG_LIST_BASE_STOCOFE.vNrCol', true) ::numeric &gt; 0 THEN
    k := 0;
    WHILE k &lt; current_setting ('PKG_LIST_BASE_STOCOFE.vNrCol', true) ::numeric
    LOOP
      k := k + 1;
      sUpd1Col1 := coalesce (sUpd1Col1,'')|| ',P'|| coalesce (k::varchar,'');
      sUpd1Col2 := coalesce (sUpd1Col2,'')|| ',Max(case when x.indexlocal = '|| coalesce (k::varchar,'')|| ' then pm.'|| coalesce (vLeiVal,'')|| ' else 0 end) ';
      IF pkg_list_base_stocofe_valladaos() THEN
        k := k + 1;
        sUpd2Col1 := coalesce (sUpd2Col1,'')|| ',P'|| coalesce (k::varchar,'')|| ' = (P'|| coalesce ( (k - 1) ::varchar,'')|| ' / PrInreg -1) * 100';
      END IF;
    END LOOP;

    sUpd1Col1 := SUBSTR (sUpd1Col1, 2);
    sUpd1Col2 := SUBSTR (sUpd1Col2, 2);
    sUpd2Col1 := SUBSTR (sUpd2Col1, 2);
    sUpdate1  := 'UPDATE '|| coalesce (tmpName,'')|| ' t
                  SET ( '|| coalesce (sUpd1Col1,'')|| ' ) = ( SELECT '|| coalesce (sUpd1Col2,'')
                                                         || ' FROM pretm pm INNER JOIN tmp_dinamic_cols x ON x.Cod = pm.CodCatPret
                                                              WHERE pm.codobiect = t.codobiect AND pm.subunitatea = t.codsubunit '|| coalesce (sCondPM,'')|| ')';
    sUpdate2 := 'UPDATE '|| coalesce (tmpName,'')|| ' SET '|| coalesce (sUpd2Col1,'')|| ' WHERE coalesce(PrInreg,0) &lt;&gt; 0';

    PERFORM LIST_EXECUTE_IMMEDIATE (sUpdate1, aListID, aListVer);

    IF pkg_list_base_stocofe_valladaos() THEN
      PERFORM LIST_EXECUTE_IMMEDIATE (sUpdate2, aListID, aListVer);
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocofe_setjoinuri</obj_name>
  <obj_hashval>119c60c2b8fe1fa95e23f8b823ce40dd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocofe_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 09.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec (current_setting ('PKG_LIST_BASE_STOCOFE.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocofe_setparams</obj_name>
  <obj_hashval>dd84d3e72113335f8274c9887e42a2b9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocofe_setparams(pallart numeric DEFAULT 1, pservicii numeric DEFAULT 1, ptippret numeric DEFAULT NULL::numeric, ptipcalcul numeric DEFAULT NULL::numeric, pcodmoneda numeric DEFAULT NULL::numeric, pallgest numeric DEFAULT 1, pallioart numeric DEFAULT 1, palladaos numeric DEFAULT 0, pcodjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 09.09.2020
  perform set_config ('PKG_LIST_BASE_STOCOFE.vAllArt'   ,coalesce(pAllArt,1)::varchar  ,false);
  perform set_config ('PKG_LIST_BASE_STOCOFE.vServicii' ,coalesce(pServicii,1)::varchar,false);
  perform set_config ('PKG_LIST_BASE_STOCOFE.vTipPret'  ,pTipPret::varchar             ,false);
  perform set_config ('PKG_LIST_BASE_STOCOFE.vTipCalcul',pTipCalcul::varchar           ,false);
  perform set_config ('PKG_LIST_BASE_STOCOFE.vCodMoneda',pCodMoneda::varchar           ,false);
  perform set_config ('PKG_LIST_BASE_STOCOFE.vAllIoart' ,coalesce(pAllIoart,1)::varchar,false);
  perform set_config ('PKG_LIST_BASE_STOCOFE.vAllGest'  ,coalesce(pAllGest,1)::varchar ,false);
  perform set_config ('PKG_LIST_BASE_STOCOFE.vAllAdaos' ,coalesce(pAllAdaos,1)::varchar,false);
  PERFORM PKG_LIST_BASE_STOCOFE_BAGA_DINAMIC_COLS();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocofe_valladaos</obj_name>
  <obj_hashval>65107705d7f4061b5064bee2d6cff8e6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocofe_valladaos()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 09.09.2020
  return current_setting ('PKG_LIST_BASE_STOCOFE.vAllAdaos', true)::numeric = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocofe_vallart</obj_name>
  <obj_hashval>c557e235dadc774d8e64103aea1eff8e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocofe_vallart()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 09.09.2020
  return current_setting ('PKG_LIST_BASE_STOCOFE.vAllArt', true)::numeric = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocofe_vallgest</obj_name>
  <obj_hashval>96ab3b91b0f7fdd5abd441498815027e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocofe_vallgest()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 09.09.2020
  return current_setting ('PKG_LIST_BASE_STOCOFE.vAllGest', true)::numeric = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocofe_vallioart</obj_name>
  <obj_hashval>e9ad0cb2bc3322017bdbc7f8a53c5ddc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocofe_vallioart()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 09.09.2020
  return current_setting ('PKG_LIST_BASE_STOCOFE.vAllIoart', true)::numeric = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocofe_vservicii</obj_name>
  <obj_hashval>d18d3dd61a8d262b4bedf4374734ef71</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocofe_vservicii()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 09.09.2020
  return current_setting ('PKG_LIST_BASE_STOCOFE.vServicii', true)::numeric = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocprognoza_filtrugeststoc</obj_name>
  <obj_hashval>b826fe3b08d03bdd102cffe4913bfc74</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocprognoza_filtrugeststoc(col character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 04 septembrie 2020
  IF  NOT current_setting('PKG_LIST_BASE_STOCPROGNOZA.vToateGestStoc', true)::boolean THEN
    RETURN  '
        AND ' || coalesce(COL,'') || '::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' )';
  ELSE
    RETURN  NULL;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocprognoza_filtruobj</obj_name>
  <obj_hashval>ead130ba9e06acd0ceef30fb620ee9f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocprognoza_filtruobj(col character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 04 septembrie 2020
  IF  NOT current_setting('PKG_LIST_BASE_STOCPROGNOZA.vToateArt', true)::boolean THEN
    RETURN  '
        AND ' || coalesce(COL,'') || '::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' )';
  ELSE
    RETURN  NULL;
  END IF;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocprognoza_setparams</obj_name>
  <obj_hashval>fc253d872a160dd1910c9139227104ce</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocprognoza_setparams(ptoateart numeric DEFAULT 1, pcomsubunit numeric DEFAULT 1, pconsum numeric DEFAULT 1, ptoategeststoc numeric DEFAULT 1, pexclneconforme numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 17.08.2021 - sinc.Oracle din 17.08.2021
  --Adina 04 septembrie 2020
  perform set_config('PKG_LIST_BASE_STOCPROGNOZA.vToateArt',      ( trunc(COALESCE(pToateArt      ,1)) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_STOCPROGNOZA.vComSubunit',    ( trunc(COALESCE(pComSubunit    ,1)) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_STOCPROGNOZA.vConsum',        ( trunc(COALESCE(pConsum        ,1)) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_STOCPROGNOZA.vToateGestStoc' ,( trunc(COALESCE(pToateGestStoc ,1)) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_STOCPROGNOZA.vExclNeconforme',( trunc(COALESCE(pExclNeconforme,0)) = 1)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocprognoza_setparams_xx</obj_name>
  <obj_hashval>0557f785ad21e7f027ae6e6e3e8839fb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocprognoza_setparams_xx(ptoateart numeric DEFAULT 1, pcomsubunit numeric DEFAULT 1, pconsum numeric DEFAULT 1, ptoategeststoc numeric DEFAULT 1)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 04 septembrie 2020
  perform set_config('PKG_LIST_BASE_STOCPROGNOZA.vToateArt',     ( trunc(COALESCE(pToateArt     ,1)) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_STOCPROGNOZA.vComSubunit',   ( trunc(COALESCE(pComSubunit   ,1)) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_STOCPROGNOZA.vConsum',       ( trunc(COALESCE(pConsum       ,1)) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_STOCPROGNOZA.vToateGestStoc',( trunc(COALESCE(pToateGestStoc,1)) = 1)::varchar,false);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocrezerv_setparams</obj_name>
  <obj_hashval>105cabb6f301b25ef74e2ce7e1769ec0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocrezerv_setparams(ptoateart numeric DEFAULT 1)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 27 august 2020
  perform set_config('PKG_LIST_BASE_STOCREZERV.vToateArt',( pToateArt = 1)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocrotatie_setjoinuri</obj_name>
  <obj_hashval>fdba4e358eb8c28f58cc279ad8b281e1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocrotatie_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_STOCROTATIE.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocrotatie_setparams</obj_name>
  <obj_hashval>7a2a8a2ba86c296a45e8a8e724c84b55</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocrotatie_setparams(pdataini character varying, pdatafin character varying, ptoateart numeric DEFAULT 1, pcodjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnLunaIni numeric := 0;
  vAnLunaFin numeric := 0;
BEGIN
  --Adina 16.10.2020
  perform set_config('PKG_LIST_BASE_STOCROTATIE.vToateArt',(COALESCE(pToateArt,1) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_STOCROTATIE.vDataIni' ,pDataIni,false);
  perform set_config('PKG_LIST_BASE_STOCROTATIE.vDataFin' ,pDataFin,false);

  IF  COALESCE(pCodJob1,0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1, pDataIni, pDataFin, vAnLunaIni, vAnLunaFin);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocval_processlist</obj_name>
  <obj_hashval>b4256f781a1ca93ed6c23325eb4487c8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocval_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gSuplCols   VARCHAR := 'IOART IOA';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  sInsert     varchar := '';
  pAnPrec     numeric;
  pLunaPrec   numeric;
  pAnLucru    numeric;
  pLunaLucru  numeric;
BEGIN
  --Adina 08.04.2021 - alstart,alstop
  --Adina 06 august 2020
  pAnLucru   := getanlucru();
  plunaLucru := getlunalucru();
  SELECT  NEWAN, newLuna INTO pAnPrec, pLunaPrec from pkg_globals_Calculeaza_Luna_Precedenta(pAnLucru, pLunaLucru, pAnPrec, pLunaPrec);

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

  CALL PRC_AL_CHECK('ioart1',0);

  sInsert := 'INSERT INTO ' || coalesce(TMPNAME,'') || '(
    DEN_GEST,DEN_IOART,TVA,
    INIVAL, INITVA, INIADAOS, INIACHIZ,
    INTVAL, INTTVA, INTADAOS, INTACHIZ,
    IESVAL, IESTVA, IESADAOS, IESACHIZ,
    FINVAL, FINTVA, FINADAOS, FINACHIZ, FININTR, FINADINTR' || gUserFields || ')
   WITH
    v AS
    (
      SELECT
        GEST, CODIOART, TVA,
        SUM(INIVAL) INIVAL, SUM(INIVAL)/(1+TVA)*TVA INITVA, SUM(INIADAOS) INIADAOS,
        SUM(INTVAL) INTVAL, SUM(INTVAL)/(1+TVA)*TVA INTTVA, SUM(INTADAOS) INTADAOS,
        SUM(IESVAL) IESVAL, SUM(IESVAL)/(1+TVA)*TVA IESTVA, SUM(IESADAOS) IESADAOS,
        SUM(SOLDINTR) SOLDINTR, SUM(ADAOSINTR)  ADAOSINTR
      FROM (
            SELECT
                  SVL.GEST, SVL.CODIOART, Coalesce(SVL.TVA, 0) TVA,
                  SVL.SOLD INIVAL, (SVL.ADAOS - SVL.SOLD / (1+Coalesce(SVL.TVA, 0)) * Coalesce(SVL.TVA, 0) ) INIADAOS,
                  0 INTVAL, 0 INTADAOS,
                  0 IESVAL, 0 IESADAOS,
                  SVL.SOLDINTR, (SVL.ADAOSINTR - SVL.SOLDINTR / (1+Coalesce(SVL.TVA, 0)) ) ADAOSINTR
            FROM STOCVALLUNA SVL INNER JOIN NGEST NG ON NG.CODGEST = SVL.GEST
            WHERE AN = ' || coalesce(pAnPrec::varchar,'0') || ' AND LUNA = ' || coalesce(pLunaPrec::varchar,'0') || ' ' ||
                  coalesce((SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG', 'CODSUBUNIT',NULL,NULL))::varchar ,'') || '
            UNION ALL
            SELECT
                  N.GEST, NS.CODIOART, NS.TVA,
                  0 INIVAL, 0 INIADAOS,
                  NS.CANTNIR * NS.PRET INTVAL, NS.CANTNIR * (NS.ADAOS - NS.PRET * NS.TVA/(1 + NS.TVA)) INTADAOS,
                  0 IESVAL,0 IESADAOS,
                  NS.CANTNIR * NS.PRET SOLDINTR, NS.CANTNIR * (NS.ADAOS - NS.PRET * NS.TVA/(1 + NS.TVA)) ADAOSINTR
            FROM NIRSTOC NS
                 INNER JOIN IOART1 IOA1 ON IOA1.CODIOART = NS.CODIOART AND ' || coalesce(getanlunalucru()::varchar,'0') || ' BETWEEN IOA1.ALStart and IOA1.ALStop AND IOA1.MG = 5
                 INNER JOIN NIR    N    ON N.CODNIR      = NS.CODNIR
                 INNER JOIN TRANSF T    ON T.CODTRANSF   = N.CODTRANSF
            WHERE N.TIPNIR IN (12, 13) AND  N.ANULAT = 0 AND N.OPERAT = 1
                  AND T.AN = ' || coalesce(pAnLucru::varchar,'0') || ' AND T.LUNA = ' || coalesce(pLunaLucru::varchar,'0') || ' ' ||
                  coalesce((SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'T',NULL,NULL,NULL)),'') || '
            UNION ALL
            SELECT
                  N.GEST, NS.CODIOART, NS.TVA,
                  0 INIVAL, 0 INIADAOS,
                  NS.CANTNIR * NS.PRET INTVAL, NS.CANTNIR * (NS.ADAOS - NS.PRET * NS.TVA/(1 + NS.TVA)) INTADAOS,
                  0 IESVAL,0 IESADAOS,
                  NS.CANTNIR * NS.PRET SOLDINTR, NS.CANTNIR * (NS.ADAOS - NS.PRET * NS.TVA/(1 + NS.TVA)) ADAOSINTR
            FROM NIRSTOC NS
                 INNER JOIN IOART1 IOA1 ON IOA1.CODIOART = NS.CODIOART AND ' || coalesce(getanlunalucru()::varchar,'0') || ' BETWEEN IOA1.ALStart and IOA1.ALStop AND IOA1.MG = 5
                 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, 6) AND  N.ANULAT = 0 AND N.OPERAT = 1
                  AND I.AN = ' || coalesce(pAnLucru::varchar,'0') || ' AND I.LUNA =  ' || coalesce(pLunaLucru::varchar,'0') || ' ' ||
                  coalesce((SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL)),'') || '
            UNION ALL
            SELECT
                  LV.GEST, LV.CODIOART, Coalesce(LV.TVANEEX, 0) TVA,
                  0 INIVAL, 0 INIADAOS,
                  0 INTVAL, 0 INTADAOS,
                  LV.PRETINREG * L1.CANT IESVAL, (LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0)) - LV.PRETACHIZ) * L1.CANT IESADAOS,
                  0 AS SOLDINTR, 0 AS ADAOSINTR
            FROM LIVRVAL LV
                 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
            WHERE L.TIPLIVR IN (1, 2, 3, 4, 6) AND  L.OPERAT = 1 AND L.ANULAT = 0
                  AND I.AN = ' || coalesce(pAnLucru::varchar,'0') || ' AND I.LUNA = ' || coalesce(pLunaLucru::varchar,'0') || ' ' ||
                  coalesce((SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL)),'') || '
            UNION ALL
            SELECT
                  LV.GEST, LV.CODIOART, Coalesce(LV.TVANEEX, 0) TVA,
                  0 INIVAL, 0 INIADAOS,
                  (case when L.TIPLIVR=15 then LV.PRETINREG * L1.CANT                                               else 0 end) INTVAL,
                  (case when L.TIPLIVR=15 then (LV.PRETINREG /(1+Coalesce(LV.TVANEEX, 0)) - LV.PRETACHIZ) * L1.CANT else 0 end) INTADAOS,
                  (case when L.TIPLIVR=15 then 0 else LV.PRETINREG * L1.CANT end) IESVAL,
                  (case when L.TIPLIVR=15 then 0 else (LV.PRETINREG /(1+Coalesce(LV.TVANEEX, 0)) - LV.PRETACHIZ) * L1.CANT end) IESADAOS,
                  (case when L.TIPLIVR=15 then LV.PRETINREG * L1.CANT                                               else 0 end) SOLDINTR,
                  (case when L.TIPLIVR=15 then (LV.PRETINREG /(1+Coalesce(LV.TVANEEX, 0)) - LV.PRETACHIZ) * L1.CANT else 0 end) ADAOSINTR
            FROM LIVRVAL LV
                 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
            WHERE L.OPERAT = 1 AND L.ANULAT = 0
                  AND I.AN = ' || coalesce(pAnLucru::varchar,'0') || ' AND I.LUNA = ' || coalesce(pLunaLucru::varchar,'0') || ' ' ||
                  coalesce((SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL)),'') || '
            UNION ALL
            SELECT
                  LV.GEST, LV.CODIOART, Coalesce(LV.TVANEEX, 0) TVA, 0 INIVAL, 0 INIADAOS,
                  0 INTRLUNA, 0 ADINTRLUNA,
                  LV.PRETINREG * L1.CANT IESLUNA, (LV.PRETINREG /(1+Coalesce(LV.TVANEEX, 0)) - LV.PRETACHIZ) * L1.CANT ADIESLUNA,
                  0 SOLDINTR, 0 ADAOSINTR
            FROM LIVRVAL LV
                 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
            WHERE L.TIPLIVR IN (12, 13) AND L.OPERAT = 1 AND L.ANULAT = 0
                  AND T.AN = ' || coalesce(pAnLucru::varchar,'0') || ' AND T.LUNA = ' || coalesce(pLunaLucru::varchar,'0') || ' ' ||
                  coalesce((SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'T',NULL,NULL,NULL)),'') || '
           ) a_pg
      GROUP BY GEST, CODIOART, TVA
    )
    SELECT
          g.den_gest,ioa.den_ioart,v.TVA * 100,
          v.INIVAL, v.INITVA, v.INIADAOS, v.INIVAL - v.INITVA - v.INIADAOS,
          v.INTVAL, v.INTTVA, v.INTADAOS, v.INTVAL - v.INTTVA - v.INTADAOS,
          v.IESVAL, v.IESTVA, v.IESADAOS, v.IESVAL - v.IESTVA - v.IESADAOS,
          v.INIVAL + v.INTVAL - v.IESVAL, v.INITVA + v.INTTVA - v.IESTVA, v.INIADAOS + v.INTADAOS - v.IESADAOS,
          (v.INIVAL + v.INTVAL - v.IESVAL) - (v.INITVA + v.INTTVA - v.IESTVA) - (v.INIADAOS + v.INTADAOS - v.IESADAOS),
          v.SOLDINTR, v.ADAOSINTR' || gUserAlias || '
    FROM v
         INNER JOIN ngest  g   ON v.GEST      = g.codgest
         INNER JOIN IOART1 io  ON v.CODIOART  = io.codioart AND ' || coalesce(getanlunalucru()::varchar,'0') || ' BETWEEN IO.ALStart and IO.ALStop AND IO.MG = 5
         INNER JOIN IOART  IOA ON IO.CODIOART = IOA.CODIOART' || gSuplJoins;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocval_setjoinuri</obj_name>
  <obj_hashval>552492756d9f9629a0555f6c4e7276af</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocval_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 06 august 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_STOCVAL.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocvechime_processlist</obj_name>
  <obj_hashval>2aa62587ca6468b33c279818c4e35869</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocvechime_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSelect         varchar := '';
  aSubunitate     numeric;
  sFiltruInterne  varchar := '';
  AnPrec          numeric;
  LunaPrec        numeric;
  DataStoc        date    := to_date(current_setting('PKG_LIST_SELFISAMAG.p_dataStoc',true), 'dd.mm.yyyy');
  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';
  gUserFields     VARCHAR := '';
  gUserAlias      VARCHAR := '';
  gNullAlias      VARCHAR := '';
  gSuplJoins      VARCHAR := '';
  v_RezUM1        boolean := current_setting('PKG_LIST_SELFISAMAG.p_RezUM1'    ,true)::boolean;
  v_StocLaZi      boolean := current_setting('PKG_LIST_SELFISAMAG.p_StoclaZi'  ,true)::boolean;
  v_flgTipCont    boolean := current_setting('PKG_LIST_SELFISAMAG.p_flgTipCont',true)::boolean;
  v_flgGest       boolean := current_setting('PKG_LIST_SELFISAMAG.p_flgGest'   ,true)::boolean;
  v_flgArt        boolean := current_setting('PKG_LIST_SELFISAMAG.p_flgArt'    ,true)::boolean;
  v_DataRef       varchar := 'to_date('''||current_setting('PKG_LIST_SELFISAMAG.p_DataRef',true)||''', ''dd.mm.yyyy'')';
BEGIN
  --Adina 09.04.2021 - alstart, alstop
  --Stef  09.11.2020 - Ticket 40773
  --Adina 04 septembrie 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NOBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = NOBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, '', '', '',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_STOCVECHIME.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  CALL PRC_AL_CHECK('ioart1',0);

  aSubunitate     := getSUBUNITATE();
  --dataStoc        := to_date(current_setting('PKG_LIST_SELFISAMAG.p_dataStoc',true), 'dd.mm.yyyy');
  LunaLista       := EXTRACT( MONTH FROM DataStoc);
  AnLista         := EXTRACT( YEAR FROM DataStoc);
  sFiltruInterne  := '';

  IF v_RezUM1 THEN
    sFiltruInterne := ' and ies.tipdoc not in (14,15)';
  END IF;

  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, CodObiect,
      DEN_GEST, DEN_LGEST, DEN_IOART, DEN_ART, DEN_UM,
      PRETACH, CODINTERN, CODEXTERN,VEKIMEMEDIE,PRODUCATOR,DATAACHIZ, DATAREF, STOC, VAL,
      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_360, VAL_180_360, STOC_360_PLUS, VAL_360_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' || gUserFields || ')';

  IF v_StocLaZi 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 WHERE coalesce(intr.anulat,0) = 0 AND intr.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 WHERE ies.anulat = 0 AND ies.operat = 1' || sFiltruInterne;

    IF NOT v_RezUM1 THEN
      sSelect := sSelect || '
        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  WHERE tr.anulat = 0 AND tr.operat = 1';
    END IF;

    sSelect := coalesce(sSelect,'') || ')
    SELECT
      DOC.NAV_CODDOC, DOC.nav_tipdoc, NS.CODNIRSTOC, NOBJ.CODOBIECT,
      NG.DEN_GEST,NLOC.DENUMIRE LOCATIE,IO.DEN_IOART TIPCONTABIL,NOBJ.DENUMIRE,NUM1.DEN_UM1,
      NS.PRET - NS.ADAOS PRETACHIZ, NOBJ.CODINTERN, NOBJ.CODEXTERN, '||v_DataRef||' - coalesce(NS.DATAACHIZ,nir.datanir) VEKIMEMED,
      PROD.DEN_PART PRODUCATOR,coalesce(NS.DATAACHIZ,nir.datanir), '||v_DataRef||', NS.REST, NS.REST * NS.PRET,
      CASE WHEN '||v_DataRef||' - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN   0 AND  30 THEN NS.REST           ELSE 0 END STOC_0_30,
      CASE WHEN '||v_DataRef||' - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN   0 AND  30 THEN NS.REST * NS.PRET ELSE 0 END VAL_0_30,
      CASE WHEN '||v_DataRef||' - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN  31 AND  60 THEN NS.REST           ELSE 0 END STOC_31_60,
      CASE WHEN '||v_DataRef||' - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN  31 AND  60 THEN NS.REST * NS.PRET ELSE 0 END VAL_31_60,
      CASE WHEN '||v_DataRef||' - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN  61 AND  90 THEN NS.REST           ELSE 0 END STOC_61_90,
      CASE WHEN '||v_DataRef||' - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN  61 AND  90 THEN NS.REST * NS.PRET ELSE 0 END VAL_61_90,
      CASE WHEN '||v_DataRef||' - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN  91 AND 180 THEN NS.REST           ELSE 0 END STOC_91_180,
      CASE WHEN '||v_DataRef||' - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN  91 AND 180 THEN NS.REST * NS.PRET ELSE 0 END VAL_91_180,
      CASE WHEN '||v_DataRef||' - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN 181 AND 360 THEN NS.REST           ELSE 0 END STOC_180_360,
      CASE WHEN '||v_DataRef||' - coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN 181 AND 360 THEN NS.REST * NS.PRET ELSE 0 END VAL_180_360,
      CASE WHEN '||v_DataRef||' - coalesce(NS.DATAACHIZ,nir.datanir) &gt; 360 THEN NS.REST ELSE 0 END STOC_360_PLUS,
      CASE WHEN '||v_DataRef||' - coalesce(NS.DATAACHIZ,nir.datanir) &gt; 360 THEN NS.REST * NS.PRET ELSE 0 END VAL_360_PLUS,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS('||v_DataRef||', -3)+1 AND '||v_DataRef||' THEN NS.REST ELSE 0 END STOC_0_3_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS('||v_DataRef||', -3)+1 AND '||v_DataRef||' THEN NS.REST * NS.PRET ELSE 0 END VAL_0_3_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS('||v_DataRef||', -6)+1 AND ADD_MONTHS('||v_DataRef||', -3) THEN NS.REST ELSE 0 END STOC_3_6_LUN,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS('||v_DataRef||', -6)+1 AND ADD_MONTHS('||v_DataRef||', -3) THEN NS.REST * NS.PRET ELSE 0 END VAL_3_6_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS('||v_DataRef||', -9)+1 AND ADD_MONTHS('||v_DataRef||', -6) THEN NS.REST ELSE 0 END STOC_6_9_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS('||v_DataRef||', -9)+1 AND ADD_MONTHS('||v_DataRef||', -6) THEN NS.REST * NS.PRET ELSE 0 END VAL_6_9_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS('||v_DataRef||',-12)+1 AND ADD_MONTHS('||v_DataRef||', -9) THEN NS.REST ELSE 0 END STOC_9_12_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS('||v_DataRef||',-12)+1 AND ADD_MONTHS('||v_DataRef||', -9) THEN NS.REST * NS.PRET ELSE 0 END VAL_9_12_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS('||v_DataRef||',-12)+1 AND ADD_MONTHS('||v_DataRef||', -6) THEN NS.REST ELSE 0 END STOC_6_12_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS('||v_DataRef||',-12)+1 AND ADD_MONTHS('||v_DataRef||', -6) THEN NS.REST * NS.PRET ELSE 0 END VAL_6_12_LUNI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS('||v_DataRef||',-24)+1 AND ADD_MONTHS('||v_DataRef||',-12) THEN NS.REST ELSE 0 END STOC_1_2_ANI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) BETWEEN ADD_MONTHS('||v_DataRef||',-24)+1 AND ADD_MONTHS('||v_DataRef||',-12) THEN NS.REST * NS.PRET ELSE 0 END VAL_1_2_ANI,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) &lt;= ADD_MONTHS('||v_DataRef||',-24) THEN NS.REST ELSE 0 END STOC_2_ANI_PLUS,
      CASE WHEN coalesce(NS.DATAACHIZ,nir.datanir) &lt;= ADD_MONTHS('||v_DataRef||',-24) THEN NS.REST * NS.PRET ELSE 0 END VAL_2_ANI_PLUS ' || 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 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';
  ELSE
    sSelect := '
    SELECT
      COALESCE(VLS.CODTRANSF,VLS.CODIES,VLS.CODINTR), VLS.TIPNIR, VLS.CODNIRSTOC, NOBJ.CODOBIECT,
      NG.DEN_GEST,VLS.LOCATIE,IO.DEN_IOART TIPCONTABIL,NOBJ.DENUMIRE,NUM1.DEN_UM1,
      VLS.PRETACHIZ,NOBJ.CODINTERN, NOBJ.CODEXTERN,'||v_DataRef||' - NS.DATAACHIZ VEKIMEMED,
      PROD.DEN_PART PRODUCATOR,INTRATLA, '||v_DataRef||', VLS.REST, VLS.REST * VLS.PRET,
      CASE WHEN '||v_DataRef||' - VLS.INTRATLA BETWEEN   0 AND  30 THEN VLS.REST            ELSE 0 END STOC_0_30,
      CASE WHEN '||v_DataRef||' - VLS.INTRATLA BETWEEN   0 AND  30 THEN VLS.REST * VLS.PRET ELSE 0 END VAL_0_30,
      CASE WHEN '||v_DataRef||' - VLS.INTRATLA BETWEEN  31 AND  60 THEN VLS.REST            ELSE 0 END STOC_31_60,
      CASE WHEN '||v_DataRef||' - VLS.INTRATLA BETWEEN  31 AND  60 THEN VLS.REST * VLS.PRET ELSE 0 END VAL_31_60,
      CASE WHEN '||v_DataRef||' - VLS.INTRATLA BETWEEN  61 AND  90 THEN VLS.REST            ELSE 0 END STOC_61_90,
      CASE WHEN '||v_DataRef||' - VLS.INTRATLA BETWEEN  61 AND  90 THEN VLS.REST * VLS.PRET ELSE 0 END VAL_61_90,
      CASE WHEN '||v_DataRef||' - VLS.INTRATLA BETWEEN  91 AND 180 THEN VLS.REST            ELSE 0 END STOC_91_180,
      CASE WHEN '||v_DataRef||' - VLS.INTRATLA BETWEEN  91 AND 180 THEN VLS.REST * VLS.PRET ELSE 0 END VAL_91_180,
      CASE WHEN '||v_DataRef||' - VLS.INTRATLA BETWEEN 181 AND 360 THEN VLS.REST            ELSE 0 END STOC_180_360,
      CASE WHEN '||v_DataRef||' - VLS.INTRATLA BETWEEN 181 AND 360 THEN VLS.REST * VLS.PRET ELSE 0 END VAL_180_360,
      CASE WHEN '||v_DataRef||' - VLS.INTRATLA &gt; 360 THEN VLS.REST ELSE 0 END STOC_360_PLUS,
      CASE WHEN '||v_DataRef||' - VLS.INTRATLA &gt; 360 THEN VLS.REST * VLS.PRET ELSE 0 END VAL_360_PLUS,
      CASE WHEN VLS.INTRATLA BETWEEN ADD_MONTHS('||v_DataRef||', -3)+1 AND '||v_DataRef||' THEN VLS.REST ELSE 0 END STOC_0_3_LUNI,
      CASE WHEN VLS.INTRATLA BETWEEN ADD_MONTHS('||v_DataRef||', -3)+1 AND '||v_DataRef||' THEN VLS.REST * VLS.PRET                 ELSE 0 END VAL_0_3_LUNI,
      CASE WHEN VLS.INTRATLA BETWEEN ADD_MONTHS('||v_DataRef||', -6)+1 AND ADD_MONTHS('||v_DataRef||', -3) THEN VLS.REST            ELSE 0 END STOC_3_6_LUN,
      CASE WHEN VLS.INTRATLA BETWEEN ADD_MONTHS('||v_DataRef||', -6)+1 AND ADD_MONTHS('||v_DataRef||', -3) THEN VLS.REST * VLS.PRET ELSE 0 END VAL_3_6_LUNI,
      CASE WHEN VLS.INTRATLA BETWEEN ADD_MONTHS('||v_DataRef||', -9)+1 AND ADD_MONTHS('||v_DataRef||', -6) THEN VLS.REST            ELSE 0 END STOC_6_9_LUNI,
      CASE WHEN VLS.INTRATLA BETWEEN ADD_MONTHS('||v_DataRef||', -9)+1 AND ADD_MONTHS('||v_DataRef||', -6) THEN VLS.REST * VLS.PRET ELSE 0 END VAL_6_9_LUNI,
      CASE WHEN VLS.INTRATLA BETWEEN ADD_MONTHS('||v_DataRef||',-12)+1 AND ADD_MONTHS('||v_DataRef||', -9) THEN VLS.REST            ELSE 0 END STOC_9_12_LUNI,
      CASE WHEN VLS.INTRATLA BETWEEN ADD_MONTHS('||v_DataRef||',-12)+1 AND ADD_MONTHS('||v_DataRef||', -9) THEN VLS.REST * VLS.PRET ELSE 0 END VAL_9_12_LUNI,
      CASE WHEN VLS.INTRATLA BETWEEN ADD_MONTHS('||v_DataRef||',-12)+1 AND ADD_MONTHS('||v_DataRef||', -6) THEN VLS.REST            ELSE 0 END STOC_6_12_LUNI,
      CASE WHEN VLS.INTRATLA BETWEEN ADD_MONTHS('||v_DataRef||',-12)+1 AND ADD_MONTHS('||v_DataRef||', -6) THEN VLS.REST * VLS.PRET ELSE 0 END VAL_6_12_LUNI,
      CASE WHEN VLS.INTRATLA BETWEEN ADD_MONTHS('||v_DataRef||',-24)+1 AND ADD_MONTHS('||v_DataRef||',-12) THEN VLS.REST            ELSE 0 END STOC_1_2_ANI,
      CASE WHEN VLS.INTRATLA BETWEEN ADD_MONTHS('||v_DataRef||',-24)+1 AND ADD_MONTHS('||v_DataRef||',-12) THEN VLS.REST * VLS.PRET ELSE 0 END VAL_1_2_ANI,
      CASE WHEN VLS.INTRATLA &lt;= ADD_MONTHS('||v_DataRef||',-24) THEN VLS.REST            ELSE 0 END STOC_2_ANI_PLUS,
      CASE WHEN VLS.INTRATLA &lt;= ADD_MONTHS('||v_DataRef||',-24) THEN VLS.REST * VLS.PRET ELSE 0 END VAL_2_ANI_PLUS ' || 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 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 NGEST    NG   ON NG.CODGEST      = VLS.GEST
      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';

    IF v_RezUM1 THEN
      sSelect := coalesce(sSelect,'') || '
      AND VLS.TIPNIR NOT IN (12,13,14,15)';
    END IF;
  END IF;

  IF NOT v_flgTipCont THEN    --= FALSE
    sSelect := coalesce(sSelect,'') || '
      AND NS.CODIOART::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
  END IF;

  IF NOT v_flgGest THEN    --= FALSE
    sSelect := coalesce(sSelect,'') || '
      AND NIR.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
  END IF;

  IF NOT v_flgArt THEN    --= 0
    sSelect := coalesce(sSelect,'') || '
      AND NS.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'') ';
  END IF;

  IF  aSubunitate &gt; 1 THEN
    sSelect := sSelect || '
      AND NG.CODSUBUNIT = ' || aSubunitate;
  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_stocvechime_setjoinuri</obj_name>
  <obj_hashval>a9fc979f04434415f6384c47f7a8f4dd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocvechime_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 04 septembrie 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_STOCVECHIME.gSuplCols', true));
  PERFORM Pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocvitrot_setparams</obj_name>
  <obj_hashval>acf5c86e2a6f7a38f9cb8eac15e8f824</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocvitrot_setparams(pdataini character varying, pdatafin character varying, panual numeric DEFAULT 1, pavizesub numeric DEFAULT 1, ptransfval numeric DEFAULT 1, piesconsum numeric DEFAULT 1, ptoateart numeric DEFAULT 1, ptoategest numeric DEFAULT 1, ptoateioart numeric DEFAULT 1, pcentr numeric DEFAULT 1, v_codjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
BEGIN
  --Adina 04 septembrie 2020
  perform set_config('PKG_LIST_BASE_STOCVITROT.vDataIni',pDataIni,false);
  perform set_config('PKG_LIST_BASE_STOCVITROT.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_STOCVITROT.vDataIni', true), current_setting('PKG_LIST_BASE_STOCVITROT.vDataFin', true), xLunaAnIni, xLunaAnFin);
  END IF;

  perform set_config('PKG_LIST_BASE_STOCVITROT.vData1',to_char(DATE_TRUNC('month',to_date(current_setting('PKG_LIST_BASE_STOCVITROT.vDataIni', true),'dd.mm.yyyy')),'dd.mm.yyyy'),false);
  perform set_config('PKG_LIST_BASE_STOCVITROT.vAnual',     ( trunc(COALESCE(pAnual,1))      = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_STOCVITROT.vAvizeSub',  ( trunc(COALESCE(pAvizeSub,1))   = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_STOCVITROT.vTransfVal', ( trunc(COALESCE(pTransfVal,1))  = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_STOCVITROT.vIesConsum', ( trunc(COALESCE(pIesConsum,1))  = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_STOCVITROT.vToateArt',  ( trunc(COALESCE(pToateArt,1))   = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_STOCVITROT.vToateGest', ( trunc(COALESCE(pToategest,1))  = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_STOCVITROT.vToateIOArt',( trunc(COALESCE(pToateIOArt,1)) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_STOCVITROT.vCentr',     ( trunc(COALESCE(pCentr,1))      = 1)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_syncpretretail_processlist</obj_name>
  <obj_hashval>a5a2c32c805d075cf082d2b353066039</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_syncpretretail_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert        varchar;
  sSelect        varchar;
  sWhere         varchar;
  gSuplCols      varchar := 'syncpretretail spr, nartobj nao, nart na';
  gUserFields    VARCHAR := '';
  gUserAlias     VARCHAR := '';
  gNullAlias     VARCHAR := '';
  gSuplJoins     VARCHAR := '';
  vCodCatPretStr VARCHAR := '';
  vCodCatPret    NUMERIC(20);
begin
  --Bogdan 12.05.2022 54059 : PG - Lista Situatie sincronizare preturi retail - coloane suplimentare
  --Bogdan 28.04.2022 54059 : PG - Lista Situatie sincronizare preturi retail - eroare
  --Florin 08.04.2021 - fixat 46895
  --Adina 09.03.2021 - PRC_AL_CHECK
  --Florin 06.08.2020
  --Adina 27.11.2020 tichet 41319
  vCodCatPretStr := CURRENT_SETTING('PKG_LIST_BASE_SYNCPRETRETAIL.vCodCatPret', TRUE);
  vCodCatPret := case when coalesce(vCodCatPretStr,'') = '' then 0 else vCodCatPretStr::numeric end;
  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_SYNCPRETRETAIL.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||'(
    Art, CodIntern, CodExtern, PretVechi, PretNou '||COALESCE(gUserFields, '')||')';

  sSelect := '
  SELECT
    nao.denumire, nao.codintern, nao.codextern, spr.pretvechi, spr.pretnou '||COALESCE(gUserAlias, '')||'
  FROM syncpretretail spr
    INNER JOIN tmp_manevra m   ON m.codunic     = spr.idpreluare
    LEFT  JOIN nartobj     nao ON nao.codobiect = spr.codobiect
    LEFT  JOIN nart        na  ON na.codarticol = nao.codarticol '||
    gSuplJoins;

  sWhere := '
    WHERE spr.CODCATPRET = '||COALESCE(vCodCatPret::varchar, '');

  IF vCodCatPret = 0 THEN
    sWhere := '';
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_syncpretretail_setparams</obj_name>
  <obj_hashval>84366cae888c4c9d50a971c3148d0fb1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_syncpretretail_setparams(pcodcatpret numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 54059 - PG - Lista Situatie sincronizare preturi retail - eroare
  --Florin 18.04.2022
  PERFORM set_config('PKG_LIST_BASE_SYNCPRETRETAIL.vCodCatPret', Coalesce(pCodCatPret, 0)::varchar, FALSE);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_taskuri_setparams</obj_name>
  <obj_hashval>0f8a8ec6b93be8847b3ba36a49d8451e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_taskuri_setparams(includsterse numeric DEFAULT 0, areinterval numeric DEFAULT 0, dataini character varying DEFAULT ''::character varying, datafin character varying DEFAULT ''::character varying, includlog numeric DEFAULT 0, v_codjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
BEGIN
  --Adina 11 septembrie 2020
  perform set_config('PKG_LIST_BASE_TASKURI.g_dataIni',(DataIni)::varchar,false);
  perform set_config('PKG_LIST_BASE_TASKURI.g_dataFin',(datafin)::varchar,false);

  IF  COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, current_setting('PKG_LIST_BASE_TASKURI.g_dataIni', true), current_setting('PKG_LIST_BASE_TASKURI.g_dataFin', true), xLunaAnIni, xLunaAnFin);
  END IF;

  perform set_config('PKG_LIST_BASE_TASKURI.g_includSterse',( trunc(COALESCE(includSterse,0)) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_TASKURI.g_areInterval' ,( trunc(COALESCE(areInterval ,0)) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_TASKURI.g_includLog'   ,( trunc(COALESCE(includLog   ,0)) = 1)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_tehprod_bagamateriale</obj_name>
  <obj_hashval>02637dc498d7d25f09570d713fddd24b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_tehprod_bagamateriale(aobservatii character varying, acodobiect numeric, acant numeric, acodprodcomp numeric, anivel numeric, acodmoneda numeric, acodoriginal numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_TMP RECORD;
begin
  --Bogdan 14.09.2020
  FOR v_tmp IN (SELECT mat.codobiect,
                       mat.tip,
                       CASE WHEN COALESCE (mat.tip, 3) &lt;= 2 THEN COALESCE (pc.codprodcomp, 0) ELSE 0 END CODPRODCOMP,
                       aCant / CASE WHEN COALESCE (prod.cant, 0) = 0 THEN 1 ELSE prod.cant END * mat.cant CANT,
                       CASE WHEN aObservatii &lt;&gt; ' ' THEN coalesce (aObservatii,'')|| '.'|| coalesce (LPAD ( (IndexLocal) ::varchar, 2, '0') ,'')
                            ELSE LPAD ( (IndexLocal) ::varchar, 2, '0')
                       END OBSERVATII,
                       mat.codmat
                FROM prodmat          mat
                  INNER JOIN prodcomp prod ON prod.codprodcomp = mat.codprodcomp
                  LEFT JOIN prodcomp  pc   ON pc.codobiect     = mat.codobiect and pc.implicit = 1
                WHERE mat.codprodcomp = aCodProdComp
                ORDER BY mat.indexlocal
               )
  LOOP
    INSERT INTO tmp_prodcomp (CodProdcomp,
        Codobiect,
        Cant,
        Observatii,
        CodProiect,
        NrCmd,
        CodMoneda,
        ImplicitOld)
      VALUES (v_tmp.codprodcomp,
        v_tmp.CodObiect,
        v_tmp.Cant,
        v_tmp.Observatii,
        v_tmp.codmat,
        aNivel + 1,
        aCodMoneda,
        aCodOriginal);

    IF v_tmp.CodProdComp &gt; 0 THEN
      PERFORM PKG_LIST_BASE_TEHPROD_BagaMateriale (v_tmp.Observatii, v_tmp.CodObiect, v_tmp.Cant, v_tmp.CodProdComp, aNivel + 1, aCodMoneda, aCodOriginal);
    END IF;
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_tehprod_make_mat1</obj_name>
  <obj_hashval>1db8c0c4a5aaa491e57a9789e2d447ad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_tehprod_make_mat1(acodprodcomp numeric, acodsemif numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_mat record;
  v_sem record;
  acount NUMERIC(10);
BEGIN
  --Florin 01.03.2023 - sinc. Oracle (28.02.2023)
  for v_mat in (select mat.codobiect
                from prodmat mat
                where mat.codprodcomp = acodsemif
               ) loop
    select count(*) into acount
    from prodcomp
    where codobiect = v_mat.codobiect and implicit = 1
          and coalesce(inactiv,0) = 0;
    if acount = 0 then
--      merge into manevra_prodcomp_clona m
--      using (select acodprodcomp codprodcomp, v_mat.codobiect codobiect from dual) n
--      on (m.codprodcomp = n.codprodcomp and m.codobiect = n.codobiect)
--      when not matched then insert (codprodcomp,codobiect) values (n.codprodcomp, n.codobiect);
    else
      for v_sem in (select codprodcomp
                    from prodcomp
                    where codobiect = v_mat.codobiect and implicit = 1
                          and coalesce(inactiv,0) = 0
                   ) loop
        PERFORM pkg_list_base_tehprod_make_mat1(acodprodcomp, v_sem.codprodcomp);
      end loop;
    end if;
  end loop;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_teme_processlist</obj_name>
  <obj_hashval>89444de67950cc12dc6fd65fafdce93a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_teme_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  gSuplCols   varchar := 'NPERS FORMATOR, CURSURI C';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --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_TEME.gSuplCols', gSuplCols, FALSE);

  sInsert := 'INSERT INTO ' || tmpName ||
    '(Den_tema, Ore, Pret, Formator ' || gUserFields || ')
    SELECT t.den_tema, t.ore, t.pret, formator.nume||'' ''||formator.prenume ' || gUserAlias || '
    FROM teme t
      LEFT JOIN npers    formator ON formator.codpers = t.codformator
      LEFT JOIN cursuri1 c1       ON c1.codtema       = t.codtema
      LEFT JOIN cursuri  c        ON c.codcurs        = c1.codcurs' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_teme_setjoinuri</obj_name>
  <obj_hashval>7cd8a91865a5793ddc5e9048f8c35b84</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_teme_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 15.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_TEME.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_termedcli_setjoinuri</obj_name>
  <obj_hashval>44fc432ce7ef7f346c528389dda07533</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_termedcli_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 19.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_TERMEDCLI.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_termedfurn_setjoinuri</obj_name>
  <obj_hashval>db482f88298a9c06333453077ba9efc5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_termedfurn_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 19.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_TERMEDFURN.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topart_setparams</obj_name>
  <obj_hashval>9ff97d24b9b8345fcc2145861f052f5f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topart_setparams(pdataini character varying, pdatafin character varying, ppefurn numeric, psorttype numeric, pdoctype numeric, v_codjob1 numeric, pcodatribut numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
  sDataS     varchar := pDataIni;
  sDataF     varchar := pDataFin;
BEGIN
  --Florin 01.09.2020
  IF COALESCE(v_CodJob1, 0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, sDataS, sDataF, xLunaAnIni, xLunaAnFin);
  END IF;
  PERFORM set_config('PKG_LIST_BASE_TOPART.vdataIni'   , sDataS, FALSE);
  PERFORM set_config('PKG_LIST_BASE_TOPART.vdataFin'   , sDataF, FALSE);
  PERFORM set_config('PKG_LIST_BASE_TOPART.vPeFurn'    , (COALESCE(ppefurn, 0) = 1)::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_TOPART.vSortType'  , pSortType  ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_TOPART.vDocType'   , pDocType   ::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_TOPART.vCodAtribut', pCodAtribut::varchar, FALSE);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topcliani_setjoinuri</obj_name>
  <obj_hashval>484f29e332ddf1cd5715b74bd65cc995</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topcliani_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Florin 12.02.2021
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_TOPCLIENTI.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topcliani_setparams</obj_name>
  <obj_hashval>84fd8f1112381169d19409038df3f7de</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topcliani_setparams(plunastart numeric DEFAULT 1, plunafin numeric DEFAULT 12, ptotipart boolean DEFAULT true, v_codjob1 numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni INTEGER;
  xLunaAnFin INTEGER;
  sDataS     varchar := '01.01.2018';
  sDataF     varchar := '12.12.2018';
  dDataIni   date;
  dDataFin   date;
  pToti      NUMERIC = 0;
BEGIN
  --Florin 16.12.2022 - sinc. Oracle
  --Bogdan 02.09.2020
  --Florin 07.04.2021 - fixat 46801
  dDataIni := To_Date( sDataS, 'dd.mm.yyyy');
  dDataFin := To_Date( sDataF, 'dd.mm.yyyy');

  IF  COALESCE(v_CodJob1, 0) &gt; 0 THEN
    select PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.adataini , PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.adatafin,
           PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.alunaanini, PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.alunaanfin
    from PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(v_CodJob1, dDataIni, dDataFin, xLunaAnIni, xLunaAnFin)
    into dDataIni, dDataFin, xLunaAnIni, xLunaAnFin;
  END IF;

  sDataS := To_Char( dDataIni, 'dd.mm.yyyy');
  sDataF := To_Char( dDataFin, 'dd.mm.yyyy');
  perform set_config('PKG_LIST_BASE_TOPCLIANI.vLunaStart', pLunaStart::varchar, false);
  perform set_config('PKG_LIST_BASE_TOPCLIANI.vLunaFin'  , plunafin::varchar, false);
  perform set_config('PKG_LIST_BASE_TOPCLIANI.vTotiPart', ptotipart::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topcliani_totipart</obj_name>
  <obj_hashval>51fbaea034c5ac9000ae38d64b69877c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topcliani_totipart()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
declare
BEGIN
  --Florin 13.01.2023 - fixat 56794
  --Bogdan 02.09.2020
  return  current_setting('PKG_LIST_BASE_TOPCLIANI.vTotiPart', true);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topclienti_setparams</obj_name>
  <obj_hashval>7c93d364dd28be0021d4d756afc78716</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topclienti_setparams(pdataini character varying, pdatafin character varying, pallioart numeric, pallcls numeric, pavize numeric, paducust numeric, paduemul numeric, pcodjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
declare
  vDataINI    varchar(10);
  vDataFIN    varchar(10);
  xLunaAnIni  NUMERIC;
  xLunaAnFin  NUMERIC;
  dDataIni    date;
  dDataFin    date;
begin
  --Bogdan 01.09.2020
  dDataIni := To_Date( pDataINI, 'dd.mm.yyyy');
  dDataFin := To_Date( pDataFIN, 'dd.mm.yyyy');
  IF  pCodJob1 &gt; 0  THEN
    select PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.adataini  , PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.adatafin,
           PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.alunaanini, PKG_ORA_LISTS_SET_INTERVAL_DINAMIC.alunaanfin
    from PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1, dDataIni, dDataFin, xLunaAnIni, xLunaAnFin)
    into dDataIni, dDataFin, xLunaAnIni, xLunaAnFin;
  END IF;
  vDataINI := To_Char( dDataIni, 'dd.mm.yyyy');
  vDataFIN := To_Char( dDataFin, 'dd.mm.yyyy');

  perform set_config('PKG_LIST_BASE_TOPCLIENTI.vDataIni',vDataINI,false);
  perform set_config('PKG_LIST_BASE_TOPCLIENTI.vDataFin',vDataFIN,false);

  perform set_config('PKG_LIST_BASE_TOPCLIENTI.vAvize'  ,Coalesce(pAvize,   1)::varchar,false);
  perform set_config('PKG_LIST_BASE_TOPCLIENTI.vAllIOA' ,Coalesce(pAllIOArt,1)::varchar,false);
  perform set_config('PKG_LIST_BASE_TOPCLIENTI.vAllCls' ,Coalesce(pAllCls,  1)::varchar,false);
  perform set_config('PKG_LIST_BASE_TOPCLIENTI.vAduCust',Coalesce(pAduCust, 0)::varchar,false);
  perform set_config('PKG_LIST_BASE_TOPCLIENTI.vAduEmul',Coalesce(pAduEmul, 0)::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topclientiold_conditieincludere</obj_name>
  <obj_hashval>4987780110a7903e352e4746bacb0851</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topclientiold_conditieincludere(acodies1 numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount  numeric;
BEGIN
  --Adina 19.10.2020
  IF current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vAllIOArt',true)::boolean and current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vAllCls',true)::boolean
  THEN RETURN 1;
  ELSE
    SELECT count(*) INTO aCount
    FROM livr1 l1
         INNER JOIN iesiri1 i1 on i1.codies1    = l1.codies1
         LEFT  JOIN livrval lv on lv.codlivr1   = l1.codlivr1
         LEFT  JOIN nirstoc ns on l1.codnirstoc = ns.codnirstoc
    WHERE l1.codies1 = aCodIes1 and pkg_list_base_TOPCLIENTIOLD_ConditieIncludereIOArt(coalesce(ns.codioart, lv.codioart)) &gt; 0
                                and pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0;
    RETURN aCount;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topclientiold_conditieincluderee</obj_name>
  <obj_hashval>bbf1f89695d8a653468cbb9cdc814872</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topclientiold_conditieincluderee(acodemulare1 numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount  numeric;
BEGIN
  --Adina 19.10.2020
  IF current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vAllIOArt',true)::boolean and current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vAllCls',true)::boolean
  THEN RETURN 1;
  ELSE
    SELECT count(*) INTO aCount
    FROM emulare1
    WHERE codemulare1 = aCodEmulare1 AND pkg_list_base_topclientiold_ConditieIncludereIOArt(codioart) &gt; 0
                                     AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, CODOBIECT) &gt; 0;
    RETURN aCount;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topclientiold_getnrfact_art</obj_name>
  <obj_hashval>d6a8477ec6c8a58ef492afcf5ee63e39</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topclientiold_getnrfact_art(acodobiect numeric, acodpart numeric, atip numeric, acodlocatie numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aNr          numeric;
  aNrB        numeric;
  aCodSubunit  numeric;
  vDataINI    varchar := current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vDataIni',true);
  vDataFIN    varchar := current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vDataFin',true);
BEGIN
  --Adina 19.10.2020
  IF current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vSediiL',true)::numeric = 1 THEN
    aCodSubunit := GETSUBUNITATE();
    IF aCodSubunit = 1 then
      if aTip = 1 then
        SELECT
          COUNT(DISTINCT I.CodIes) INTO aNr
        FROM IESIRI I
             INNER JOIN IESIRI1 I1 ON I.CodIes   = I1.CodIes
             INNER JOIN NPART P    ON I.Partener = P.CodPart
        WHERE I1.CodObiect = aCodObiect
              AND I.TipDoc &lt;&gt; 20
              AND P.CodPart = aCodPart
              AND I.DataDoc BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I.CODLOCATIE = aCodLocatie
              AND pkg_list_base_topclientiold_ConditieIncludere(I1.CODIES1) &gt; 0;
        if current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vWithEmul',true)::boolean then
          SELECT
            COUNT(DISTINCT E.CODEMULARE) INTO ANRB
          FROM EMULARE E
               INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
          WHERE E.CODPART = aCodPart
                and E1.CODOBIECT = ACODOBIECT
                AND E.DATABON BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
                AND E.CODLOCATIE = ACODLOCATIE
                AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, E1.CODOBIECT) &gt; 0;
        end if;
      else
        SELECT
          COUNT(DISTINCT I.CodIes) INTO aNr
        FROM IESIRI I
             INNER JOIN IESIRI1 I1 ON I.CodIes   = I1.CodIes
             INNER JOIN NPART P    ON I.Partener = P.CodPart
        WHERE I1.ContDiscount = aCodObiect
              AND I.TipDoc &lt;&gt; 20
              AND P.CodPart = aCodPart
              AND I.DataDoc BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I.CODLOCATIE = aCodLocatie
              AND pkg_list_base_topclientiold_ConditieIncludere(I1.CODIES1) &gt; 0;
        if current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vWithEmul',true)::boolean then
          SELECT
            COUNT(DISTINCT E.CODEMULARE) INTO ANRB
          FROM EMULARE E
               INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
          WHERE E.CODPART = aCodPart
                and E1.CODOBIECT = ACODOBIECT
                AND E.DATABON BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
                AND E.CODLOCATIE = ACODLOCATIE
                AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                AND pkg_list_base_topclientiold_ConditieIncludere(E1.CODEMULARE1) &gt; 0;
        end if;
      end if;
    else
      if aTip = 1 then
        SELECT
          COUNT(DISTINCT I.CodIes) INTO aNr
        FROM IESIRI I
             INNER JOIN IESIRI1 I1 ON I.CodIes   = I1.CodIes
             INNER JOIN NPART P    ON I.Partener = P.CodPart
        WHERE I1.CodObiect = aCodObiect
              AND I.TipDoc &lt;&gt; 20
              AND P.CodPart = aCodPart
              AND I.DataDoc BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
              AND I.Subunitatea = aCodSubunit
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I.CODLOCATIE = aCodLocatie
              AND pkg_list_base_topclientiold_ConditieIncludere(I1.CODIES1) &gt; 0;
        if current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vWithEmul',true)::boolean then
          SELECT
            COUNT(DISTINCT E.CODEMULARE) INTO ANRB
          FROM EMULARE E
               INNER JOIN EMULARE1 E1   ON E.CODEMULARE    = E1.CODEMULARE
               INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
          WHERE E.CODPART = aCodPart
                and E1.CODOBIECT = ACODOBIECT
                AND E.DATABON BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
                AND E.CODLOCATIE = ACODLOCATIE
                AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                AND C.SUBUNITATEA = aCodSubunit
                AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0;
        end if;
      else
        SELECT
          COUNT(DISTINCT I.CodIes) INTO aNr
        FROM IESIRI I
             INNER JOIN IESIRI1 I1 ON I.CodIes   = I1.CodIes
             INNER JOIN NPART P    ON I.Partener = P.CodPart
        WHERE I1.ContDiscount = aCodObiect
              AND I.TipDoc &lt;&gt; 20
              AND P.CodPart = aCodPart
              AND I.DataDoc BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
              AND I.Subunitatea = aCodSubunit
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I.CODLOCATIE = aCodLocatie
              AND pkg_list_base_topclientiold_ConditieIncludere(I1.CODIES1) &gt; 0;
        if current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vWithEmul',true)::boolean then
          SELECT
            COUNT(DISTINCT E.CODEMULARE) INTO ANRB
          FROM EMULARE E
               INNER JOIN EMULARE1 E1   ON E.CODEMULARE    = E1.CODEMULARE
               INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
          WHERE E.CODPART = aCodPart
                and E1.CODOBIECT = ACODOBIECT
                AND E.DATABON BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
                AND E.CODLOCATIE = ACODLOCATIE
                AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                AND C.SUBUNITATEA = aCodSubunit
                AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0;
        end if;
      end if;
    end if;
  else
    aCodSubunit := GETSUBUNITATE();
    IF aCodSubunit = 1 then
      if aTip = 1 then
        SELECT
          COUNT(DISTINCT I.CodIes) INTO aNr
        FROM IESIRI I
             INNER JOIN IESIRI1 I1 ON I.CodIes   = I1.CodIes
             INNER JOIN NPART P    ON I.Partener = P.CodPart
        WHERE I1.CodObiect = aCodObiect
              AND I.TipDoc &lt;&gt; 20
              AND P.CodPart = aCodPart
              AND I.DataDoc BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND pkg_list_base_topclientiold_ConditieIncludere(I1.CODIES1) &gt; 0;
        if current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vWithEmul',true)::boolean then
          SELECT
            COUNT(DISTINCT E.CODEMULARE) INTO ANRB
          FROM EMULARE E
               INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
          WHERE E.CODPART = aCodPart
                and E1.CODOBIECT = ACODOBIECT
                AND E.DATABON BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
                AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0;
        end if;
      else
        SELECT
          COUNT(DISTINCT I.CodIes) INTO aNr
        FROM IESIRI I
             INNER JOIN IESIRI1 I1 ON I.CodIes   = I1.CodIes
             INNER JOIN NPART P    ON I.Partener = P.CodPart
        WHERE I1.ContDiscount = aCodObiect
              AND I.TipDoc &lt;&gt; 20
              AND P.CodPart = aCodPart
              AND I.DataDoc BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND pkg_list_base_topclientiold_ConditieIncludere(I1.CODIES1) &gt; 0;
        if current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vWithEmul',true)::boolean then
          SELECT
            COUNT(DISTINCT E.CODEMULARE) INTO ANRB
          FROM EMULARE E
               INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
          WHERE E.CODPART = aCodPart
                and E1.CODOBIECT = ACODOBIECT
                AND E.DATABON BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
                AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0;
        end if;
      end if;
    else
      if aTip = 1 then
        SELECT
          COUNT(DISTINCT I.CodIes) INTO aNr
        FROM IESIRI I
             INNER JOIN IESIRI1 I1 ON I.CodIes   = I1.CodIes
             INNER JOIN NPART P    ON I.Partener = P.CodPart
        WHERE I1.CodObiect = aCodObiect
              AND I.TipDoc &lt;&gt; 20
              AND P.CodPart = aCodPart
              AND I.DataDoc BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
              AND I.Subunitatea = aCodSubunit
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND pkg_list_base_topclientiold_ConditieIncludere(I1.CODIES1) &gt; 0;
        if current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vWithEmul',true)::boolean then
          SELECT
            COUNT(DISTINCT E.CODEMULARE) INTO ANRB
          FROM EMULARE E
               INNER JOIN EMULARE1 E1   ON E.CODEMULARE    = E1.CODEMULARE
               INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
          WHERE E.CODPART = aCodPart
                and E1.CODOBIECT = ACODOBIECT
                AND E.DATABON BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
                AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                AND C.SUBUNITATEA = aCodSubunit
                AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0;
        end if;
      else
        SELECT
          COUNT(DISTINCT I.CodIes) INTO aNr
        FROM IESIRI I
             INNER JOIN IESIRI1 I1 ON I.CodIes   = I1.CodIes
             INNER JOIN NPART P    ON I.Partener = P.CodPart
        WHERE I1.ContDiscount = aCodObiect
              AND I.TipDoc &lt;&gt; 20
              AND P.CodPart = aCodPart
              AND I.DataDoc BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
              AND I.Subunitatea = aCodSubunit
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND pkg_list_base_topclientiold_ConditieIncludere(I1.CODIES1) &gt; 0;
        if current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vWithEmul',true)::boolean then
          SELECT
            COUNT(DISTINCT E.CODEMULARE) INTO ANRB
          FROM EMULARE E
               INNER JOIN EMULARE1 E1   ON E.CODEMULARE    = E1.CODEMULARE
               INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
          WHERE E.CODPART = aCodPart
                and E1.CODOBIECT = ACODOBIECT
                AND E.DATABON BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
                AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                AND C.SUBUNITATEA = aCodSubunit
                AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0;
        end if;
      end if;
    end if;
  end if;
  RETURN aNr+ANRB;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topclientiold_getnrfact_part</obj_name>
  <obj_hashval>45318c25a55f8c5e500dfec87c9f9fd4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topclientiold_getnrfact_part(acodpart numeric, acodlocatie numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aNr          numeric;
  aNrB        numeric;
  aCodSubunit  numeric;
  vDataINI    varchar := current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vDataIni',true);
  vDataFIN    varchar := current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vDataFin',true);
BEGIN
  --Adina 19.10.2020
  aCodSubunit := GETSUBUNITATE();
  if current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vSediiL',true)::numeric = 1 then
    IF aCodSubunit = 1 then
      SELECT
        COUNT(DISTINCT I.CodIes) INTO aNr
      FROM IESIRI I
           INNER JOIN NPART P    ON I.Partener = P.CodPart
           INNER JOIN IESIRI1 I1 ON I1.CODIES  = I.CODIES
      WHERE P.CodPart = aCodPart
            AND I.TipDoc &lt;&gt; 20
            AND I.DataDoc BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
            AND coalesce(I.Anulat, 0) = 0
            AND coalesce(I.Initializari, 0) = 0
            AND I.Operat = 1
            AND I.CodLocatie = aCodLocatie
            AND pkg_list_base_topclientiold_ConditieIncludere(I1.CODIES1) &gt; 0;
      if current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vWithEmul',true)::boolean then
        SELECT
          COUNT(DISTINCT E.CODEMULARE) INTO ANRB
        FROM EMULARE E
             INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
        WHERE E.CODPART = aCodPart
              AND E.DATABON BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
              AND E.CODLOCATIE = ACODLOCATIE
              AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
              AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0;
      end if;
    ELSE
      SELECT
        COUNT(DISTINCT I.CodIes) INTO aNr
      FROM IESIRI I
           INNER JOIN NPART P    ON I.Partener = P.Codpart
           INNER JOIN IESIRI1 I1 ON I1.CODIES  = I.CODIES
      WHERE P.CodPart = aCodPart
            AND I.TipDoc &lt;&gt; 20
            AND I.DataDoc BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
            AND I.Subunitatea = aCodSubunit
            AND coalesce(I.Anulat, 0) = 0
            AND coalesce(I.Initializari, 0) = 0
            AND I.Operat = 1
            AND I.CodLocatie = aCodLocatie
            AND pkg_list_base_topclientiold_ConditieIncludere(I1.CODIES1) &gt; 0;
      if current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vWithEmul',true)::boolean then
        SELECT
          COUNT(DISTINCT E.CODEMULARE) INTO ANRB
        FROM EMULARE E
             INNER JOIN EMULARE1 E1   ON E.CODEMULARE    = E1.CODEMULARE
             INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
        WHERE E.CODPART = aCodPart
              AND E.DATABON BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
              AND E.CODLOCATIE = ACODLOCATIE
              AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
              AND C.SUBUNITATEA = ACODSUBUNIT
              AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0;
      end if;
    END IF;
  else
    IF aCodSubunit = 1 then
      SELECT
        COUNT(DISTINCT I.CodIes) INTO aNr
      FROM IESIRI I
           INNER JOIN NPART P    ON I.Partener = P.CodPart
           INNER JOIN IESIRI1 I1 ON I1.CODIES  = I.CODIES
      WHERE P.CodPart = aCodPart
            AND I.TipDoc &lt;&gt; 20
            AND I.DataDoc BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
            AND coalesce(I.Anulat, 0) = 0
            AND coalesce(I.Initializari, 0) = 0
            AND I.Operat = 1
            AND pkg_list_base_topclientiold_ConditieIncludere(I1.CODIES1) &gt; 0;
      if current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vWithEmul',true)::boolean then
        SELECT
          COUNT(DISTINCT E.CODEMULARE) INTO ANRB
        FROM EMULARE E
             INNER JOIN EMULARE1 E1   ON E.CODEMULARE    = E1.CODEMULARE
             INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
        WHERE E.CODPART = aCodPart
              AND E.DATABON BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
              AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
              AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0;
      end if;
    ELSE
      SELECT
        COUNT(DISTINCT I.CodIes) INTO aNr
      FROM IESIRI I
           INNER JOIN NPART P    ON I.Partener = P.Codpart
           INNER JOIN IESIRI1 I1 ON I1.CODIES  = I.CODIES
      WHERE P.CodPart = aCodPart
            AND I.TipDoc &lt;&gt; 20
            AND I.DataDoc BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
            AND I.Subunitatea = aCodSubunit
            AND coalesce(I.Anulat, 0) = 0
            AND coalesce(I.Initializari, 0) = 0
            AND I.Operat = 1
            AND pkg_list_base_topclientiold_ConditieIncludere(I1.CODIES1) &gt; 0;
      if current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vWithEmul',true)::boolean then
        SELECT
          COUNT(DISTINCT E.CODEMULARE) INTO ANRB
        FROM EMULARE E
             INNER JOIN EMULARE1 E1   ON E.CODEMULARE    = E1.CODEMULARE
             INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
        WHERE E.CODPART = aCodPart
              AND E.DATABON BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE (vDataFIN,'DD.MM.YYYY')
              AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
              AND C.SUBUNITATEA = ACODSUBUNIT
              AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0;
      end if;
    END IF;
  end if;
  RETURN aNr + ANRB;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topclientiold_getvalachiz</obj_name>
  <obj_hashval>5d42c8d626633cb2b8f68c47881a55a5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topclientiold_getvalachiz(acodies1 numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aVal  numeric;
  aTip  numeric;
BEGIN
  --Adina 19.10.2020
  SELECT i.tipdoc INTO aTip
  FROM iesiri1 i1
       INNER JOIN iesiri i ON i1.codies = i.codies
  WHERE codies1 = aCodIes1;

  IF aTip &lt;&gt; 26 THEN
    BEGIN
      SELECT sum( coalesce(lv.pretachiz, ns.pret-ns.adaos)*L1.cant ) INTO aVal
      FROM
        iesiri1 i1
        INNER JOIN iesiri i   ON i1.codies     = i.codies
        INNER JOIN LIVR L     ON I.CodIes      = L.CodIes
        INNER JOIN livr1 L1   ON L1.codies1    = i1.codies1 and l.codlivr = l1.codlivr
        LEFT  JOIN nirstoc ns ON L1.codnirstoc = ns.codnirstoc
        LEFT  JOIN livrval lv ON lv.codlivr1   = L1.codlivr1
      WHERE i1.codies1 = aCodIes1;
    EXCEPTION WHEN OTHERS THEN aVal := 0;
    END;
  ELSE
    BEGIN
      SELECT sum(coalesce(lv.pretachiz, ns.pret-ns.adaos)*L1.cant) INTO aVal
      FROM
        iesiri1 i1
        INNER JOIN ieslink il  ON il.codies1      = i1.codies1
        INNER JOIN iesiri1 ia1 ON il.codlinieaviz = ia1.codies1
        INNER JOIN iesiri ia   ON ia1.codies      = ia.codies
        INNER JOIN livr l      ON ia.codies       = l.codies
        INNER JOIN livr1 L1    ON L1.codies1      = ia1.codies1 and l1.codlivr = l.codlivr
        LEFT  JOIN nirstoc ns  ON L1.codnirstoc   = ns.codnirstoc
        LEFT  JOIN livrval lv  ON lv.codlivr1     = L1.codlivr1
      WHERE i1.codies1 = aCodIes1;
    EXCEPTION WHEN OTHERS THEN aVal := 0;
    END;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topclientiold_setparams</obj_name>
  <obj_hashval>b4d9a612fd5ce77b233fde90b5fac803</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topclientiold_setparams(pdataini character varying, pdatafin character varying, porder numeric, pavize numeric, psediil numeric, pcodjob1 numeric DEFAULT 0, psubunit numeric DEFAULT 0, paducustodie numeric DEFAULT 0, pallioart numeric DEFAULT 1, pallcls numeric DEFAULT 1, withemul numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni INTEGER;
  xLunaAnFin INTEGER;
BEGIN
  --Adina 19.10.2020
  PERFORM set_config('PKG_LIST_BASE_TOPCLIENTIOLD.vDataIni', pDataIni, false);
  PERFORM set_config('PKG_LIST_BASE_TOPCLIENTIOLD.vDataFin', pDataFin, false);

  IF COALESCE(pCodJob1,0) &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1,pDataIni,pDataFin,xLunaAnIni,xLunaAnFin);
  END IF;

  PERFORM set_config('PKG_LIST_BASE_TOPCLIENTIOLD.vAvize'      , pAvize , false);
  PERFORM set_config('PKG_LIST_BASE_TOPCLIENTIOLD.vOrder'      , pOrder , false);
  PERFORM set_config('PKG_LIST_BASE_TOPCLIENTIOLD.vSediiL'     , pSediiL, false);
  PERFORM set_config('PKG_LIST_BASE_TOPCLIENTIOLD.vSubunit'    , (COALESCE(pSubunit    ,0) = 1)::varchar, false);
  PERFORM set_config('PKG_LIST_BASE_TOPCLIENTIOLD.vAduCustodie', (COALESCE(pAduCustodie,0) = 1)::varchar, false);
  PERFORM set_config('PKG_LIST_BASE_TOPCLIENTIOLD.vAllIOArt'   , (COALESCE(pAllIOArt   ,1) = 1)::varchar, false);
  PERFORM set_config('PKG_LIST_BASE_TOPCLIENTIOLD.vAllCls'     , (COALESCE(pAllCls     ,1) = 1)::varchar, false);
  PERFORM set_config('PKG_LIST_BASE_TOPCLIENTIOLD.vWithEmul'   , (COALESCE(withEmul    ,0) = 1)::varchar, false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topfurn_conditieclasa</obj_name>
  <obj_hashval>ecfa0ec31b80b9fd8ad052a1fd8edb00</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topfurn_conditieclasa(aall numeric, acodobiect numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  rez       numeric;
  aCodIdent varchar;
BEGIN
  --Adina 07 septembrie 2020
  IF  aAll &gt; 0 THEN
    RETURN  1;
  END IF;

  BEGIN
    SELECT cls.codident INTO aCodIdent
    FROM nartobj obj
         INNER JOIN nart    art ON  obj.codarticol = art.codarticol
         INNER JOIN nclasea cls ON  art.clasa      = cls.codclasea
    WHERE obj.codobiect = aCodObiect;
  EXCEPTION WHEN others THEN
    RETURN  0;
  END;

  rez := 0;
  FOR v_rec IN (SELECT cls.codident
                FROM  tmp_manevra_liste tmp
                      INNER JOIN nclasea cls ON  cls.codclasea::varchar = tmp.valoare
                WHERE tmp.filtru = 'CODCLASEA'
               )
  LOOP
    IF  INSTRB(aCodIdent, v_rec.codident) = 1 THEN
      rez := 1;
      EXIT ;
    END IF;
  END LOOP;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topfurn_getnrfact_art</obj_name>
  <obj_hashval>c54a1aaea9e89805446f1f00d0e6a3c7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topfurn_getnrfact_art(acodobiect numeric, acodpart numeric, atip numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aNr         numeric := 0;
  aCodSubunit numeric;
  vAllIOArt   boolean := current_setting('PKG_LIST_BASE_TOPFURN.vAllIOArt', true)::boolean;
  vDataINI    varchar := current_setting('PKG_LIST_BASE_TOPFURN.vDataINI' , true);
  vDataFIN    varchar := current_setting('PKG_LIST_BASE_TOPFURN.vDataFIN' , true);
BEGIN
  --Adina 07 septembrie 2020
  aCodSubunit := getSUBUNITATE();

  IF vAllIOArt THEN
    SELECT COUNT(I.CodIntr) INTO aNr
    FROM  INTRARI I
          INNER JOIN INTRARI1 I1 ON  I.CodIntr  = I1.CodIntr
          INNER JOIN NPART    P  ON  I.Partener = P.CodPart
    WHERE I.TipDoc &lt;&gt; 2 AND  COALESCE(I.Anulat, 0) = 0 AND  COALESCE(I.Initializari, 0) = 0 AND  I.Operat = 1
      AND I.DataDoc BETWEEN TO_DATE(vDataINI, 'DD.MM.YYYY') AND TO_DATE(vDataFIN, 'DD.MM.YYYY')
      AND  P.CodPart = aCodPart AND  aCodObiect = CASE WHEN  aTip=1 THEN I1.CodObiect ELSE  I1.ContDiscount END
      AND  aCodSubunit = CASE WHEN  aCodSubunit=1 THEN 1 ELSE  I.Subunitatea END ;
  ELSE
    SELECT COUNT(CodIntr) INTO aNr
    FROM (
          SELECT I.CODINTR
          FROM  INTRARI I
                INNER JOIN INTRARI1 I1 ON  I.CodIntr   = I1.CodIntr
                INNER JOIN NIRSTOC  NS ON  NS.CODINTR1 = I1.CODINTR1
                INNER JOIN NPART    P  ON  I.Partener  = P.CodPart
          WHERE I.TipDoc &lt;&gt; 2 AND  COALESCE(I.Anulat, 0) = 0 AND  COALESCE(I.Initializari, 0) = 0 AND  I.Operat = 1
            AND I.DataDoc BETWEEN TO_DATE(vDataINI, 'DD.MM.YYYY') AND TO_DATE(vDataFIN, 'DD.MM.YYYY')
            AND  P.CodPart = aCodPart AND  I1.TIPLINIE = '=' AND  aCodObiect = CASE WHEN  aTip=1 THEN I1.CodObiect ELSE  I1.ContDiscount END
            AND  aCodSubunit = CASE WHEN  aCodSubunit=1 THEN 1 ELSE  I.Subunitatea END
            AND  EXISTS (SELECT TMP.VALOARE FROM TMP_MANEVRA_LISTE TMP WHERE TMP.FILTRU = 'CODIOART' AND  COALESCE(TMP.VALOARE,'') = COALESCE(NS.CODIOART::varchar,''))
          union ALL
          SELECT I.CODINTR
          FROM  INTRARI I
                INNER JOIN INTRARI1 I1 ON  I.CodIntr   = I1.CodIntr
                INNER JOIN NIRSTOC  NS ON  NS.CODINTR1 = I1.CODINTR1
                INNER JOIN NPART    P  ON  I.Partener  = P.CodPart
          WHERE I.TipDoc &lt;&gt; 2 AND  COALESCE(I.Anulat, 0) = 0 AND  COALESCE(I.Initializari, 0) = 0 AND  I.Operat = 1
            AND I.DataDoc BETWEEN TO_DATE(vDataINI, 'DD.MM.YYYY') AND TO_DATE(vDataFIN, 'DD.MM.YYYY')
            AND  P.CodPart = aCodPart AND  I1.TIPLINIE &lt;&gt; '=' AND  aCodObiect = CASE WHEN  aTip=1 THEN I1.CodObiect ELSE  I1.ContDiscount END
            AND  aCodSubunit = CASE WHEN  aCodSubunit=1 THEN 1 ELSE  I.Subunitatea END
          ) A_PG;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topfurn_getnrfact_part</obj_name>
  <obj_hashval>b5c17b4025d1137f630f621168bea462</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topfurn_getnrfact_part(acodpart numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCodSubunit numeric;
  aNr         numeric := 0;
  vAllIOArt   boolean := current_setting('PKG_LIST_BASE_TOPFURN.vAllIOArt', true)::boolean;
  vDataINI    varchar := current_setting('PKG_LIST_BASE_TOPFURN.vDataINI' , true);
  vDataFIN    varchar := current_setting('PKG_LIST_BASE_TOPFURN.vDataFIN' , true);
BEGIN
  --Adina 07 septembrie 2020
  aCodSubunit := getSUBUNITATE();

  IF vAllIOArt THEN
    IF  aCodSubunit = 1 THEN
      SELECT COUNT(I.CodIntr) INTO aNr
      FROM  INTRARI I
            INNER JOIN NPART P ON  I.Partener = P.CodPart
      WHERE P.CodPart = aCodPart
            AND  I.TipDoc &lt;&gt; 20
            AND I.DataDoc BETWEEN TO_DATE(vDataINI, 'DD.MM.YYYY') AND TO_DATE(vDataFIN, 'DD.MM.YYYY')
            AND  COALESCE(I.Anulat, 0) = 0
            AND  COALESCE(I.Initializari, 0) = 0
            AND  I.Operat = 1;
    ELSE
      SELECT COUNT(I.CodIntr) INTO aNr
      FROM  INTRARI I
            INNER JOIN NPART P ON  I.Partener = P.Codpart
      WHERE P.CodPart = aCodPart
            AND  I.TipDoc &lt;&gt; 20
            AND I.DataDoc BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE(vDataFIN,'DD.MM.YYYY')
            AND  I.Subunitatea = aCodSubunit
            AND  COALESCE(I.Anulat, 0) = 0
            AND  COALESCE(I.Initializari, 0) = 0
            AND  I.Operat = 1;
    END IF;
  ELSE
    IF  aCodSubunit = 1 THEN
      SELECT COUNT(CodIntr) INTO aNr
      FROM (
            SELECT I.CODINTR
            FROM  INTRARI I
                    INNER JOIN INTRARI1 I1 ON  I.CodIntr   = I1.CodIntr
                    INNER JOIN NIRSTOC  NS ON  NS.CODINTR1 = I1.CODINTR1
                    INNER JOIN NPART    P  ON  I.Partener  = P.CodPart
            WHERE P.CodPart = aCodPart
                  AND  I.TipDoc &lt;&gt; 20
                  AND I.DataDoc BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE(vDataFIN,'DD.MM.YYYY')
                  AND  COALESCE(I.Anulat, 0) = 0
                  AND  COALESCE(I.Initializari, 0) = 0
                  AND  I.Operat = 1
                  AND  I1.TIPLINIE = '='
                  AND  EXISTS (SELECT TMP.VALOARE FROM TMP_MANEVRA_LISTE TMP WHERE TMP.FILTRU = 'CODIOART' AND  COALESCE(TMP.VALOARE,'') = COALESCE(NS.CODIOART::varchar,''))
            union ALL
            SELECT I.CODINTR
            FROM  INTRARI I
                  INNER JOIN INTRARI1 I1 ON  I.CodIntr  = I1.CodIntr
                  INNER JOIN NPART    P  ON  I.Partener = P.CodPart
            WHERE P.CodPart = aCodPart
                  AND  I.TipDoc &lt;&gt; 20
                  AND I.DataDoc BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE(vDataFIN,'DD.MM.YYYY')
                  AND  COALESCE(I.Anulat, 0) = 0
                  AND  COALESCE(I.Initializari, 0) = 0
                  AND  I.Operat = 1
                  AND  I1.TIPLINIE &lt;&gt; '='
            ) A_PG;
    ELSE
      SELECT COUNT(CodIntr) INTO aNr
      FROM (
            SELECT I.CODINTR
            FROM  INTRARI I
                  INNER JOIN INTRARI1 I1 ON  I.CodIntr   = I1.CodIntr
                  INNER JOIN NIRSTOC  NS ON  NS.CODINTR1 = I1.CODINTR1
                  INNER JOIN NPART    P  ON  I.Partener  = P.Codpart
            WHERE P.CodPart = aCodPart
                  AND  I.TipDoc &lt;&gt; 20
                  AND I.DataDoc BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE(vDataFIN,'DD.MM.YYYY')
                  AND  I.Subunitatea = aCodSubunit
                  AND  COALESCE(I.Anulat, 0) = 0
                  AND  COALESCE(I.Initializari, 0) = 0
                  AND  I.Operat = 1
                  AND  I1.TIPLINIE = '='
                  AND  EXISTS (SELECT TMP.VALOARE FROM TMP_MANEVRA_LISTE TMP WHERE TMP.FILTRU = 'CODIOART' AND  COALESCE(TMP.VALOARE,'') = COALESCE(NS.CODIOART::varchar,''))
            union ALL
            SELECT I.CODINTR
            FROM  INTRARI I
                  INNER JOIN INTRARI1 I1 ON  I.CodIntr   = I1.CodIntr
                  INNER JOIN NIRSTOC  NS ON  NS.CODINTR1 = I1.CODINTR1
                  INNER JOIN NPART    P  ON  I.Partener  = P.Codpart
            WHERE P.CodPart = aCodPart
                  AND  I.TipDoc &lt;&gt; 20
                  AND I.DataDoc BETWEEN TO_DATE(vDataINI,'DD.MM.YYYY') AND TO_DATE(vDataFIN,'DD.MM.YYYY')
                  AND  I.Subunitatea = aCodSubunit
                  AND  COALESCE(I.Anulat, 0) = 0
                  AND  COALESCE(I.Initializari, 0) = 0
                  AND  I.Operat = 1
                  AND  I1.TIPLINIE &lt;&gt; '='
            ) B_PG;
    END IF;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topfurn_setnrfact_part</obj_name>
  <obj_hashval>97049390d2f139e1c95a2e4a9b83c15d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topfurn_setnrfact_part()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aNr numeric(20) := 0;
  aCodSubunit numeric(20);
BEGIN
  --Florin 13.01.2022 - fixat 56791
  --Florin 18.07.2022 - fixat 54942
  --Florin 07.07.2022
  aCodSubunit := GETSUBUNITATE();
  IF current_setting('PKG_LIST_BASE_TOPFURN.vAllIOArt', TRUE) THEN
    IF aCodSubunit = 1 then
      insert into tmp_cmd_tmp(codobiect,resta,tip)
      SELECT
        P.CODPART,COUNT(DISTINCT I.CodIntr), 'FACTPART'
      FROM INTRARI I
           INNER JOIN NPART P ON I.Partener = P.CodPart
      WHERE I.TipDoc &lt;&gt; 20
            AND I.DataDoc BETWEEN TO_DATE(current_setting('PKG_LIST_BASE_TOPFURN.vDataINI', true),'DD.MM.YYYY') AND TO_DATE (current_setting('PKG_LIST_BASE_TOPFURN.vDataFIN', TRUE),'DD.MM.YYYY')
            AND coalesce(I.Anulat, 0) = 0
            AND coalesce(I.Initializari, 0) = 0
            AND I.Operat = 1
      GROUP BY P.CODPART;
    ELSE
      insert into tmp_cmd_tmp(codobiect,resta,tip)
      SELECT
        P.CODPART,COUNT(DISTINCT I.CodIntr), 'FACTPART'
      FROM INTRARI I
           INNER JOIN NPART P ON I.Partener = P.Codpart
      WHERE I.TipDoc &lt;&gt; 20
            AND I.DataDoc BETWEEN TO_DATE(current_setting('PKG_LIST_BASE_TOPFURN.vDataINI', true),'DD.MM.YYYY') AND TO_DATE (current_setting('PKG_LIST_BASE_TOPFURN.vDataFIN', TRUE),'DD.MM.YYYY')
            AND I.Subunitatea = aCodSubunit
            AND coalesce(I.Anulat, 0) = 0
            AND coalesce(I.Initializari, 0) = 0
            AND I.Operat = 1
      GROUP BY P.CODPART;
    END IF;
  ELSE
    IF aCodSubunit = 1 then
      insert into tmp_cmd_tmp(codobiect,resta,tip)
      SELECT
        CODPART,COUNT(DISTINCT CodIntr),'FACTPART'
      FROM (
        SELECT DISTINCT I.CODINTR, I.PARTENER CODPART
        FROM INTRARI I
             INNER JOIN INTRARI1 I1 ON I.CodIntr = I1.CodIntr
             INNER JOIN NIR ON NIR.CODINTR = I.CODINTR
             INNER JOIN NIRSTOC NS ON NS.CODINTR1 = I1.CODINTR1 AND NS.CODNIR = NIR.CODNIR
        WHERE I.TipDoc &lt;&gt; 20
              AND I.DataDoc BETWEEN TO_DATE(current_setting('PKG_LIST_BASE_TOPFURN.vDataINI', true),'DD.MM.YYYY') AND TO_DATE (current_setting('PKG_LIST_BASE_TOPFURN.vDataFIN', TRUE),'DD.MM.YYYY')
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1 AND I1.TIPLINIE = '='
              AND EXISTS (SELECT TMP.VALOARE FROM TMP_MANEVRA_LISTE TMP WHERE TMP.FILTRU = 'CODIOART' AND TMP.VALOARE = NS.CODIOART::varchar)
        UNION ALL
        SELECT DISTINCT I.CODINTR, I.PARTENER CODPART
        FROM INTRARI I
             INNER JOIN INTRARI1 I1 ON I.CodIntr = I1.CodIntr
        WHERE I.TipDoc &lt;&gt; 20
              AND I.DataDoc BETWEEN TO_DATE(current_setting('PKG_LIST_BASE_TOPFURN.vDataINI', true),'DD.MM.YYYY') AND TO_DATE (current_setting('PKG_LIST_BASE_TOPFURN.vDataFIN', TRUE),'DD.MM.YYYY')
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1 AND I1.TIPLINIE &lt;&gt; '='
           ) a_pg GROUP BY CODPART;
    ELSE
      insert into tmp_cmd_tmp(codobiect,resta,tip)
      SELECT
        CODPART,COUNT(DISTINCT CodIntr),'FACTPART'
      FROM (
      SELECT DISTINCT I.CODINTR, I.PARTENER CODPART
      FROM INTRARI I
           INNER JOIN INTRARI1 I1 ON I.CodIntr = I1.CodIntr
           INNER JOIN NIR ON NIR.CODINTR = I.CODINTR
           INNER JOIN NIRSTOC NS ON NS.CODINTR1 = I1.CODINTR1 AND NS.CODNIR = NIR.CODNIR
      WHERE I.TipDoc &lt;&gt; 20
            AND I.DataDoc BETWEEN TO_DATE(current_setting('PKG_LIST_BASE_TOPFURN.vDataINI', true),'DD.MM.YYYY') AND TO_DATE (current_setting('PKG_LIST_BASE_TOPFURN.vDataFIN', TRUE),'DD.MM.YYYY')
            AND I.Subunitatea = aCodSubunit
            AND coalesce(I.Anulat, 0) = 0
            AND coalesce(I.Initializari, 0) = 0
            AND I.Operat = 1 AND I1.TIPLINIE = '='
            AND EXISTS (SELECT TMP.VALOARE FROM TMP_MANEVRA_LISTE TMP WHERE TMP.FILTRU = 'CODIOART' AND TMP.VALOARE = NS.CODIOART::varchar)
      UNION ALL
      SELECT DISTINCT I.CODINTR, I.PARTENER CODPART
      FROM INTRARI I
           INNER JOIN INTRARI1 I1 ON I.CodIntr = I1.CodIntr
      WHERE I.TipDoc &lt;&gt; 20
            AND I.DataDoc BETWEEN TO_DATE(current_setting('PKG_LIST_BASE_TOPFURN.vDataINI', true),'DD.MM.YYYY') AND TO_DATE (current_setting('PKG_LIST_BASE_TOPFURN.vDataFIN', TRUE),'DD.MM.YYYY')
            AND I.Subunitatea = aCodSubunit
            AND coalesce(I.Anulat, 0) = 0
            AND coalesce(I.Initializari, 0) = 0
            AND I.Operat = 1 AND I1.TIPLINIE &lt;&gt; '='
      ) b_pg GROUP BY CODPART;
    END IF;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topfurn_setparams</obj_name>
  <obj_hashval>7cd11a8dd549420a6e0be8887a1f8a7c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topfurn_setparams(pdataini character varying, pdatafin character varying, pinlei numeric, pcodjob1 numeric DEFAULT 0, pallioart numeric DEFAULT 1, pallcls numeric DEFAULT 1)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
BEGIN
  --Adina 07 septembrie 2020
  perform set_config('PKG_LIST_BASE_TOPFURN.vDataIni',pDataIni,false);
  perform set_config('PKG_LIST_BASE_TOPFURN.vDataFin',pDataFin,false);
  IF  pCodJob1 &gt; 0 THEN
    PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(pCodJob1, current_setting('PKG_LIST_BASE_TOPFURN.vDataIni', true), current_setting('PKG_LIST_BASE_TOPFURN.vDataFin', true), xLunaAnIni, xLunaAnFin);
  END IF;
  perform set_config('PKG_LIST_BASE_TOPFURN.InLei'    ,(pInLei)::varchar               ,false);
  perform set_config('PKG_LIST_BASE_TOPFURN.vAllIOArt',( trunc(pAllIOArt) = 1)::varchar,false);
  perform set_config('PKG_LIST_BASE_TOPFURN.vAllCls'  ,( trunc(pAllCls) = 1)::varchar  ,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_traduceri_processlist</obj_name>
  <obj_hashval>e4647c8a94933844611e4d48179a5139</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_traduceri_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'NARTOBJTRAD OT, NARTOBJ O, NLIMBA L';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 17 septembrie 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_TRADUCERI.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || tmpName || ' (Denumire, DenumireTrad, Limba, CodObiect, CodLimba ' || gUserFields || ')
  SELECT O.Denumire, OT.DenumireTrad, L.DenLimba, OT.CodObiect, OT.CodLimba ' || gUserAlias || '
  FROM NARTOBJTRAD OT
    INNER JOIN NARTOBJ O ON O.CodObiect = OT.CodObiect
    INNER JOIN NLIMBA  L ON L.CodLimba  = OT.CodLimba' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_transfdoc_getvaltva</obj_name>
  <obj_hashval>901f76752b3d4c3eb6f43490d445f020</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_transfdoc_getvaltva(acodtransf numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aVal numeric;
BEGIN
  --Adina 29.03.2021 - alstart, alstop
  --Adina 17 septembrie 2020
  aVal := 0;

  WITH T1 AS (
    SELECT   t.an, t.luna,
            CASE WHEN  COALESCE(l1.codnirstoc, 0) &lt;&gt; 0 THEN ns_s.codioart ELSE lv.codioart  END  CODIOARTS,
            na.codarticol,
            CASE WHEN  COALESCE(l1.codnirstoc, 0) &lt;&gt; 0 THEN ns_s.pret     ELSE lv.pretinreg END  PINREGS,
            t1.umsec, l1.cant
    FROM   transf t
          INNER JOIN transf1 t1   ON  t1.codtransf    = t.codtransf
          INNER JOIN livr l       ON  l.codtransf     = t.codtransf
          INNER JOIN livr1 l1     ON  l1.codlivr      = l.codlivr AND  l1.codies1 = t1.codtransf1
          INNER JOIN nartobj nobj ON  nobj.codobiect  = t1.codobiect
          INNER JOIN nart na       ON  na.codarticol   = nobj.codarticol
          LEFT  JOIN nirstoc ns_s ON  ns_s.codnirstoc = l1.codnirstoc
          LEFT  JOIN nir n_s       ON  n_s.codnir      = ns_s.codnir
          LEFT  JOIN livrval lv   ON  l1.codlivr1     = lv.codlivr1
    WHERE L.CODTRANSF = aCodTransf
  )
  SELECT sum(CASE
                 WHEN COALESCE(io1s.aretvaneex, 0) IN (0, 2) THEN t1.cant * t1.pinregs * (  100 + tva1.procent)  / 100 / COALESCE(um.paritate, 1)
                 ELSE t1.cant * t1.pinregs / COALESCE(um.paritate, 1)
              END )
  INTO aVal
  FROM   t1
        LEFT JOIN num1 um             ON  um.codum1      = t1.umsec
        LEFT JOIN tmp_ioart_luna io1s ON  io1s.codioart  = t1.codioarts
        LEFT JOIN ncont ncs           ON  ncs.codcont    = io1s.cont
        LEFT JOIN nart1 na1           ON  na1.codarticol = t1.codarticol AND (t1.an*12+t1.luna) BETWEEN  na1.alstart and  na1.alstop
        LEFT JOIN ntva1 tva1           ON  tva1.codtva    = na1.codtva    AND (t1.an*12+t1.luna) BETWEEN tva1.alstart and tva1.alstop
;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_intervutilaje_processlist</obj_name>
  <obj_hashval>a84d531e4b8dca6c4cecb9ef10a019a0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_intervutilaje_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sWhere           varchar := '';
  gSuplCols        VARCHAR := 'NARTOBJ NOBJ, NGEST G, NPART NP, NLOCALIT LOC, NINTERVENTIIAUTO I, NARTOBJ SERVICIU,
                              NCLASEA CLSI, NCLASEINT CLSINT, UTILAJE U, UTILAJE2C U2C, UTILAJE2 U2, UTILAJE20 U20';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  gAllUtilaje      boolean := current_setting('PKG_LIST_SELUTILAJE.gAllUtilaje', true)::boolean;
  gAllTipUtilaje   boolean := current_setting('PKG_LIST_SELUTILAJE.gAllTipUtilaje', true)::boolean;
  gAllInterventii  boolean := current_setting('PKG_LIST_SELUTILAJE.gAllInterventii', true)::boolean;
  gExtra1          boolean := current_setting('PKG_LIST_SELUTILAJE.gExtra1', true)::boolean;
  gPerDataInterv  NUMERIC := current_setting('PKG_LIST_SELUTILAJE.gPerDataInterv', true)::numeric;
  gDataIni        varchar := current_setting('PKG_LIST_SELUTILAJE.gDataIni', true);
  gDataFin        varchar := current_setting('PKG_LIST_SELUTILAJE.gDataFin', true);
BEGIN
  --Florin 02.10.2024 - sinc. Oracle
  --Florin 10.02.2023 - sinc. oracle (09.02.2023)
  --Florin 29.07.2022 - sinc. Oracle
  --Florin 26.07.2022 - fixat 55020
  --Florin 08.07.2022 - sinc. Oracle
  --Florin 13.01.2022 - DataEnd -&gt; DataStop
  --Adina 16 septembrie 2020
  PERFORM PKG_GLOBALS_SetSeparator(';');
  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, '', '', '',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_INTERVUTILAJE.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF  NOT gAllUtilaje THEN
    sWhere := sWhere || ' AND U.CODUTILAJ::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODUTILAJ'')';
  END IF;

  IF  NOT gAllInterventii THEN
    sWhere := sWhere || ' AND I.CODINTERVENTIIAUTO::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODINTERVENTIIAUTO'')';
  END IF;

  IF  gPerDataInterv = 1 THEN
    IF  NOT gExtra1 THEN
      sWhere := sWhere || ' AND U2C.DATAINDEXC   BETWEEN TO_DATE(''' || coalesce(gDataIni,'') || ''', ''DD.MM.YYYY'') AND TO_DATE(''' || coalesce(gDataFin,'') || ''', ''DD.MM.YYYY'')';
    ELSE
      sWhere := sWhere || ' AND ((U2C.DATAINDEXC BETWEEN TO_DATE(''' || coalesce(gDataIni,'') || ''', ''DD.MM.YYYY'') AND TO_DATE(''' || coalesce(gDataFin,'') || ''', ''DD.MM.YYYY'')) or  ' || coalesce(chr(13),'') ||
                          '       u2c.dataindexc is null) ';
    END IF;
  END IF;
  sWhere := sWhere||' AND (' || gAllTipUtilaje || ' OR U.TIP::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''TIPUTILAJ''))';

  sInsert :=
  'INSERT INTO ' || tmpName || ' (
    NAV_CodDoc, NAV_TipDoc,NAV_CodDoc1,TIP,
    DENUMIRE,NRINVENTAR,ETICHETA,TIPUTILAJ,FLOTA,
    INDEXC, DATAC, indexv, datav, NrDoc, Datadoc, Sectie, DATASTART, DATASTOP,
    DURATA, INTERVENTIE, SERVICIU, PERSONAL' || gUserFields || ')
  SELECT
    coalesce(C.CODCOMANDA,U.CODUTILAJ), coalesce(C.TIPDOC,508),case when c.codcomanda &gt; 0 then 0 else U2C.codutilaj2c end, ''PROPRIU'',
    NOBJ.DENUMIRE, U.NRINVENTAR,U.ETICHETA,U.TIPUTILAJ,U.FLOTA,
    U2C.INDEXC, U2C.DATAINDEXC, U2C.INDEXV, U2C.DATAV, C.NRDOC, C.DATADOC, G.DEN_GEST, U2C.DATASTART, U2C.DATAEND,
    (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'')) * 24,
    I.DENUMIRE, SERVICIU.DENUMIRE,
    (SELECT STRING_AGG(P.NUME||'' ''||P.PRENUME,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''')
     FROM UTILAJE2P U2P
          INNER JOIN NPERS P ON U2P.CODPERS = P.CODPERS
     WHERE U2P.CODUTILAJ2 = U2.CODUTILAJ2
     )' || gUserAlias || '
  FROM UTILAJE U
    INNER JOIN NARTOBJ NOBJ ON U.CODOBIECT = NOBJ.CODOBIECT';

  IF gExtra1 THEN
    sInsert := sInsert || '
    LEFT JOIN UTILAJE2C U2C       ON U2C.CODUTILAJ        = U.CODUTILAJ
    LEFT JOIN UTILAJE2 U2         ON U2.CODUTILAJ2        = U2C.CODUTILAJ2
    LEFT JOIN NINTERVENTIIAUTO I   ON I.CODINTERVENTIIAUTO = U2.INTERVENTIE
    LEFT JOIN COMANDA1 C1         ON U2C.CODCOMANDA1      = C1.CODCOMANDA1
    LEFT JOIN COMANDA C           ON C1.CODCOMANDA        = C.CODCOMANDA
    LEFT JOIN NGEST G             ON G.CODGEST            = C.CODGEST';
  ELSE
    sInsert := sInsert || '
    INNER JOIN UTILAJE2C U2C       ON U2C.CODUTILAJ        = U.CODUTILAJ
    INNER JOIN UTILAJE2 U2         ON U2.CODUTILAJ2        = U2C.CODUTILAJ2
    INNER JOIN NINTERVENTIIAUTO I ON I.CODINTERVENTIIAUTO = U2.INTERVENTIE
    INNER JOIN COMANDA1 C1         ON U2C.CODCOMANDA1      = C1.CODCOMANDA1
    INNER JOIN COMANDA C           ON C1.CODCOMANDA        = C.CODCOMANDA
    INNER JOIN NGEST G             ON G.CODGEST            = C.CODGEST';
  END IF;

  sInsert := sInsert || '
    LEFT JOIN UTILAJE20 U20     ON U20.CODUTILAJ20  = U.CODUTILAJ - U.CODUTILAJ
    LEFT JOIN NPART NP           ON NP.CODPART       = U.CODUTILAJ - U.CODUTILAJ
    LEFT JOIN NLOCALIT LOC       ON LOC.CODLOCALIT   = U.CODUTILAJ - U.CODUTILAJ
    LEFT JOIN NARTOBJ SERVICIU   ON I.SERVICIU       = SERVICIU.CODOBIECT
    LEFT JOIN NART ASERV         ON ASERV.CODARTICOL = SERVICIU.CODARTICOL
    LEFT JOIN NCLASEA CLSI       ON CLSI.CODCLASEA   = ASERV.CLASA
    LEFT JOIN NCLASEINT CLSINT   ON I.CLASA          = CLSINT.CODCLASEINT ' || gSuplJoins ||   ' where COALESCE(U.TIP,0) &lt;&gt; 3 '||sWhere;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  sWhere := ' WHERE CASE
                      WHEN U.TIP IS NULL AND U.CODPART &gt; 0 THEN 2
                      WHEN U.TIP = 3 THEN 2
                      ELSE
                        CASE
                          WHEN (SELECT COUNT(*) FROM UTILAJE1 WHERE CODUTILAJ = U.CODUTILAJ) &gt; 0 AND U.TIP IS NULL THEN 1
                          ELSE coalesce(U.TIP,0)
                        END
                    END = 2 ';

  IF  NOT gAllUtilaje THEN
    sWhere := sWhere || ' AND U.CODUTILAJ::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODUTILAJ'')';
  END IF;

  IF  NOT gAllInterventii THEN
    sWhere := sWhere || ' AND I.CODINTERVENTIIAUTO::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODINTERVENTIIAUTO'')';
  END IF;

  IF  gPerDataInterv = 1 THEN
    IF  NOT gExtra1 THEN
      sWhere := sWhere || ' AND U2C.DATAINDEXC   BETWEEN TO_DATE(''' || coalesce(gDataIni,'') || ''', ''DD.MM.YYYY'') AND TO_DATE(''' || coalesce(gDataFin,'') || ''', ''DD.MM.YYYY'')';
    ELSE
      sWhere := sWhere || ' AND ((U2C.DATAINDEXC BETWEEN TO_DATE(''' || coalesce(gDataIni,'') || ''', ''DD.MM.YYYY'') AND TO_DATE(''' || coalesce(gDataFin,'') || ''', ''DD.MM.YYYY'')) or  ' || coalesce(chr(13),'') ||
                          '       u2c.dataindexc is null) ';
    END IF;
  END IF;
  sWhere := sWhere||' AND (' || gAllTipUtilaje || ' OR U.TIP::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''TIPUTILAJ''))';

  sInsert :=
  'INSERT INTO ' || tmpName || ' (
    NAV_CodDoc,NAV_TipDoc,NAV_CodDoc1,TIP,
    DENUMIRE,NRINVENTAR,ETICHETA,TIPUTILAJ,FLOTA,
    INDEXC, DATAC, indexv, datav, NrDoc, Datadoc, Sectie, DATASTART, DATASTOP,
    DURATA, INTERVENTIE, SERVICIU, PERSONAL,
    P_NRDOC, P_DATADOC, P_DESCRIERE, P_STARE, P_OPERATOR, P_OBS, P_FACTURA, P_DEVIZ, P_LOCALITATE, P_ADRESA' || gUserFields || ')
  SELECT
    coalesce(C.CODCOMANDA,U.CODUTILAJ), coalesce(C.TIPDOC,508),case when c.codcomanda &gt; 0 then 0 else U2C.codutilaj2c end, ''CLIENT'',
    NOBJ.DENUMIRE, U.NRINVENTAR,U.ETICHETA,U.TIPUTILAJ,U.FLOTA,
    U2C.INDEXC, U2C.DATAINDEXC, U2C.INDEXV, U2C.DATAV, C.NRDOC, C.DATADOC, G.DEN_GEST, U2C.DATASTART, U2C.DATAEND,
    (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'')) * 24,
    I.DENUMIRE, SERVICIU.DENUMIRE,
    (SELECT STRING_AGG(P.NUME||'' ''||P.PRENUME,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''')
     FROM UTILAJE2P U2P
          INNER JOIN NPERS P ON U2P.CODPERS = P.CODPERS
     WHERE U2P.CODUTILAJ2 = U2.CODUTILAJ2
     ),
     U20.NRDOC, U20.DATADOC, U20.DESCRIERE,
     CASE U20.STARE
       WHEN 1 THEN ''initiala''
       WHEN 2 THEN ''in asteptare piese''
       WHEN 3 THEN ''in asteptare tehnician''
       WHEN 4 THEN ''in lucru''
       WHEN 7 THEN ''montaj''
       WHEN 5 THEN ''facturat''
       WHEN 6 THEN ''finalizat''
       WHEN 8 THEN ''in asteptare accept oferta/deviz client''
       WHEN 9 THEN ''in asteptare solutie producator''
       WHEN 10 THEN ''in atelier''
     END,
     (SELECT USERNAME FROM tmp_UTILIZATOR WHERE CODUTILIZATOR = U20.OPERATOR),
     U20.OBS, CASE WHEN IES.CODIES &gt; 0 THEN IES.PREFIXDOC||IES.NRDOC||''/''||TO_CHAR(IES.DATADOC,''DD.MM.YYYY'') END,
     CASE WHEN (SELECT COUNT(*) FROM UTILAJEDEV WHERE CODUTILAJ20 = U20.CODUTILAJ20) &gt; 0 THEN ''DA'' ELSE ''NU'' END,
     LOC.DEN_LOCALIT, U20.ADRESA  ' || gUserAlias || '
  FROM UTILAJE U
    INNER JOIN NARTOBJ NOBJ ON U.CODOBIECT = NOBJ.CODOBIECT';

  IF gExtra1 THEN
    sInsert := sInsert || '
    LEFT JOIN UTILAJE20 U20       ON U20.CODUTILAJ        = U.CODUTILAJ
    LEFT JOIN UTILAJE2 U2         ON U2.CODUTILAJ20       = U20.CODUTILAJ20
    LEFT JOIN UTILAJE2C U2C       ON U2C.CODUTILAJ        = U.CODUTILAJ AND U2C.CODUTILAJ2 = U2.CODUTILAJ2
    LEFT JOIN NINTERVENTIIAUTO I   ON I.CODINTERVENTIIAUTO = U2.INTERVENTIE
    LEFT JOIN COMANDA1 C1         ON U2C.CODCOMANDA1      = C1.CODCOMANDA1
    LEFT JOIN COMANDA C           ON C1.CODCOMANDA        = C.CODCOMANDA
    LEFT JOIN NGEST G             ON G.CODGEST            = C.CODGEST';
  ELSE
    sInsert := sInsert || '
    INNER JOIN UTILAJE20 U20       ON U20.CODUTILAJ        = U.CODUTILAJ
    INNER JOIN UTILAJE2 U2         ON U2.CODUTILAJ20       = U20.CODUTILAJ20
    INNER JOIN UTILAJE2C U2C       ON U2C.CODUTILAJ        = U.CODUTILAJ AND U2C.CODUTILAJ2 = U2.CODUTILAJ2
    INNER JOIN NINTERVENTIIAUTO I ON I.CODINTERVENTIIAUTO = U2.INTERVENTIE
    INNER JOIN COMANDA1 C1         ON U2C.CODCOMANDA1      = C1.CODCOMANDA1
    INNER JOIN COMANDA C           ON C1.CODCOMANDA        = C.CODCOMANDA
    INNER JOIN NGEST G             ON G.CODGEST            = C.CODGEST';
  END IF;

  sInsert := sInsert || '
    LEFT JOIN IESIRI IES         ON IES.CODIES       = U20.CODIES
    LEFT JOIN NPART NP           ON IES.PARTENER     = NP.CODPART
    LEFT JOIN NLOCALIT LOC       ON LOC.CODLOCALIT   = U20.CODLOCALIT
    LEFT JOIN NARTOBJ SERVICIU   ON I.SERVICIU       = SERVICIU.CODOBIECT
    LEFT JOIN NART ASERV         ON ASERV.CODARTICOL = SERVICIU.CODARTICOL
    LEFT JOIN NCLASEA CLSI       ON CLSI.CODCLASEA   = ASERV.CLASA
    LEFT JOIN NCLASEINT CLSINT   ON I.CLASA          = CLSINT.CODCLASEINT ' || gSuplJoins || sWhere;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_intrarisint_setjoinuri</obj_name>
  <obj_hashval>4942b242939486021da6edbe64d84e42</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_intrarisint_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 10.08.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_INTRARISINT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_intrext_processlist</obj_name>
  <obj_hashval>54540795f69c53273846ca6818c97aca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_intrext_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  gSuplCols   varchar := 'TMP_LST_INTRARI I1, INTRARI I, NARTOBJ NAO, NART NA, NCLASEA NCA, NUM UM1, NUM UM2, NPART NP, NAGENDA SSOC, NLOCALIT LOCSOC, NJUDET JUDSOC, NZONE ZONASOC,' || 'NPARTCODFISC FISC, NCLASEP NCP, NGEST NG, NGEST NGSERV, NSUBUNIT NS, NSUBUNIT NSUB, NMONEDE MON, NPART PROD, NARTOBJ1 NAO1, NART1 NA1,' || 'NTVA1 NT1, NCONT NC, CONTRACT CONTR, COMANDA C, OFERTA O, IOART IOA, IOPART IOP';
  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
    --Florin 25.01.2022 - fixat 52767
    --Adina 22.06.2021 - tichet 50623 - limitat lungimea col.serii la 500 si a col.datanir la 200 asa cum este in temporar
    --Adina 23.03.2021 - tichet 45766
    --Florin 10.08.2020
    --Florin 19.12.2020 - CIF_VALID cu un singur parametru
    --Florin 11.03.2021 - fixat 44846
    --Florin 14.04.2021 - sincronizat Oracle (39818)
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'TMP_UTILIZATOR', 'UTILIZATOR', 'UTILIZATOR.CODUTILIZATOR = I.USERID',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTCODFISC'  , 'CFF'       , 'CFF.COD_CODFISCAL = I.CODFISCAL'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'      , 'PD'        , 'PD.CODPART = NP.CODPART'            ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTTR'       , 'NPTR'      , 'NPTR.CODPARTTR = I1.DELEGAT'        ,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, 'NARTCLI'       , 'ACLI'      , 'ACLI.CODARTCLI =
    (SELECT PKG_LIST_BASE_UTILS_GETCODARTCLI.wme_result FROM PKG_LIST_BASE_UTILS_GETCODARTCLI(NULL, I1.CODOBIECT, I.PARTENER, NP.CODCLASA))');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTAMB'       , 'AA'        , 'AA.CODOBIECT = I1.CODOBIECT AND AA.UMSEC = I1.UMSEC',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CONTRACT1'     , 'CONTR1'    , 'CONTR1.CODCONTRACT1 = I1.CODCONTRACT1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'OFERTA1'       , 'O1'        , 'O1.CODOFERTA1 = I1.CODOFERTA1'        ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA1'      , 'C1'        , 'C1.CODCOMANDA1 = I1.CODCOMANDA1'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTRECOST'    , 'CC'        , 'CC.CODCENTRU = I1.CODCENTRU'          ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARI1'      , 'INTR1'     , 'INTR1.CODINTR1 = I1.CODINTR1'         ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARIF'      , 'INTRF'     , 'INTRF.CODINTR = I1.CODINTR'           ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARIF1'     , 'INTRF1'    , 'INTRF1.CODINTR1 = I1.CODINTR1'        ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDF'       , 'CFEXT'     , 'CFEXT.CODCOMANDA = C.CODCOMANDA'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDF1'      , 'CF1EXT'    , 'CF1EXT.CODCOMANDA1 = I1.CODCOMANDA1'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'ANALIZANOD'    , 'ANOD'      , 'ANOD.CODANALIZANOD = I1.CODANALIZANOD',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'ANALIZA'       , 'ANALIZ'    , 'ANALIZA.CODANALIZ = 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, 'NTARI'         , 'TARASOC'   , 'TARASOC.CODTARA = LOCSOC.CODTARA'           ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NAGENDA'       , 'SPROD'     , 'SPROD.CODPART = NAO.CODPRODUCATOR AND SPROD.SEDIUSOCIAL BETWEEN 4 AND 7 AND Coalesce(SSOC.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, 'NARTOBJTRAD'   , 'TRAD'      , 'TRAD.CODOBIECT = NAO.CODOBIECT AND TRAD.CODLIMBA = ' || fnc_getvalconstantalucru('LimbaDenArt'));
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_INTREXT.gSuplCols', gSuplCols, FALSE);

  sFiltru := '
      WHERE Coalesce(i1.cant,0) &lt;&gt; 0 AND i.anulat = 0
        AND NOT (i1.tiplinie IN (''G'',''T'')
        AND Coalesce(i1.contdiscount,0) = 0)
        AND Coalesce(i.initializari,0) = 0';
  IF current_setting('PKG_LIST_SELDOCEXT.vDupaData', TRUE)::NUMERIC = 1
  THEN
    sFiltru := COALESCE(sFiltru,'') || '
        AND i.datadoc ' || 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_intrari';
  sInsertTMP := PKG_LIST_BASE_INTRARI_Sql_tmp_lst_intrari(sFiltru);
  sInsert := '
      INSERT INTO ' || tmpName || '(
        CODFIRMA, DEN_FIRMA,
        CodDoc, TipDoc, CODOBIECT, TIPART, DEN_ARTICOL,
        IOART, SIMBOL, DEN_CONT, DEN_UM1, CANT,
        PU, PU_CU_TVA, PU_CU_TVAN, ADDIM,
        PROC_TVA, PROC_TVA_NART, DISCTOTAL, DISCTOT_TVA, DISCTOTCUTVA,
        VALOARE, VAL_TVA, VAL_CU_TVA, VAL_TVAN, VAL_CU_TVAN,
        DEN_PART, DATADOC, TIPDOCUMENT, NRDOC,
        DOCUMENT, NRAVIZ, SERDOC,
        BLOCAT, MONEDA, CURS, MASA, VOLUM, CODVAMAL, OBSLINIE, DEN_CLASEA,
        CODINTERNA, CODEXTERNA, DEN_PROD, UMALT1, UMALT2,
        CANTUM1, CANTUM2,
        PRETMAXIMAL,
        DEN_LOCALIT, DEN_JUDET, DEN_ZONA,
        TIPTVA, TIPTRANZ,
        DEN_CLASEP, CODFISCAL, CODEXTERNP, CODINTERNP, GESTACT, TIPSERIE, SERIE,
        ZILESCADENTE, TERMEN, MAJORARI, OBSDOC, INDEXLINIE,
        ANDOC, LUNADOC, LUNA, SUBUNITATEA, PRETINREG,
        CUICorect, clasas, nrinreg, datanir, EXCLUSPLATA' || gUserFields || ')
      SELECT
        TPG.FIRMAID, TPG.FIRMANAME,
        i1.codintr, i1.tipdoc , i1.codobiect, i1.tipart,
        (Case  When i1.tiplinie= ''T'' then ''Majorare direct pe cont (de total)''  When i1.tiplinie=''G'' then ''Majorare direct pe cont (de grup)'' else nao.denumire end), ioa.den_ioart,
        nc.simbol, Coalesce(substr(nc.den_cont, 100),''-''), (Case  When i1.tiplinie=''T'' then ''%'' When i1.tiplinie=''G'' then ''%'' else um.den_um1 end), i1.cantrec/Coalesce(um.paritate,1),
        i1.pu*Coalesce(um.paritate,1), (i1.pu+i1.tvau)*Coalesce(um.paritate,1), (i1.pu+i1.tvau*i1.coeftned)*Coalesce(um.paritate,1), i1.addim,
        i1.coef_tva * 100, nt1.procent,i1.cantrec*i1.discu, i1.cantrec*i1.discu*i1.coef_tva, i1.cantrec*i1.discu*(1+i1.coef_tva),
        i1.cantrec*i1.pu, i1.cantrec*i1.tvau, i1.cantrec*(i1.pu+i1.tvau), i1.cantrec*i1.tvau*i1.coeftned, i1.cantrec*(i1.pu+i1.tvau*i1.coeftned),
        (Case  When i1.tipdoc=6 then ns.den_subunit When i1.tipdoc=7 then ng.den_gest else np.den_part end), i.datadoc,
        (Case  When i1.tipdoc=9 then ''FA'' else i.prefixdoc end), i.nrdoc,
        i.prefixdoc||i.nrdoc||''/''||TO_CHAR(i.Datadoc,''dd.mm.yyyy''), i1.nraviz, i.seriadoc,
        (Case  When i.blocat=1 then ''Da'' else ''Nu'' end), mon.simbol, (Case  When i.curs=NULL then 1 When i.curs=0 then 1 else i.curs end),
        nao.masa, nao.volum, nao.codvamal, i1.obsart, nca.den_clasea,
        nao.codintern, nao.codextern, prod.den_part, um1.den_um, um2.den_um,
        CASE WHEN i1.cantrec = 0 THEN 0 WHEN i1.cantrec = i1.cant THEN i1.cantum1 ELSE i1.cantum1*i1.cant/i1.cantrec END CANTUM1, CASE WHEN i1.cantrec = 0 THEN 0 WHEN i1.cantrec = i1.cant THEN i1.cantum2 ELSE i1.cantum2*i1.cant/i1.cantrec END CANTUM2,
        CASE WHEN Coalesce(nao1.tippretmax,0) IN (1,2,3) THEN i1.pumaximal WHEN Coalesce(nao1.tippretmax,0) IN (4,5,6) THEN nao1.pretmaximal ELSE NULL END,
        locsoc.den_localit,judsoc.den_judet, zonasoc.den_zona,
        CASE WHEN i.tiptva = 1 THEN ''Taxare normala'' WHEN i.tiptva = 2 THEN ''Taxare inversa'' WHEN i.tiptva = 3 THEN ''Tranzactie triunghiulara'' WHEN i.tiptva = 4 THEN ''Suspendare temporara'' END TIPTVA,
        CASE
          WHEN i.tiptranzactie = 2 THEN ''Achizitie intracomunitara''
          WHEN i.tiptranzactie = 3 THEN ''Import servicii''
          WHEN i1.tipdoc = 5       THEN ''Import''
          WHEN i.tiptranzactie = 1 THEN ''Tranzactie interna''
        END TIPTRANZ,
        ncp.den_clasep, fisc.codfiscal, np.codextern, np.codintern,ngserv.den_gest,i1.tipserie, substr(i1.serii,1,500) serii,
        t.termen - i.datadoc, t.termen, t.majorari, i.obs, i1.indexlocal,
        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, nsub.den_subunit, i1.valinreg /
        (Case  When i1.cantrec=0 then 1 else i1.cantrec end) PRETINREG,
        CASE WHEN cif_valid(FISC.CodFiscal::varchar) = 0 THEN ''NU'' ELSE ''DA'' END CUICorect, NCLS.DEN_CLASEAS, I.NRI, substr(I1.datanir,1,200) datanir,
        CASE WHEN i.exclusplata = 1 THEN ''DA'' ELSE ''NU'' END EXCLUSPLATA' || coalesce(gUserAlias,'') || '
      FROM tmp_lst_intrari I1
        CROSS JOIN TMP_PKG_GLOBALS TPG
        LEFT JOIN COMANDA      C       ON C.CODCOMANDA  = I1.CODCOMANDA
        LEFT JOIN INTRARI      I       ON I.CodIntr     = I1.CodIntr
        LEFT JOIN NARTOBJ      NAO     ON nao.codobiect = i1.codobiect
        LEFT JOIN NART         NA      ON na.codarticol = nao.codarticol
        LEFT JOIN NCLASEA      NCA     ON nca.codclasea = na.clasa
        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 NPART        NP      ON np.codpart    = i.partener
        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     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 NPARTCODFISC FISC    ON fisc.codpart    = i.partener AND fisc.principal = 1
        LEFT JOIN NCLASEP      NCP     ON ncp.codclasep   = np.codclasa
        LEFT JOIN NGEST        NG      ON ng.codgest      = i.codgestprod
        LEFT JOIN NGEST        NGSERV  ON ngserv.codgest  = i1.gestact
        LEFT JOIN NSUBUNIT     NS      ON ns.codsubunit   = i.codsubunit
        LEFT JOIN NSUBUNIT     NSUB    ON nsub.codsubunit = i.subunitatea
        LEFT JOIN NMONEDE      MON     ON mon.codmoneda   = i.moneda
        LEFT JOIN NPART        PROD    ON prod.codpart    = nao.codproducator
        LEFT JOIN NCLASEAS     NCLS    ON NCLS.CODCLASEAS = NA.CLASASTATIST
        LEFT JOIN (
          SELECT g.coddoc, g.tipdoc, MAX(o.termen) termen, MAX(o.majorari) majorari
          FROM obligpif o INNER JOIN general g ON g.codgeneral = o.codgeneral
          WHERE o.termen IS NOT NULL AND o.semnificatie = 100
          GROUP BY g.coddoc, g.tipdoc) T on t.coddoc = i1.codintr AND t.tipdoc = i1.tipdoc
        LEFT JOIN NARTOBJ1 NAO1  ON nao1.codobiect    = i1.codobiect AND (i.an*12+i.luna) BETWEEN nao1.alstart AND nao1.alstop
        LEFT JOIN NART1    NA1   ON na1.codarticol    = nao.codarticol AND (i.an*12+i.luna) BETWEEN na1.alstart AND na1.alstop
        LEFT JOIN NTVA1    NT1   ON nt1.codtva        = na1.codtva AND (i.an*12+i.luna) BETWEEN nt1.alstart AND nt1.alstop
        LEFT JOIN NPART1   NP1   ON np1.codpart1      = i1.codpart1
        LEFT JOIN IOART1   IOA1  ON IOA1.CodIOArt1    = I1.CodIOArt1
        LEFT JOIN IOART    IOA   ON IOA.CodIOArt      = IOA1.CodIOArt
        LEFT JOIN IOPART   IOP   ON IOP.CodIOPart     = NP1.CodIOPart
        LEFT JOIN NCONT    NC    ON nc.codcont        = COALESCE(ioa1.cont,i1.codcont,0)
        LEFT JOIN NPARCAUT PAUT  ON PAUT.CODNPARCAUT  = I1.CODAUTO
        LEFT JOIN OFERTA   O     ON O.CODOFERTA       = I1.CODOFERTA
        LEFT JOIN CONTRACT CONTR ON contr.codcontract = i1.codcontract' || 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_intrext_setjoinuri</obj_name>
  <obj_hashval>d114c73261a4b428a2f66e206e4ba925</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_intrext_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 10.08.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_INTREXT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_intrmf_processlist</obj_name>
  <obj_hashval>65c43e86f2c71c7d9c7a40a716982c2e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_intrmf_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 61624
  --Florin 03.04.2024 - sinc. Oracle
  --Florin 02.04.2024 - sinc. Oracle
  --Florin 09.02.2022 - sinc. Oracle (07-08.02.2022)
  --Adina 02.04.2021 - alstart, alstop
  --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_INTRMF.gSuplCols',gSuplCols,false);

  sInsert := 'INSERT INTO '|| TMPNAME|| '(
            TipOperatie,
            Partener,
            Doc,
            Articol,
            NrInventar,
            Cant,
            Pret,
            Valoare,
            TVA,
            An,
            Luna,
            Cont '
            || coalesce (gUserFields ,'')
            || ')
          ';

        if fnc_getvalconstantalucru('MifixExtins')::numeric = 1 then
  sSelect := '
        SELECT
          CASE
            WHEN F.CODOPERATIE =  1 THEN ''Intrare in firma''
            WHEN F.CODOPERATIE =  2 THEN ''Transfer intre gestiuni''
            WHEN F.CODOPERATIE =  3 AND I.TIPDOC = 1 AND I.TIPFACTURA = 2              THEN ''Leasing''
            WHEN F.CODOPERATIE =  3 AND I.TIPDOC = 1 AND coalesce (I.TIPFACTURA,0) = 0 THEN ''Factura intrare''
            WHEN F.CODOPERATIE =  3 AND I.TIPDOC = 5                                   THEN ''Factura intrare din import''
            WHEN F.CODOPERATIE =  4 THEN ''Casare''
            WHEN F.CODOPERATIE =  5 THEN ''Vanzare''
            WHEN F.CODOPERATIE =  6 THEN ''Reevaluare - valoare MF''
            WHEN F.CODOPERATIE =  7 THEN ''Reevaluare - amortizare prec''
            WHEN F.CODOPERATIE =  8 THEN ''Marire de stoc''
            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,
          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) PRET,
          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 FISAMF               F
          INNER JOIN TRANSF       T    ON T.TIPDOC       = F.TIPDOC
          INNER JOIN TRANSF1      T1   ON T1.CODTRANSF   = T.CODTRANSF AND F.CODDOC1 = T1.CODTRANSF1
          INNER JOIN IMBMIFIXLINK L    ON L.CODTRANSF1   = T1.CODTRANSF1
          INNER JOIN INTRARI1     I1   ON I1.CODINTR1    = L.CODINTR1
          INNER JOIN INTRARI      I    ON I.CODINTR      = I1.CODINTR
          INNER JOIN NPART        P    ON I.PARTENER     = P.CODPART
          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    = I1.CODMIFIX
          INNER JOIN NIRSTOC      NS   ON T1.CODTRANSF1  = NS.CODTRANSF1
          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
          INNER JOIN NARTOBJ      IMB  ON I1.CODOBIECT   = IMB.CODOBIECT '
            || coalesce (gSuplJoins ,'')|| '
        WHERE 1=1 '
            || 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
          ''Punere in functiune'' TIPOPERATIE,
          '' ''  Partener,
          coalesce(T.NRDOC::varchar,'''') ||'' / '' ||coalesce(TO_CHAR (T.DATADOC, ''DD.MM.YYYY''),'''') Doc,
          OBJ.DENUMIRE  Articol,
          M.NrInventar,
          T1.Cant,
          T1.PU,
          T1.Cant * T1.PU Valoare,
          T1.TVA,
          T.An,
          T.Luna,
          C.SIMBOL Cont'
            || coalesce (gUserAlias ,'') || '
        FROM FISAMF          F
          INNER JOIN TRANSF  T    ON T.TIPDOC       = F.TIPDOC
          INNER JOIN TRANSF1 T1   ON T1.CODTRANSF   = T.CODTRANSF AND F.CODDOC1 = T1.CODTRANSF1
          INNER JOIN NARTOBJ OBJ  ON T1.CODOBIECT   = OBJ.CODOBIECT
          INNER JOIN NIRSTOC NS   ON T1.CODTRANSF1  = NS.CODTRANSF1
          INNER JOIN NART    ART  ON ART.CODARTICOL = OBJ.CODARTICOL
          INNER JOIN IOART1  IOA1 ON NS.CODIOART    = IOA1.CODIOART
          INNER JOIN NCONT   C    ON C.CODCONT      = IOA1.CONT
          INNER JOIN MIFIX   M    ON M.CODMIFIX     = F.CODMIFIX
          INNER JOIN MIFIX1  M1   ON M1.CODMIFIX    = F.CODMIFIX
          LEFT JOIN NARTOBJ  IMB  ON IMB.CODOBIECT  = OBJ.CODOBIECT - OBJ.CODOBIECT '
          || coalesce (gSuplJoins ,'') || '
        WHERE
          F.codoperatie = 12
          and (M1.ANSTART * 12 + M1.LUNASTART) = (SELECT MAX (ANSTART * 12 + LUNASTART) FROM MIFIX1 WHERE CODMIFIX = M.CODMIFIX)
          AND (M1.ANSTART * 12 + M1.LUNASTART) BETWEEN IOA1.ALStart and IOA1.ALStop ';
      PERFORM LIST_EXECUTE_IMMEDIATE(sInsert||sSelect, aListID, aListVer);
  else
  sSelect := '
  WITH NSS AS
  (
   SELECT DISTINCT NS1.CODNIRSTOCORIG CODNIRSTOC, MF1.CODMIFIX, mf1.cant
   FROM MIFIX1 MF1
        INNER JOIN MIFIX MF ON MF.CODMIFIX = MF1.CODMIFIX
        INNER JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = MF1.CODNIRSTOC
   WHERE MF.TIP = ''MF''
  )
  SELECT
    ''Intrare in firma'' TIPOPERATIE,
    P.DEN_PART Partener,
    coalesce(I.NRDOC::varchar, '''')||''/''||coalesce(TO_CHAR(I.DATADOC, ''DD.MM.YYYY''), '''') Doc,
    OBJ.DENUMIRE Articol,
    MF.NrInventar,
    nss.Cant,
    I1.PU * (case when coalesce(I.MONEDA,0) = 0 then 1 else coalesce(I.CURS,1) end) PRET,
    nss.Cant * I1.PU * (case when coalesce(I.MONEDA,0)= 0 then 1 else coalesce(I.CURS,1) end) Valoare,
    case when coalesce(i1.cant,0) = 0 then 0 else nss.cant/i1.cant*I1.TVA * (case when NVL(I.MONEDA,0) = 0 then 1 else NVL(I.CURS,1) end) end,
    I.An,
    I.Luna,
    C.SIMBOL Cont'||
    gUserAlias||'
  FROM NSS
    INNER JOIN NIRSTOC NS ON NSS.CODNIRSTOC = NS.CODNIRSTOC
    INNER JOIN INTRARI1     I1   ON I1.CODINTR1    = NS.CODINTR1
    INNER JOIN INTRARI      I    ON I.CODINTR      = I1.CODINTR
    INNER JOIN NPART        P    ON I.PARTENER     = P.CODPART
    INNER JOIN NARTOBJ      OBJ  ON NS.CODOBIECT   = OBJ.CODOBIECT
    INNER JOIN NART         ART  ON ART.CODARTICOL = OBJ.CODARTICOL
    INNER JOIN MIFIX        MF   ON MF.CODMIFIX    = NSS.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 NARTOBJ       IMB  ON OBJ.CODOBIECT - OBJ.CODOBIECT = IMB.CODOBIECT
    '||gSuplJoins||'
  WHERE 1=1 ' || 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(sInsert||sSelect, aListID, aListVer);

  sSelect := '
  WITH NSS AS
  (
   SELECT DISTINCT NS.CODNIRSTOC CODNIRSTOC, MF1.CODMIFIX, mf1.cant
   FROM MIFIX1 MF1
        INNER JOIN MIFIX MF ON MF.CODMIFIX = MF1.CODMIFIX
        INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = MF1.CODNIRSTOC
   WHERE MF.TIP = ''MF''
  )
  SELECT
    case when t.tipdoc = 12 then ''TRANSFER DIN MARFA''
         when t.tipdoc = 13 then ''MODIFICARE DE PRET''
    end TIPOPERATIE,
    '' '' Partener,
    T.NRDOC||''/''||TO_CHAR(T.DATADOC, ''DD.MM.YYYY'') Doc,
    OBJ.DENUMIRE Articol,
    MF.NrInventar,
    nss.Cant,
    case when t.tipdoc = 13 then T1.PU - NSP.PRET else t1.pu end PRET,
    nss.Cant * T1.PU Valoare,
    case when coalesce(T1.cant,0) = 0 then 0 else nss.cant/T1.cant*T1.TVA  end,
    T.An,
    T.Luna,
    C.SIMBOL Cont'||
    gUserAlias||'
  FROM NSS
    INNER JOIN NIRSTOC NS ON NSS.CODNIRSTOC = NS.CODNIRSTOC
    INNER JOIN TRANSF1     T1   ON T1.CODTRANSF1    = NS.CODTRANSF1
    INNER JOIN TRANSF      T    ON T.CODTRANSF      = T1.CODTRANSF
    INNER JOIN NARTOBJ      OBJ  ON NS.CODOBIECT   = OBJ.CODOBIECT
    INNER JOIN NART         ART  ON ART.CODARTICOL = OBJ.CODARTICOL
    INNER JOIN MIFIX        MF   ON MF.CODMIFIX    = NSS.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
    INNER JOIN NIRSTOC NSP ON NS.CODNIRSTOCPARINTE = NSP.CODNIRSTOC
    INNER JOIN NIR      NP ON NP.CODNIR = NSP.CODNIR
    INNER JOIN NIR       N ON N.CODNIR = NS.CODNIR
    INNER JOIN NGEST GP ON GP.CODGEST = NP.GEST
    INNER JOIN NGEST G ON G.CODGEST = N.GEST
    LEFT JOIN NARTOBJ       IMB  ON OBJ.CODOBIECT - OBJ.CODOBIECT = IMB.CODOBIECT
    '||gSuplJoins||'
  WHERE GP.CODSUBUNIT = G.CODSUBUNIT ' || 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);

    IF fnc_getvalconstantalucru('Holding') = '1' THEN
      sSelect := '
      WITH NSS AS
      (
       SELECT DISTINCT NS.CODNIRSTOC CODNIRSTOC, MF1.CODMIFIX, mf1.cant
       FROM MIFIX1 MF1
            INNER JOIN MIFIX MF ON MF.CODMIFIX = MF1.CODMIFIX
            INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = MF1.CODNIRSTOC
       WHERE MF.TIP = ''MF''
      )
      SELECT
        case when t.tipdoc = 12 then ''TRANSFER DIN MARFA''
             when t.tipdoc = 13 then ''MODIFICARE DE PRET''
        end TIPOPERATIE,
        '' '' Partener,
        T.NRDOC||''/''||TO_CHAR(T.DATADOC, ''DD.MM.YYYY'') Doc,
        OBJ.DENUMIRE Articol,
        MF.NrInventar,
        nss.Cant,
        T1.PU PRET,
        nss.Cant * T1.PU Valoare,
        case when coalesce(T1.cant,0) = 0 then 0 else nss.cant/T1.cant*T1.TVA  end,
        T.An,
        T.Luna,
        C.SIMBOL Cont'||
        gUserAlias||'
      FROM NSS
        INNER JOIN NIRSTOC NS ON NSS.CODNIRSTOC = NS.CODNIRSTOC
        INNER JOIN TRANSF1     T1   ON T1.CODTRANSF1    = NS.CODTRANSF1
        INNER JOIN TRANSF      T    ON T.CODTRANSF      = T1.CODTRANSF
        INNER JOIN NARTOBJ      OBJ  ON NS.CODOBIECT   = OBJ.CODOBIECT
        INNER JOIN NART         ART  ON ART.CODARTICOL = OBJ.CODARTICOL
        INNER JOIN MIFIX        MF   ON MF.CODMIFIX    = NSS.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
        INNER JOIN NIRSTOC NSP ON NS.CODNIRSTOCPARINTE = NSP.CODNIRSTOC
        INNER JOIN NIR      NP ON NP.CODNIR = NSP.CODNIR
        INNER JOIN NIR       N ON N.CODNIR = NS.CODNIR
        INNER JOIN NGEST GP ON GP.CODGEST = NP.GEST
        INNER JOIN NGEST G ON G.CODGEST = N.GEST
        LEFT JOIN NARTOBJ       IMB  ON OBJ.CODOBIECT - OBJ.CODOBIECT = IMB.CODOBIECT
        '||gSuplJoins||'
      WHERE GP.CODSUBUNIT &lt;&gt; G.CODSUBUNIT '||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(sInsert||sSelect, aListID, aListVer);
    end if;
  end if;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_iopers_setjoinuri</obj_name>
  <obj_hashval>a13e573d47bbc835b50a507b9e6c7949</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_iopers_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$

  begin
    perform Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_IOPERS.gSuplCols', true));
    perform pkg_list_struct_AdunaColoanele();
end;

$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_jurncump_pregateste_tmp_lst_tvaincas</obj_name>
  <obj_hashval>1c5db4241d2e3ecfc7427b65abbba82d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_jurncump_pregateste_tmp_lst_tvaincas(alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsAux1   TEXT;
  sInsAux2   TEXT;
  sDebug     TEXT;
  sAnLista   TEXT    := coalesce(current_setting('PKG_LIST_BASE_JURNCUMP.vAnLista',   true), '0');
  sLunaLista TEXT    := coalesce(current_setting('PKG_LIST_BASE_JURNCUMP.vLunaLista', true), '0');
  sTip       TEXT    := coalesce(current_setting('PKG_LIST_BASE_JURNCUMP.vTip',       true), '0');
  sSubunit   TEXT    := coalesce(current_setting('PKG_LIST_BASE_JURNCUMP.vSubunit',   true), '0');
  vSubunit   NUMERIC := sSubunit::NUMERIC;
  sAnLunaIni TEXT    := coalesce(current_setting('PKG_LIST_BASE_JURNCUMP.vAnLunaIni', true), '0');
  sAL_OL     TEXT;
begin
  --Stef  28.04.2025
  sDebug :=
    'DO $$' || Chr(10) ||
    'BEGIN' || Chr(10) ||
    '  perform pkg_list_base_jurncump_setperioada(' ||sAnLista|| ',' || sLunaLista || ',' || sTip || ',' || sSubunit || ');' || Chr(10) ||
    'END$$;';
  PERFORM PKG_GLOBALS_CheckDebugMode(sDebug, aLISTID, aLISTVER);

  SELECT Least (ancurent*12+lunacurenta,sAnLunaIni::numeric)::text INTO sAL_OL FROM firmaluni;

  sInsAux1 := 'INSERT INTO TMP_LST_TVAINCAS(
    coddoc, tipdoc, nrdoc, prefixdoc, seriadoc, datadoc, datastingere, valstinsa, datastop, coef, coefbaza, coeftva, tipstingere, prefixstingere, nrstingere,
    coefdoc,
    coefdocbaza,
    coefdoctva,
    orddoc, countdoc, coefplata, coefplatabaza, coefplatatva, restdoc)
  WITH
  I AS (
    SELECT CODINTR, TIPDOC, VALDOC, TVADOC, SPLITTVA
    -- exista cazuri mai dubioase pe facturile din initializate cu cecuri in curs din initializare cand valdoc si valoare obligatie nu e real, e rest de incasat
    FROM (
      SELECT I.CODINTR, I.TIPDOC, Sum(Coalesce(i1.pu*i1.cant, 0)+Coalesce(i1.tva,0)) ValDoc, Sum(Coalesce(i1.tva,0)) TVADoc, I.SPLITTVA
      FROM INTRARI I INNER JOIN INTRARI1 i1 ON I1.CODINTR = I.CODINTR
      WHERE Coalesce(I.INITIALIZARI, 0) = 1 AND I.TVAINCASARE = 1 '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', NULL, NULL, vSubunit)|| '
        AND EXISTS (SELECT 1 FROM GENERAL G WHERE G.CODDOC = I.CODINTR AND G.TIPDOC = I.TIPDOC)
      GROUP BY I.CODINTR, I.TIPDOC, I.SPLITTVA
    ) pg_sql
    WHERE TVADOC &lt;&gt; 0 AND VALDOC &lt;&gt; 0
    UNION
    SELECT I.CODINTR, I.TIPDOC, I.VALDOC, I.TVADOC, I.SPLITTVA
    FROM INTRARI I
    WHERE I.AN*12+I.LUNA &lt; '||sAnLunaIni||'
      AND I.AN*12+I.LUNA &gt;= (SELECT ancurent*12+lunacurenta FROM firmaluni)
      AND Coalesce(I.INITIALIZARI,0) = 0
      AND I.TVAINCASARE = 1 AND I.TVADOC &lt;&gt; 0 AND I.VALDOC &lt;&gt; 0 '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', NULL, NULL, vSubunit)||'
      AND EXISTS (SELECT 1 FROM INTRARI1 I1 WHERE I1.CODINTR = I.CODINTR AND Coalesce(I1.TVANEDED,0) &lt;&gt; 1)
    UNION
    SELECT DISTINCT I.CODINTR, I.TIPDOC, I.VALDOC, I.TVADOC, I.SPLITTVA
    FROM OBLIGPIFLUNA OL
      INNER JOIN OBLIGPIF O ON O.CODOBLIGPIF = OL.CODOBLIGPIF
      INNER JOIN GENERAL  G ON G.CODGENERAL  = O.CODGENERAL
      INNER JOIN INTRARI  I ON I.CODINTR     = G.CODDOC AND I.TIPDOC = G.TIPDOC
    WHERE OL.AN*12+OL.LUNA+1 = '||sAL_OL||'
      AND OL.REST &lt;&gt; 0
      AND I.AN*12+I.LUNA &lt; (SELECT ancurent*12+lunacurenta FROM firmaluni)
      AND Coalesce(I.INITIALIZARI,0) = 0
      AND I.TVAINCASARE = 1 AND I.TVADOC &lt;&gt; 0 AND I.VALDOC &lt;&gt; 0 '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', NULL, NULL, vSubunit)||'
      AND NOT O.SEMNIFICATIE IN (110)
      AND EXISTS (SELECT 1 FROM INTRARI1 I1 WHERE I1.CODINTR = I.CODINTR AND Coalesce(I1.TVANEDED,0) &lt;&gt; 1)
    UNION
    SELECT DISTINCT I.CODINTR, I.TIPDOC, I.VALDOC, I.TVADOC, I.SPLITTVA
    FROM OBLIGPIFLUNA OL
      INNER JOIN OBLIGPIF O_CEC   ON O_CEC.CODOBLIGPIF  = OL.CODOBLIGPIF AND O_CEC.SEMNIFICATIE IN (500,600)
      INNER JOIN GENERAL  G_CEC   ON G_CEC.CODGENERAL   = O_CEC.CODGENERAL
      INNER JOIN GENERAL  G_STING ON G_STING.TIPDOC     = 31 AND G_STING.CODDOC = G_CEC.CODDOC AND G_STING.SEMNIFICATIE &lt;&gt;  G_CEC.SEMNIFICATIE
      INNER JOIN OBLIGPIF O_STING ON O_STING.CODGENERAL = G_STING.CODGENERAL
      INNER JOIN STINGERE S       ON S.CODSTINGATORPIF  = O_STING.CODOBLIGPIF
      INNER JOIN OBLIGPIF O       ON O.CODOBLIGPIF      = S.CODSTINSPIF
      INNER JOIN GENERAL  G       ON G.CODGENERAL       = O.CODGENERAL
      INNER JOIN INTRARI  I       ON I.CODINTR          = G.CODDOC AND I.TIPDOC = G.TIPDOC
    WHERE OL.AN*12+OL.LUNA+1 = '||sAL_OL||'
      AND OL.REST &lt;&gt; 0
      AND Coalesce(I.INITIALIZARI,0) = 0
      AND I.AN*12+I.LUNA &lt; (SELECT ancurent*12+lunacurenta FROM firmaluni)
      AND I.TVAINCASARE = 1 AND I.TVADOC &lt;&gt; 0 AND I.VALDOC &lt;&gt; 0 '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', NULL, NULL, vSubunit)||'
      AND EXISTS (SELECT 1 FROM INTRARI1 I1 WHERE I1.CODINTR = I.CODINTR AND Coalesce(I1.TVANEDED,0) &lt;&gt; 1)
  ),
  S AS (
    SELECT
      I.CODINTR, I.TIPDOC, I.VALDOC, I.TVADOC, I.SPLITTVA,
      SUM(
        ( --STINS TREZOR
          SELECT Coalesce(SUM(S.VALOARE),0)
          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 = O.CODOBLIGPIF AND Coalesce(T1.ANULAT, 0) = 0 AND T1.AN * 12 + T1.LUNA &lt; '||sAnLunaIni||'
            AND S.VALOARE &lt;&gt; 0
        ) * CASE WHEN O.VALOARE &lt; 0 THEN -1 ELSE 1 END +
        ( --STINS CEC INCASAT
          SELECT Coalesce(SUM(CASE WHEN Coalesce(T1.Initializari, 0) = 1 THEN I.VALDOC ELSE S.VALOARE END),0)
          FROM STINGERE S
            INNER JOIN OBLIGPIF O_STINGATOR ON O_STINGATOR.CODOBLIGPIF = S.CODSTINGATORPIF
            INNER JOIN GENERAL  G_STINGATOR ON G_STINGATOR.CODGENERAL  = O_STINGATOR.CODGENERAL AND G_STINGATOR.TIPDOC = 31
            INNER JOIN TREZOR1  T1          ON T1.CODTREZOR1           = G_STINGATOR.CODDOC
            INNER JOIN GENERAL  G_CEC       ON G_CEC.TIPDOC            = 31 AND G_CEC.CODDOC = G_STINGATOR.CODDOC AND G_CEC.SEMNIFICATIE IN (500,600)
            INNER JOIN OBLIGPIF O_CEC       ON O_CEC.CODGENERAL        = G_CEC.CODGENERAL
            INNER JOIN STINGERE S_CEC       ON S_CEC.CODSTINSPIF       = O_CEC.CODOBLIGPIF
            INNER JOIN OBLIGPIF O_CURENT    ON O_CURENT.CODOBLIGPIF    = S_CEC.CODSTINGATORPIF
            INNER JOIN GENERAL  G_CURENT    ON G_CURENT.CODGENERAL     = O_CURENT.CODGENERAL AND G_CURENT.TIPDOC = 30
            INNER JOIN TREZOR1  T1_CURENT   ON T1_CURENT.CODTREZOR1    = G_CURENT.CODDOC
          WHERE S.CODSTINSPIF = O.CODOBLIGPIF AND Coalesce(T1.ANULAT, 0) = 0
            AND T1.AN * 12 + T1.LUNA &lt; '||sAnLunaIni||'
            AND T1_CURENT.AN * 12 + T1_CURENT.LUNA &lt; '||sAnLunaIni||'
            AND S_CEC.VALOARE &lt;&gt; 0
        ) * CASE WHEN O.VALOARE &lt; 0 THEN -1 ELSE 1 END +
        ( -- STINS COMPENSARI
          SELECT Coalesce(SUM(S.VALOARE),0)
          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 = O.CODOBLIGPIF AND C.AN * 12 + C.LUNA &lt; '||sAnLunaIni||'
            AND S.VALOARE &lt;&gt; 0
        ) * CASE WHEN O.VALOARE &lt; 0 THEN -1 ELSE 1 END
      ) STINSDOC,
      SUM(
        ( --STINS TREZOR
          SELECT Coalesce(SUM(S.DINCARETVA),0)
          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 = O.CODOBLIGPIF AND Coalesce(T1.ANULAT, 0) = 0 AND T1.AN * 12 + T1.LUNA &lt; '||sAnLunaIni||'
            AND Coalesce(S.DINCARETVA,0) &lt;&gt; 0
        ) * CASE WHEN O.VALOARE &lt; 0 THEN -1 ELSE 1 END +
        ( --STINS CEC INCASAT
          SELECT Coalesce(SUM(CASE WHEN Coalesce(T1.Initializari, 0) = 1 AND COALESCE(S_CEC.DINCARETVA,0) &lt;&gt; 0 THEN I.TVADOC ELSE S.DINCARETVA END),0)
          FROM STINGERE S
            INNER JOIN OBLIGPIF O_STINGATOR ON O_STINGATOR.CODOBLIGPIF = S.CODSTINGATORPIF
            INNER JOIN GENERAL  G_STINGATOR ON G_STINGATOR.CODGENERAL  = O_STINGATOR.CODGENERAL AND G_STINGATOR.TIPDOC = 31
            INNER JOIN TREZOR1  T1          ON T1.CODTREZOR1           = G_STINGATOR.CODDOC
            INNER JOIN GENERAL  G_CEC       ON G_CEC.TIPDOC            = 31 AND G_CEC.CODDOC = G_STINGATOR.CODDOC AND G_CEC.SEMNIFICATIE IN (500,600)
            INNER JOIN OBLIGPIF O_CEC       ON O_CEC.CODGENERAL        = G_CEC.CODGENERAL
            INNER JOIN STINGERE S_CEC       ON S_CEC.CODSTINSPIF       = O_CEC.CODOBLIGPIF
            INNER JOIN OBLIGPIF O_CURENT    ON O_CURENT.CODOBLIGPIF    = S_CEC.CODSTINGATORPIF
            INNER JOIN GENERAL  G_CURENT    ON G_CURENT.CODGENERAL     = O_CURENT.CODGENERAL AND G_CURENT.TIPDOC = 30
            INNER JOIN TREZOR1  T1_CURENT   ON T1_CURENT.CODTREZOR1    = G_CURENT.CODDOC
          WHERE S.CODSTINSPIF = O.CODOBLIGPIF AND Coalesce(T1.ANULAT, 0) = 0
            AND T1.AN * 12 + T1.LUNA &lt; '||sAnLunaIni||'
            AND T1_CURENT.AN * 12 + T1_CURENT.LUNA &lt; '||sAnLunaIni||'
            AND Coalesce(S_CEC.DINCARETVA,0) &lt;&gt; 0
        ) * CASE WHEN O.VALOARE &lt; 0 THEN -1 ELSE 1 END +
        ( -- STINS COMPENSARI
          SELECT Coalesce(SUM(S.DINCARETVA),0)
          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 = O.CODOBLIGPIF AND C.AN * 12 + C.LUNA &lt; '||sAnLunaIni||'
            AND Coalesce(S.DINCARETVA,0) &lt;&gt; 0
        ) * CASE WHEN O.VALOARE &lt; 0 THEN -1 ELSE 1 END
      ) STINSDINCARETVA
    FROM I
      INNER JOIN GENERAL  G ON G.CODDOC     = I.CODINTR AND G.TIPDOC = I.TIPDOC
      INNER JOIN OBLIGPIF O ON O.CODGENERAL = G.CODGENERAL
    GROUP BY I.CODINTR, I.TIPDOC, I.VALDOC, I.TVADOC, I.SPLITTVA),
  TVAI AS (
    SELECT
      TMP.CODDOC, TMP.TIPDOC, TMP.NRDOC, TMP.PREFIXDOC, TMP.SERIADOC, TMP.DATADOC, TMP.DATASTINGERE, TMP.VALSTINSA, TMP.DATASTOP, TMP.COEF, TMP.COEFBAZA, TMP.COEFTVA, TMP.TIPSTINGERE, TMP.PREFIXSTINGERE, TMP.NRSTINGERE,
      Row_NUMBER()      OVER (PARTITION BY TMP.CODDOC, TMP.TIPDOC ORDER BY TMP.DATASTINGERE) OrdDoc,
      COUNT(1)          OVER (PARTITION BY TMP.CODDOC, TMP.TIPDOC) CountDoc,
      SUM(TMP.Coef)     OVER (PARTITION BY TMP.CODDOC, TMP.TIPDOC ORDER BY TMP.DATASTINGERE ROWS UNBOUNDED PRECEDING) CoefPlata,
      SUM(TMP.CoefBaza) OVER (PARTITION BY TMP.CODDOC, TMP.TIPDOC ORDER BY TMP.DATASTINGERE ROWS UNBOUNDED PRECEDING) CoefPlataBaza,
      SUM(TMP.CoefTVA)  OVER (PARTITION BY TMP.CODDOC, TMP.TIPDOC ORDER BY TMP.DATASTINGERE ROWS UNBOUNDED PRECEDING) CoefPlataTva
    FROM TMP_TVAINCAS TMP
    WHERE (COEFTVA &lt;&gt; 0 OR SPLITTVA = 1) )
  SELECT
    S.CODINTR, S.TIPDOC, TVAI.NRDOC, TVAI.PREFIXDOC, TVAI.SERIADOC, TVAI.DATADOC, TVAI.DATASTINGERE, TVAI.VALSTINSA, TVAI.DATASTOP, TVAI.COEF, TVAI.COEFBAZA, TVAI.COEFTVA, TVAI.TIPSTINGERE, TVAI.PREFIXSTINGERE, TVAI.NRSTINGERE,
    1 - ((S.STINSDOC+S.STINSDINCARETVA)/S.VALDOC) COEFDOC,
    1 - CASE WHEN Coalesce(S.SPLITTVA,0) = 0 THEN ((S.STINSDOC+S.STINSDINCARETVA)/S.VALDOC) WHEN S.TVADOC = 0 THEN 1 ELSE (S.STINSDOC/(S.VALDOC-S.TVADOC)) END COEFDOCBAZA,
    1 - CASE WHEN Coalesce(S.SPLITTVA,0) = 0 THEN ((S.STINSDOC+S.STINSDINCARETVA)/S.VALDOC) WHEN S.TVADOC = 0 THEN 1 ELSE (S.STINSDINCARETVA/S.TVADOC)     END COEFDOCTVA,
    TVAI.ORDDOC, TVAI.COUNTDOC, Coalesce(TVAI.COEFPLATA,0) COEFPLATA, Coalesce(TVAI.COEFPLATABAZA,0) COEFPLATABAZA, Coalesce(TVAI.COEFPLATATVA,0) COEFPLATATVA, ABS(S.VALDOC-S.STINSDOC-S.STINSDINCARETVA) RESTDOC
  FROM S LEFT JOIN TVAI ON TVAI.CODDOC = S.CODINTR AND TVAI.TIPDOC = S.TIPDOC';

  sInsAux2 :=
  'INSERT INTO TMP_LST_TVAINCAS(
    coddoc, tipdoc, nrdoc, prefixdoc, seriadoc, datadoc, datastingere, valstinsa, datastop, coef, coefbaza, coeftva, tipstingere, prefixstingere, nrstingere,
    coefdoc,
    coefdocbaza,
    coefdoctva,
    orddoc, countdoc,
    coefplata,
    coefplatabaza,
    coefplatatva)
  SELECT
    coddoc, tipdoc, nrdoc, prefixdoc, seriadoc, datadoc, datastingere, valstinsa, datastop, coef, coefbaza, coeftva, tipstingere, prefixstingere, nrstingere,
    1 CoefDoc,
    1 CoefDocBaza,
    1 CoefDocTva,
    Row_NUMBER()  OVER (PARTITION BY CODDOC, TIPDOC ORDER BY DATASTINGERE, TIPSTINGERE, NRSTINGERE) OrdDoc, COUNT(1) OVER (PARTITION BY CODDOC, TIPDOC) CountDoc,
    SUM(Coef)     OVER (PARTITION BY CODDOC, TIPDOC ORDER BY DATASTINGERE, TIPSTINGERE, NRSTINGERE ROWS UNBOUNDED PRECEDING) CoefPlata,
    SUM(CoefBaza) OVER (PARTITION BY CODDOC, TIPDOC ORDER BY DATASTINGERE, TIPSTINGERE, NRSTINGERE ROWS UNBOUNDED PRECEDING) CoefPlataBaza,
    SUM(CoefTva)  OVER (PARTITION BY CODDOC, TIPDOC ORDER BY DATASTINGERE, TIPSTINGERE, NRSTINGERE ROWS UNBOUNDED PRECEDING) CoefPlataTva
  FROM TMP_TVAINCAS
  WHERE COEFTVA &lt;&gt; 0 OR SPLITTVA = 1';

  sDebug :=
    'DO LANGUAGE PLPGSQL $$'||Chr(10)||
    'BEGIN'||Chr(10)||
    '  DELETE FROM TMP_LST_TVAINCAS;' || Chr(10)||
    '  DELETE FROM TMP_JURNAL1;' || Chr(10)||
    '  DELETE FROM TMP_TVAINCAS;';

  IF current_setting('PKG_LIST_BASE_JURNCUMP.vAnLista', true)::numeric &gt; 2012 THEN
    sDebug := sDebug|| Chr(10)||
    '  PERFORM PKG_INCHIDERI_MAKE_TMP_StingereTVADed(1::numeric);' || Chr(10)||
    '  DELETE FROM TMP_TVAINCAS T' || Chr(10)||
    '  WHERE 0 = (SELECT Coalesce(Max( Abs(PKG_INCHIDERI_CalcTVADed(I.TipTVA, I1.TVANeded, I.ProRata, I1.TVA))),-1) ' || Chr(10)||
    '  FROM Intrari1 I1, Intrari I WHERE  I.CodIntr = T.CodDoc AND I.TipDoc = T.TipDoc AND I1.CodIntr = I.CodIntr); ' || Chr(10)||
    '  ' || coalesce(sInsAux1,'') || '; ' || Chr(10)||
    '  DELETE FROM TMP_TVAINCAS WHERE CODDOC IN (SELECT CODDOC FROM TMP_LST_TVAINCAS);' || Chr(10)||
    '  DELETE FROM TMP_LST_TVAINCAS WHERE COEFPLATA = 0 AND RESTDOC &lt; 0.01;' || Chr(10)||
    '  ' || coalesce(sInsAux2,'') || ';';
  END IF;

  sDebug := sDebug || Chr(10) ||
    'END $$;';

  PERFORM LIST_EXECUTE_IMMEDIATE(sDebug, aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_jurncump_processlist</obj_name>
  <obj_hashval>29d06552daadbb180635c2e6c432e336</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_jurncump_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC RECORD;
  sInsert         VARCHAR;
  sSelect1        VARCHAR;
  sInsAux1        VARCHAR;
  sUpdate1        VARCHAR;
  sSelect2        VARCHAR;
  sSelect3        VARCHAR;
  sSelect4        VARCHAR;
  sSelect5        VARCHAR;
  sCondLuna       VARCHAR;
  vCodTvaImplicit numeric;
  sPjTva          VARCHAR;
  cModEditJurn    NUMERIC;
  vTVA0FaraJurnal VARCHAR;
  vCountArt       NUMERIC := 0;
  gSuplCols       VARCHAR := '';
  gUserFields     VARCHAR := '';
  gUserAlias      VARCHAR := '';
  gNullAlias      VARCHAR := '';
  gSuplJoins      VARCHAR := '';
  vAnLista        NUMERIC;
  vLunaLista      NUMERIC;
  vTip            NUMERIC;
  vSubunit        NUMERIC;
  sfiltrucodart   VARCHAR;
  sAnLunaIni      VARCHAR;
  sAnLunaFin      VARCHAR;
BEGIN
  --Florin 30.10.2025 - sinc. Oracle
  --Stef   21.10.2025 - sinc. Oracle
  --Florin 17.09.2025 - sinc. Oracle
  --Florin 20.08.2025 - fixat 66453
  --Florin 19.08.2025 - sinc. Oracle
  --Stef   11.08.2024
  CALL create_wm_temps_flag('JURNVANZ');
  gSuplCols := 'INTRARI I, NPART P, NPARTCODFISC CFP, NPARTCODFISC CFD, NSUBUNIT SUB, NAGENDA SDOC, NAGENDA SSOC, NLOCALIT L, NTARI T, DOCCARNETE DC';
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_JURNCUMP.gSuplCols', gSuplCols, false);
  PERFORM pkg_globals_SetSeparator(',');

  CALL PRC_AL_CHECK('nsubunit1',0);
  IF (aLISTID &gt; 0 OR tmpName &lt;&gt; 'TMP_JC_D300') THEN
    vSubunit := getsubunitate();
    BEGIN
      SELECT Coalesce(ModEditareJurnal, 0)
      INTO cModEditJurn
      FROM NSUBUNIT1
      WHERE CodSubunit = vSubunit AND getanlunalucru() BETWEEN ALSTART AND ALSTOP;
    EXCEPTION
      WHEN NO_DATA_FOUND THEN cModEditJurn := 0;
    END;
    cModEditJurn := Coalesce(cModEditJurn,0);
    IF cModEditJurn = 0 THEN
      cModEditJurn := fnc_GetValConstanta('ModEditareJurnal', getanlucru(), getlunalucru())::numeric;
      cModEditJurn := Coalesce(cModEditJurn,0);
    END IF;
    vTip := CASE WHEN cModEditJurn = 2 AND Mod(getlunalucru(),3) = 0 THEN 1 ELSE 0 END;
    PERFORM PKG_LIST_BASE_JURNCUMP_SetPerioada(getanlucru(), getlunalucru(), vTip, vSubunit, 0);
  END IF;

  vCodTvaImplicit := Coalesce(fnc_GetValConstanta('TIPTVAImplicit',     vAnLista,vLunaLista), '0');
  SELECT To_Char(Coalesce(Max(PROCENT),0)) INTO sPjTva FROM NTVA1 WHERE CODTVA = vCodTvaImplicit AND vAnLista*12+vLunaLista BETWEEN ALSTART AND ALSTOP;

  vAnLista        := current_setting('PKG_LIST_BASE_JURNCUMP.vAnLista'  , TRUE)::NUMERIC;
  vLunaLista      := current_setting('PKG_LIST_BASE_JURNCUMP.vLunaLista', TRUE)::NUMERIC;
  sAnLunaIni      := current_setting('PKG_LIST_BASE_JURNCUMP.vAnLunaIni', TRUE);
  sAnLunaFin      := current_setting('PKG_LIST_BASE_JURNCUMP.vAnLunaFin', TRUE);
  vTVA0FaraJurnal := Coalesce(fnc_GetValConstanta('TVA0FaraJurnal', vAnLista, vLunaLista), '-1');
  sPjTva          := Coalesce(fnc_GetValConstanta('TIPTVAImplicit', vAnLista, vLunaLista), '-1');

  perform set_config('PKG_LIST_BASE_JURNCUMP.vISIVB',     Coalesce(fnc_GetValConstanta('InclServInValBunuri', vAnLista, vLunaLista), '-1'), false);
  perform set_config('PKG_LIST_BASE_JURNCUMP.sServAICB' , Coalesce(fnc_GetValConstanta('ServAICB'           , vAnLista, vLunaLista), '-1'), false);
  perform set_config('PKG_LIST_BASE_JURNCUMP.vIMFEStoc' , Coalesce(fnc_GetValConstanta('ImbMiFixEStoc'      , vAnLista, vLunaLista), '-1'), false);
  perform set_config('PKG_LIST_BASE_JURNCUMP.sCImbMifix', Coalesce(fnc_GetValConstanta('CImbMifix'          , vAnLista, vLunaLista), '-1'), false);

  IF vTVA0FaraJurnal &lt;&gt; '-1' THEN
    CALL PRC_AL_CHECK('nart1');

    DELETE FROM TMP_MANEVRA;
    PERFORM LIST_EXECUTE_IMMEDIATE('INSERT INTO TMP_MANEVRA SELECT DISTINCT CodArticol FROM NART1 WHERE CodTva IN (' || coalesce(vTVA0FaraJurnal,'') || ') AND '||sAnLunaFin||' BETWEEN ALSTART AND ALSTOP', aListID, aListVer);

    FOR vRec IN (SELECT CodUnic FROM TMP_MANEVRA) LOOP
      IF  vCountArt = 0 THEN
        sFiltruCodArt := (vrec.CodUnic)::VARCHAR;
      ELSE
        sFiltruCodArt := coalesce(sFiltruCodArt,'') || ',' || coalesce((vrec.CodUnic)::VARCHAR ,'');
      END IF;

      vCountArt := vCountArt + 1;
    END LOOP;

    IF  vCountArt &gt; 0 THEN
      sInsAux1 := sFiltruCodArt;
      sFiltruCodArt := '
        AND NOT o.CodArticol IN (' || coalesce(sFiltruCodArt::VARCHAR ,'') || ')';
    ELSE
      sFiltruCodArt := '';
    END IF;
  END IF;
  perform set_config('PKG_LIST_BASE_JURNCUMP.sFiltruCodArt', sFiltruCodArt,false);

  IF sAnLunaIni = sAnLunaFin THEN
    sCondLuna := '= '||sAnLunaIni;
  ELSE
    sCondLuna := 'BETWEEN '||sAnLunaIni||' AND '||sAnLunaFin;
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(
    NAV_CODDOC, NAV_CodDoc1, NAV_TIPDOC, ORDDOC,
    PREFIXDOC, TIPDOC, NRDOC, NRI, DATADOC, SERIADOC, DEN_PART, CODFISCAL,
    VALDOC, BAZA_MAX, TVA_MAX, BAZA_MIN, TVA_MIN, BAZA_MED, TVA_MED,
    BAZA_REGMAX, TVA_REGMAX, BAZA_REGMIN, TVA_REGMIN,
    BAZA_REG,  TVA_REG, BAZA_REG2, TVA_REG2, BAZA_REG3, TVA_REG3, BAZA_REG4, TVA_REG4, BAZA_REG5, TVA_REG5,
    TVA_0,
    AICB_BAZA,   AICB_TVA,
    AICB_SCUT,   AICB_NEIMP,
    AICS_SCUT,   AICS_NEIMP,
    RS315_BAZA,  RS315_TVA,
    BS150_BAZA,  BS150_TVA,
    BS160_BAZA,  BS160_TVA,
    BS160_BMAX,  BS160_TMAX,
    BS160_BMIN,  BS160_TMIN,
    BS160_BMED,  BS160_TMED,
    BS160_BREG,  BS160_TREG,
    BS160_BREG2, BS160_TREG2,
    BS160_BREG3, BS160_TREG3,
    BS160_BREG4, BS160_TREG4,
    BS160_BREG5, BS160_TREG5,
    PRORATA, TVAN_MAX, TVAN_MIN, TVAN_MED, TVAN_REG, TVAN_REG2, TVAN_REG3, TVAN_REG4, TVAN_REG5, TVANEDED, TVANPRORATA, TVAMPRORATA,
    OBS, SUBUNITATE, UE, TI,
    DATACDOC, OPERATOR, ANDOC, LUNADOC, TVALAINC, TVALAINCF,
    RESTOL, BAZAOBLIG, TVANOBLIG,
    PLATAPREFIX, PLATATIP, PLATANR, PLATADATA,
    PLATAVAL, PLATAVFT, PLATATVA,
    RESTVAL, RESTTVA, SOLDVAL, SOLDTVA,
    DOCVAL, DOCBAZA, DOCTVA,
    TIPTVADOC,
    TVA_RET' || gUserFields || ')';

  sSelect1 := '
  WITH X AS (' || coalesce(pkg_list_base_jurncump_sxintr(sPjTva), '') || '
    AND I.CODINTR NOT IN (SELECT DISTINCT CODDOC FROM TMP_LST_TVAINCAS)
    AND I.AN*12+I.LUNA ' || coalesce(sCondLuna,'') || '),
  JC AS (' || coalesce(pkg_list_base_jurncump_sjcintr(), '') || ')
  SELECT
   I.CODINTR, NULL NAV_CodDoc1, I.TIPDOC, 1 ORDDOC,
    I.PREFIXDOC, PKG_LIST_BASE_UTILS_DECODE_TIPDOC_SCURT(I.TIPDOC) TIPDOC, I.NRDOC, I.NRI, I.DATADOC, Coalesce(I.SERIADOC,DC.SERIE) SERIADOC, P.DEN_PART, COALESCE(CFD.CODFISCAL,SDOC.CODFISCAL,CFP.CODFISCAL) CODFISCAL,
    CASE
      WHEN JC.TVAINC = 0
      THEN I.VALDOC * Coalesce(NULLIf(I.Curs,0),1) + CASE WHEN Coalesce(I.TIPTRANZACTIE, 0) = 2 THEN Coalesce(d.TVADOCVAMA,0) ELSE Coalesce(d.VALSUPLIM,0) + Coalesce(d.VALDOCVAMA,0) END
      ELSE JC.BMAX + JC.TMAX + JC.BMIN + JC.TMIN + JC.BMED + JC.TMED + JC.BREG + JC.TREG + JC.BREG2 + JC.TREG2 + JC.BREG3 + JC.TREG3 + JC.BREG4 + JC.TREG4 + JC.BREG5 + JC.TREG5 + JC.T0
    END VALDOC,
    CASE WHEN JC.DOC_REG = 1 THEN 0 ELSE JC.BMAX END BAZA_MAX, CASE WHEN JC.DOC_REG = 1 THEN 0 ELSE JC.TMAX END TVA_MAX,
    CASE WHEN JC.DOC_REG = 1 THEN 0 ELSE JC.BMIN END BAZA_MIN, CASE WHEN JC.DOC_REG = 1 THEN 0 ELSE JC.TMIN END TVA_MIN,
    JC.BMED BAZA_MED, JC.TMED TVA_MED,
    CASE WHEN JC.DOC_REG = 0 THEN 0 ELSE JC.BMAX END BAZA_REGMAX, CASE WHEN JC.DOC_REG = 0 THEN 0 ELSE JC.TMAX END TVA_REGMAX,
    CASE WHEN JC.DOC_REG = 0 THEN 0 ELSE JC.BMIN END BAZA_REGMIN, CASE WHEN JC.DOC_REG = 0 THEN 0 ELSE JC.TMIN END TVA_REGMIN,
    JC.BREG BAZA_REG, JC.TREG TVA_REG, JC.BREG2 BAZA_REG2, JC.TREG2 TVA_REG2, JC.BREG3 BAZA_REG3, JC.TREG3 TVA_REG3, JC.BREG4 BAZA_REG4, JC.TREG4 TVA_REG4, JC.BREG5 BAZA_REG5, JC.TREG5 TVA_REG5, JC.T0 TVA_0,
    CASE WHEN JC.TVAINC = 0 THEN JC.AICB_BAZA   END AICB_BAZA,   CASE WHEN JC.TVAINC = 0 THEN JC.AICB_TVA    END AICB_TVA,
    CASE WHEN JC.TVAINC = 0 THEN JC.AICB_SCUT   END AICB_SCUT,   CASE WHEN JC.TVAINC = 0 THEN JC.AICB_NEIMP  END AICB_NEIMP,
    CASE WHEN JC.TVAINC = 0 THEN JC.AICS_SCUT   END AICS_SCUT,   CASE WHEN JC.TVAINC = 0 THEN JC.AICS_NEIMP  END AICS_NEIMP,
    CASE WHEN JC.TVAINC = 0 THEN JC.RS315_BAZA  END RS315_BAZA,  CASE WHEN JC.TVAINC = 0 THEN JC.RS315_TVA   END RS315_TVA,
    CASE WHEN JC.TVAINC = 0 THEN JC.BS150_BAZA  END BS150_BAZA,  CASE WHEN JC.TVAINC = 0 THEN JC.BS150_TVA   END BS150_TVA,
    CASE WHEN JC.TVAINC = 0 THEN JC.BS160_BAZA  END BS160_BAZA,  CASE WHEN JC.TVAINC = 0 THEN JC.BS160_TVA   END BS160_TVA,
    CASE WHEN JC.TVAINC = 0 THEN JC.BS160_BMAX  END BS160_BMAX,  CASE WHEN JC.TVAINC = 0 THEN JC.BS160_TMAX  END BS160_TMAX,
    CASE WHEN JC.TVAINC = 0 THEN JC.BS160_BMIN  END BS160_BMIN,  CASE WHEN JC.TVAINC = 0 THEN JC.BS160_TMIN  END BS160_TMIN,
    CASE WHEN JC.TVAINC = 0 THEN JC.BS160_BMED  END BS160_BMED,  CASE WHEN JC.TVAINC = 0 THEN JC.BS160_TMED  END BS160_TMED,
    CASE WHEN JC.TVAINC = 0 THEN JC.BS160_BREG  END BS160_BREG,  CASE WHEN JC.TVAINC = 0 THEN JC.BS160_TREG  END BS160_TREG,
    CASE WHEN JC.TVAINC = 0 THEN JC.BS160_BREG2 END BS160_BREG2, CASE WHEN JC.TVAINC = 0 THEN JC.BS160_TREG2 END BS160_TREG2,
    CASE WHEN JC.TVAINC = 0 THEN JC.BS160_BREG3 END BS160_BREG3, CASE WHEN JC.TVAINC = 0 THEN JC.BS160_TREG3 END BS160_TREG3,
    CASE WHEN JC.TVAINC = 0 THEN JC.BS160_BREG4 END BS160_BREG4, CASE WHEN JC.TVAINC = 0 THEN JC.BS160_TREG4 END BS160_TREG4,
    CASE WHEN JC.TVAINC = 0 THEN JC.BS160_BREG5 END BS160_BREG5, CASE WHEN JC.TVAINC = 0 THEN JC.BS160_TREG5 END BS160_TREG5,
    JC.PRORATA, JC.TNMAX TVAN_MAX, JC.TNMIN TVAN_MIN, JC.TNMED TVAN_MED, JC.TNREG TVAN_REG, JC.TNREG2 TVAN_REG2, JC.TNREG3 TVAN_REG3, JC.TNREG4 TVAN_REG4, JC.TNREG5 TVAN_REG5,
    JC.TNEDED TVANEDED, JC.TNPRORATA TVANPRORATA, JC.TMPRORATA TVAMPRORATA,
    I.OBS, SUB.DEN_SUBUNIT SUBUNITATE, CASE WHEN t.statcomunitar = 1 THEN ''DA'' ELSE ''NU'' END UE, CASE WHEN jc.tiptva = 2 THEN ''DA'' ELSE ''NU'' END TI,
    I.DATACREARE, UT.USERNAME, I.AN, I.LUNA, CASE WHEN JC.TVAINC = 1 THEN ''DA'' ELSE ''NU'' END TVALAINC, CASE WHEN I.TVAINCASARE_F = 1 THEN ''DA'' ELSE ''NU'' END TVALAINCF,
    CASE WHEN JC.TVAINC = 1 THEN JC.BAZAX+JC.TVAX END RESTOL, CASE WHEN JC.TVAINC = 1 THEN JC.BAZAX END BAZAOBLIG, CASE WHEN JC.TVAINC = 1 THEN JC.TVAX END TVANOBLIG,
    NULL PLATAPREFIX, NULL PLATATIP, NULL PLATANR, NULL PLATADATA,
    NULL PLATAVAL, NULL PLATAVFT, NULL PLATATVA,
    CASE WHEN JC.TVAINC = 1 THEN JC.BAZAX+JC.TVAX END RESTVAL, CASE WHEN JC.TVAINC = 1 THEN JC.TVAX END RESTTVA,
    CASE WHEN JC.TVAINC = 1 THEN JC.BAZAX+JC.TVAX END SOLDVAL, CASE WHEN JC.TVAINC = 1 THEN JC.TVAX END SOLDTVA,
    I.VALDOC * Coalesce(NULLIf(I.Curs,0),1) DOCVAL, (I.VALDOC-I.TVADOC) * Coalesce(NULLIf(I.Curs,0),1) DOCBAZA, I.TVADOC * Coalesce(NULLIf(I.Curs,0),1) DOCTVA,
    CASE i.tiptva WHEN 1 THEN ''Taxare normala'' WHEN 2 THEN ''Taxare inversa'' WHEN 3 THEN ''Tranzactie triunghiulara'' WHEN 4 THEN ''Suspendare temporara'' END TIPTVADOC,
    0 TVA_RET ' || gUserAlias || '
  FROM JC
    INNER JOIN INTRARI I        ON I.CODINTR         = JC.CODINTR
    LEFT JOIN NPART P           ON P.CODPART         = I.PARTENER
    LEFT JOIN NPARTCODFISC CFP  ON CFP.CODPART       = I.PARTENER AND CFP.PRINCIPAL = 1
    LEFT JOIN NPARTCODFISC CFD  ON CFD.COD_CODFISCAL = I.CODFISCAL
    LEFT JOIN DVI D             ON D.CODINTR         = JC.CODINTR
    LEFT JOIN NSUBUNIT SUB      ON SUB.CODSUBUNIT    = I.SUBUNITATEA
    LEFT JOIN NAGENDA SDOC      ON SDOC.CODAGENDA    = I.CODLOCATIE
    LEFT JOIN NAGENDA SSOC      ON SSOC.CODPART      = I.PARTENER AND Coalesce(SSOC.INACTIV,0) = 0 AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND SSOC.TIP = 0
    LEFT JOIN NLOCALIT L        ON L.CODLOCALIT      = Coalesce(SDOC.CODLOCALIT, SSOC.CODLOCALIT)
    LEFT JOIN NTARI T           ON T.CODTARA         = Coalesce(L.CODTARA, 0)
    LEFT JOIN DOCCARNETE DC     ON DC.CODCARNET      = I.CARNETDOC
    LEFT JOIN TMP_UTILIZATOR UT ON UT.CODUTILIZATOR  = I.USERID' || gSuplJoins;

  sInsAux1 := 'INSERT INTO TMP_JC_AUX1
  SELECT t.nav_coddoc, t.nav_tipdoc, (i.valdoc-Sum(I1.CANT*I1.PRETORIG*I1.COEFDISCMAJ))/i.valdoc
  FROM ' || tmpName || ' t
    INNER JOIN intrari  i  ON i.codintr   = t.nav_coddoc and i.tipdoc = t.nav_tipdoc
    INNER JOIN intrari1 i1 ON i1.codintr  = i.codintr
    INNER JOIN nartobj  o  ON o.codobiect = i1.codobiect
  WHERE i.valdoc &lt;&gt; 0
    AND o.codarticol IN (' || coalesce(sInsAux1,'') || ')
  GROUP BY t.nav_coddoc, t.nav_tipdoc, i.valdoc';

  sUpdate1 := 'UPDATE ' || tmpName || ' t SET valdoc = t.valdoc* Coalesce((SELECT a.coefdoc FROM TMP_JC_AUX1 a WHERE a.nav_coddoc = t.nav_coddoc AND a.nav_tipdoc = t.nav_tipdoc),1)';

  sSelect2 := '
  WITH X AS (
    SELECT
      t1.codtrezor1, t1.codtrezor, g.tipdoc, g.semnificatie, Coalesce(t1.codpart,0) codpart, o.icont, CASE g.semnificatie WHEN 900 THEN o.icont ELSE Coalesce(t1.codpart,0) END destinatie,
      t1.doc, t1.nrdoc, t1.datadoc, t1.carnetdoc, t1.seriedoc seriadoc, t1.obs,
      CASE WHEN Coalesce(o.valoare - g.tva,0) = 0 THEN ' || coalesce(sPjTva, '') || ' ELSE g.tva*100/(o.valoare - g.tva) END PJTVA, '
       ||sAnLunaIni||' ALTVA,
      (o.valoare - Coalesce(g.tva,0)) * Coalesce(NullIF(g.curs,0),1) * CASE WHEN g.semnificatie IN (320,430) THEN -1 ELSE 1 END baza ,
      g.tva * Coalesce(NullIF(g.curs,0),1) * CASE WHEN g.semnificatie IN (320,430) THEN -1 ELSE 1 END tva ,
      o.valoare * Coalesce(NullIF(g.curs,0),1) * CASE WHEN g.semnificatie IN (320,430) THEN -1 ELSE 1 END val,
      t.subunitatea, t.datacreare, Coalesce(o.tvaneded,0) tvaneded, t.userid, t.an, t.luna,
      t1.valdoc*Coalesce(NullIF(g.curs,0),1) DOCVAL,
      0 TVA_RET
    FROM trezor1 t1
      INNER JOIN trezor   t  ON t.codtrezor       = t1.codtrezor
      INNER JOIN general  g  ON g.coddoc          = t1.codtrezor1 AND g.tipdoc IN (29,30,33)
      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 T1.AN*12+T1.LUNA ' || coalesce(sCondLuna, '') || '
      AND ((G.SEMNIFICATIE = 900) OR ((Coalesce(G.TVA,0) &lt;&gt; 0 ) AND ((G.SEMNIFICATIE IN (310,430,700)) OR (G.SEMNIFICATIE = 320 AND OS.SEMNIFICATIE &lt;&gt; 330) OR (G.SEMNIFICATIE = 420 AND OS.SEMNIFICATIE = 430)))) ' ||
        coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'T', NULL, NULL, getsubunitate())),'') || '
    UNION ALL
    SELECT
      t1.codtrezor1, t1.codtrezor, g.tipdoc, g.semnificatie, Coalesce(t1.codpart,0) codpart, o.icont, o.icont destinatie,
      t1.doc, t1.nrdoc, t1.datadoc, t1.carnetdoc, t1.seriedoc seriadoc, t1.obs,
      0 PJTVA, '||sAnLunaIni||' ALTVA,
      0 baza ,
      0 tva ,
      o.valoare * Coalesce(g.curs,1) val,
      t.subunitatea, t.datacreare, Coalesce(o.tvaneded,0) tvaneded, t.userid, t.an, t.luna,
      t1.valdoc*Coalesce(NullIF(g.curs,0),1) DOCVAL, o.valoare * Coalesce(NullIF(g.curs,0),1) TVA_RET
    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 ostins ON ostins.codobligpif = s.codstinspif
    WHERE T.OPERAT = 1 AND T1.ANULAT = 0  ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'T', NULL, NULL, getsubunitate())), '') || '
      AND T.AN*12+T.LUNA ' || coalesce(sCondLuna,'') || '
      AND O.SEMNIFICATIE = 950 AND T1.OBIECTTRANZ IN (4,5) AND G.FARAREG = 1
  ),
  JC_TREZ AS (
    SELECT
      codtrezor1, codtrezor, tipdoc, 1 tiptva, 0 codlocatie, semnificatie, codpart, icont, doc, nrdoc, datadoc, carnetdoc, seriadoc, obs,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 3 THEN BAZA ELSE 0 END) BMAX,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 3 THEN TVA  ELSE 0 END) TMAX,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 2 THEN BAZA ELSE 0 END) BMIN,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 2 THEN TVA  ELSE 0 END) TMIN,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 1 THEN BAZA ELSE 0 END) BMED,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 1 THEN TVA  ELSE 0 END) TMED,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 4 THEN BAZA ELSE 0 END) BREG,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 4 THEN TVA  ELSE 0 END) TREG,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 5 THEN BAZA ELSE 0 END) BREG2,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 5 THEN TVA  ELSE 0 END) TREG2,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 6 THEN BAZA ELSE 0 END) BREG3,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 6 THEN TVA  ELSE 0 END) TREG3,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 7 THEN BAZA ELSE 0 END) BREG4,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 7 THEN TVA  ELSE 0 END) TREG4,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 8 THEN BAZA ELSE 0 END) BREG5,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 8 THEN TVA  ELSE 0 END) TREG5,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 0 THEN BAZA ELSE 0 END) T0,
      SUM (VAL) VALDOC,
      0 AICB_BAZA, 0 AICB_TVA, 0 AICB_SCUT, 0 AICB_NEIMP, 0 AICS_SCUT, 0 AICS_NEIMP,
      0 RS315_BAZA, 0 RS315_TVA, 0 BS150_BAZA, 0 BS150_TVA, 0 BS160_BAZA, 0 BS160_TVA, 0 BS160_BMAX, 0 BS160_TMAX, 0 BS160_BMIN, 0 BS160_TMIN, 0 BS160_BMED, 0 BS160_TMED,
      0 BS160_BREG, 0 BS160_TREG, 0 BS160_BREG2, 0 BS160_TREG2, 0 BS160_BREG3, 0 BS160_TREG3, 0 BS160_BREG4, 0 BS160_TREG4, 0 BS160_BREG5, 0 BS160_TREG5,
      0 PRORATA, SUM(CASE WHEN TVANEDED = 2 THEN TVA ELSE 0 END) TVANPRORATA, 0 TVAMPRORATA,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 3 THEN CASE TVANEDED WHEN 1 THEN TVA WHEN 3 THEN TVA/2 ELSE 0 END  ELSE 0 END) TVANMAX,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 2 THEN CASE TVANEDED WHEN 1 THEN TVA WHEN 3 THEN TVA/2 ELSE 0 END  ELSE 0 END) TVANMIN,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 1 THEN CASE TVANEDED WHEN 1 THEN TVA WHEN 3 THEN TVA/2 ELSE 0 END  ELSE 0 END) TVANMED,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 4 THEN CASE TVANEDED WHEN 1 THEN TVA WHEN 3 THEN TVA/2 ELSE 0 END  ELSE 0 END) TVANREG,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 5 THEN CASE TVANEDED WHEN 1 THEN TVA WHEN 3 THEN TVA/2 ELSE 0 END  ELSE 0 END) TVANREG2,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 6 THEN CASE TVANEDED WHEN 1 THEN TVA WHEN 3 THEN TVA/2 ELSE 0 END  ELSE 0 END) TVANREG3,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 7 THEN CASE TVANEDED WHEN 1 THEN TVA WHEN 3 THEN TVA/2 ELSE 0 END  ELSE 0 END) TVANREG4,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 8 THEN CASE TVANEDED WHEN 1 THEN TVA WHEN 3 THEN TVA/2 ELSE 0 END  ELSE 0 END) TVANREG5,
      SUM(CASE TVANEDED WHEN 1 THEN TVA WHEN 3 THEN TVA/2 ELSE 0 END) TVANEDED,

      SUBUNITATEA, DATACREARE, USERID, AN, LUNA,
      DOCVAL, SUM (BAZA) DOCBAZA, SUM (TVA) DOCTVA,
      SUM(TVA_RET) TVA_RET
    FROM X
    GROUP BY codtrezor1, codtrezor, tipdoc, semnificatie, codpart, icont, doc, nrdoc, datadoc, carnetdoc, seriadoc, obs, subunitatea, datacreare, userid, an, luna, docval
  )
  SELECT
    jc.codtrezor NAV_CodDoc, jc.codtrezor1 NAV_CodDoc1, jc.tipdoc NAV_TipDoc, 1 ORDDOC,
    jc.doc, PKG_LIST_BASE_UTILS_DECODE_TIPDOC_SCURT(JC.TIPDOC) TIPDOC, jc.nrdoc, null NRI, jc.datadoc, Coalesce(jc.seriadoc,dc.serie) SERIADOC,
    CASE
      WHEN jc.codpart &lt;&gt; 0 THEN p.den_part
      WHEN jc.semnificatie = 900 AND jc.obs LIKE ''%/%'' THEN SUBSTR(jc.OBS,1, LEAST(INSTR(jc.OBS,''/'')-1,197-length(nc.den_cont))) || '' / '' ||nc.den_cont
      WHEN jc.semnificatie = 900 THEN nc.den_cont
      ELSE p.den_part
    END DEN_PART,
    CASE
      WHEN jc.TIPDOC IN (29,33) AND jc.obs LIKE ''%/%'' AND INSTR(jc.OBS,''/'',1,2) = 0 THEN SUBSTR(jc.OBS,INSTR(jc.OBS,''/'')+1,100)
      WHEN jc.TIPDOC IN (29,33) AND jc.obs LIKE ''%/%'' THEN SUBSTR(jc.OBS,INSTR(jc.OBS,''/'')+1,Least(INSTR(jc.OBS,''/'',1,2)-INSTR(jc.OBS,''/'')-1, 100))
      ELSE cfp.codfiscal
    END CODFISCAL,
    JC.VALDOC,
    JC.BMAX BAZA_MAX, JC.TMAX TVA_MAX, JC.BMIN BAZA_MIN, JC.TMIN TVA_MIN, JC.BMED BAZA_MED, JC.TMED TVA_MED,
    0 BAZA_REGMAX, 0 TVA_REGMAX, 0 BAZA_REGMIN, 0 TVA_REGMIN,
    JC.BREG BAZA_REG, JC.TREG TVA_REG, JC.BREG2 BAZA_REG2, JC.TREG2 TVA_REG2, JC.BREG3 BAZA_REG3, JC.TREG3 TVA_REG3, JC.BREG4 BAZA_REG4, JC.TREG4 TVA_REG4, JC.BREG5 BAZA_REG5, JC.TREG5 TVA_REG5, JC.T0 TVA_0,
    JC.AICB_BAZA, JC.AICB_TVA, JC.AICB_SCUT, JC.AICB_NEIMP, 0 AICS_SCUT, 0 AICS_NEIMP,
    JC.RS315_BAZA,  JC.RS315_TVA,
    JC.BS150_BAZA,  JC.BS150_TVA,
    JC.BS160_BAZA,  JC.BS160_TVA,
    JC.BS160_BMAX,  JC.BS160_TMAX,
    JC.BS160_BMIN,  JC.BS160_TMIN,
    JC.BS160_BMED,  JC.BS160_TMED,
    JC.BS160_BREG,  JC.BS160_TREG,
    JC.BS160_BREG2, JC.BS160_TREG2,
    JC.BS160_BREG3, JC.BS160_TREG3,
    JC.BS160_BREG4, JC.BS160_TREG4,
    JC.BS160_BREG5, JC.BS160_TREG5,
    JC.PRORATA, JC.TVANMAX, JC.TVANMIN, JC.TVANMED, JC.TVANREG, JC.TVANREG2, JC.TVANREG3, JC.TVANREG4, JC.TVANREG5, JC.TVANEDED, JC.TVANPRORATA, JC.TVAMPRORATA,
    JC.OBS, SUB.DEN_SUBUNIT SUBUNITATE, CASE WHEN t.statcomunitar = 1 THEN ''DA'' ELSE ''NU'' END UE, CASE WHEN jc.tiptva = 2 THEN ''DA'' ELSE ''NU'' END TI,
    JC.DATACREARE, UT.USERNAME, JC.AN, JC.LUNA, ''NU'' TVALAINC, ''NU'' TVALAINCF,
    NULL RESTOL, NULL BAZAOBLIG, NULL TVANOBLIG,NULL PLATAPREFIX, NULL PLATATIP, NULL PLATANR, NULL PLATADATA,
    NULL PLATAVAL, NULL PLATAVFT, NULL PLATATVA,
    NULL RESTVAL, NULL RESTTVA, NULL SOLDVAL, NULL SOLDTVA,
    JC.DOCVAL, JC.DOCBAZA, JC.DOCTVA,
    NULL TIPTVADOC,
    JC.TVA_RET ' || gUserAlias || '
  FROM JC_TREZ jc
    LEFT JOIN INTRARI I         ON I.CODINTR         = jc.codtrezor - jc.codtrezor
    LEFT JOIN NCONT NC          ON NC.CODCONT        = JC.ICONT AND JC.SEMNIFICATIE = 900
    LEFT JOIN NPART P           ON P.CODPART         = JC.CODPART
    LEFT JOIN NPARTCODFISC CFP  ON CFP.CODPART       = P.CODPART AND CFP.PRINCIPAL = 1
    LEFT JOIN NPARTCODFISC CFD  ON CFD.COD_CODFISCAL = CFP.COD_CODFISCAL
    LEFT JOIN NSUBUNIT SUB      ON SUB.CODSUBUNIT    = JC.SUBUNITATEA
    LEFT JOIN NAGENDA SDOC      ON SDOC.CODAGENDA    = JC.CODLOCATIE
    LEFT JOIN NAGENDA SSOC      ON SSOC.CODPART      = P.CODPART  AND Coalesce(SSOC.INACTIV,0) = 0 AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND SSOC.TIP = 0
    LEFT JOIN NLOCALIT L        ON L.CODLOCALIT      = SSOC.CODLOCALIT
    LEFT JOIN NTARI T           ON T.CODTARA         = Coalesce(L.CODTARA, 0)
    LEFT JOIN DOCCARNETE DC     ON DC.CODCARNET      = JC.CARNETDOC
    LEFT JOIN TMP_UTILIZATOR UT ON UT.CODUTILIZATOR  = JC.USERID' || gSuplJoins;

  sSelect3 := '
  WITH X AS (
    SELECT
      NC.CODNC, NC.NRDOC, NC.DATADOC, NC.CARNETDOC, NC.TIPTRANZ, NC.TIPTVA, NC.SUBUNITATEA, NC.DATACREARE, NC.USERID, NC.AN, NC.LUNA, NC.OBS, NC.VALOARE DOCVAL,
      COALESCE(
        CASE WHEN NC.TIPTVA = 2 THEN NULL ELSE Coalesce(NULLIF(NC.PART,0),NC1.CODPART,0) END,
        Max(Coalesce(NULLIF(NC.PART,0),NC1.CODPART,0))
      ) PART,
      SUM(NC1.VALOARE) * Coalesce(NullIF(nc.curs,0),1) VALOARE,
      SUM(CASE WHEN NC1.TIPLINIETVA = 1 THEN NC1.VALOARE ELSE 0 END) * Coalesce(NullIF(nc.curs,0),1) BAZA_X,
      CASE
        WHEN NC.TIPTVA = 2 AND Coalesce(NC.TIPTRANZ,1) = 1 THEN ''BS160''
        WHEN NC.TIPTRANZ = 2 THEN ''AICB''
        ELSE ''N0''
      END CAZ_X,
      SUM(CASE WHEN NC1.TIPLINIETVA = 2 THEN NC1.VALOARE ELSE 0 END) * Coalesce(NullIF(nc.curs,0),1) BAZA_STOC,
      SUM(CASE WHEN NC1.TIPLINIETVA = 3 THEN NC1.VALOARE ELSE 0 END) * Coalesce(NullIF(nc.curs,0),1) TVA_STOC,
      '||sAnLunaIni||' ALTVA,
      CASE
        WHEN NC.TIPTVA = 2 AND Coalesce(NC.TIPTRANZ,1) = 1 THEN ''BS160''
        WHEN NC.TIPTRANZ = 2 THEN ''AICB''
        WHEN SUM(CASE WHEN NC1.TIPLINIETVA = 2 THEN NC1.VALOARE ELSE 0 END) = 0 OR SUM(CASE WHEN NC1.TIPLINIETVA = 3 THEN NC1.VALOARE ELSE 0 END) = 0 THEN ''N0''
        ELSE ''NTVA''
      END CAZ_STOC,
      SUM(CASE WHEN NC1.TIPLINIETVA = 4 THEN NC1.VALOARE ELSE 0 END) * Coalesce(NullIF(nc.curs,0),1) BAZA_SERV,
      SUM(CASE WHEN NC1.TIPLINIETVA = 5 THEN NC1.VALOARE ELSE 0 END) * Coalesce(NullIF(nc.curs,0),1) TVA_SERV,
      CASE
        WHEN NC.TIPTVA = 2 AND NC.TIPTRANZ IN (2,3) THEN ''BS150''
        WHEN NC.TIPTVA = 1 AND NC.TIPTRANZ = 2 THEN ''BS150''
        WHEN NC.TIPTVA = 1 AND NC.TIPTRANZ = 3 THEN ''N0''
        WHEN SUM(CASE WHEN NC1.TIPLINIETVA = 4 THEN NC1.VALOARE ELSE 0 END) =0 OR SUM(CASE WHEN NC1.TIPLINIETVA = 5 THEN NC1.VALOARE ELSE 0 END) = 0 THEN ''N0''
        ELSE ''NTVA''
      END CAZ_SERV,
      SUM(CASE WHEN NC1.TIPLINIETVA = 6 THEN NC1.VALOARE ELSE 0 END) * Coalesce(NullIF(nc.curs,0),1) BAZA_SCUTIT
    FROM NC INNER JOIN NC1 ON NC1.CODNC = NC.CODNC
    WHERE NC.AN*12+NC.LUNA ' || coalesce(sCondLuna,'') || '
      AND NC.JURNALTVA = 2 AND NC.TIPTVA IN (1,2)
      AND NC1.TIPLINIETVA BETWEEN 2 AND 6 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NC', NULL, NULL, getsubunitate())),'') || '
    GROUP BY
      NC.CODNC, NC.NRDOC, NC.DATADOC, NC.CARNETDOC, NC.TIPTRANZ, NC.TIPTVA, NC.SUBUNITATEA, NC.DATACREARE, NC.USERID, NC.AN, NC.LUNA, NC.OBS, NC.VALOARE, NC.CURS,
      CASE WHEN NC.TIPTVA = 2 THEN NULL ELSE Coalesce(NULLIF(NC.PART,0),NC1.CODPART,0) END
  ),
  JC_NC AS (
    SELECT
      CODNC, TIPTVA, NRDOC, 0 CODLOCATIE, DATADOC, CARNETDOC, PART, VALOARE, OBS,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 3 THEN BAZA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 3 THEN BAZA_SERV ELSE 0 END
      BMAX,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 3 THEN TVA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 3 THEN TVA_SERV ELSE 0 END
      TMAX,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 2 THEN BAZA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 2 THEN BAZA_SERV ELSE 0 END
      BMIN,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 2 THEN TVA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 2 THEN TVA_SERV ELSE 0 END
      TMIN,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 1 THEN BAZA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 1 THEN BAZA_SERV ELSE 0 END
      BMED,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 1 THEN TVA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 1 THEN TVA_SERV ELSE 0 END
      TMED,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 4 THEN BAZA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 4 THEN BAZA_SERV ELSE 0 END
      BREG,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 4 THEN TVA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 4 THEN TVA_SERV ELSE 0 END
      TREG,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 5 THEN BAZA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 5 THEN BAZA_SERV ELSE 0 END
      BREG2,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 5 THEN TVA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 5 THEN TVA_SERV ELSE 0 END
      TREG2,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 6 THEN BAZA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 6 THEN BAZA_SERV ELSE 0 END
      BREG3,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 6 THEN TVA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 6 THEN TVA_SERV ELSE 0 END
      TREG3,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 7 THEN BAZA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 7 THEN BAZA_SERV ELSE 0 END
      BREG4,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 7 THEN TVA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 7 THEN TVA_SERV ELSE 0 END
      TREG4,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 8 THEN BAZA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 8 THEN BAZA_SERV ELSE 0 END
      BREG5,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 8 THEN TVA_STOC ELSE 0 END +
      CASE WHEN CAZ_SERV = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 8 THEN TVA_SERV ELSE 0 END
      TREG5,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''N0'' OR (CAZ_STOC = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 0) THEN BAZA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''N0'' OR (CAZ_SERV = ''NTVA'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 0) THEN BAZA_SERV ELSE 0 END +
      CASE WHEN CAZ_X    = ''N0'' THEN BAZA_X ELSE 0 END +
      BAZA_SCUTIT
      T0,
      CASE WHEN CAZ_STOC = ''AICB''  THEN BAZA_STOC ELSE 0 END + CASE WHEN CAZ_X = ''AICB''  THEN BAZA_X ELSE 0 END AICB_BAZA,
      CASE WHEN CAZ_STOC = ''AICB''  THEN TVA_STOC  ELSE 0 END AICB_TVA,
      0 AICB_SCUT, 0 AICB_NEIMP, 0 AICS_SCUT, 0 AICS_NEIMP,
      0 RS315_BAZA, 0 RS315_TVA,
      CASE WHEN CAZ_SERV = ''BS150'' THEN BAZA_SERV ELSE 0 END BS150_BAZA,
      CASE WHEN CAZ_SERV = ''BS150'' THEN TVA_SERV  ELSE 0 END BS150_TVA,
      CASE WHEN CAZ_STOC = ''BS160'' THEN BAZA_STOC ELSE 0 END +
      CASE WHEN CAZ_SERV = ''BS160'' THEN BAZA_SERV ELSE 0 END +
      CASE WHEN CAZ_X    = ''BS160'' THEN BAZA_X ELSE 0 END
      BS160_BAZA,
      CASE WHEN CAZ_STOC = ''BS160'' THEN TVA_STOC  ELSE 0 END +
      CASE WHEN CAZ_SERV = ''BS160'' THEN TVA_SERV  ELSE 0 END
      BS160_TVA,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 3 THEN BAZA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 3 THEN BAZA_SERV ELSE 0 END
      BS160_BMAX,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 3 THEN TVA_STOC  ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 3 THEN TVA_SERV  ELSE 0 END
      BS160_TMAX,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 2 THEN BAZA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 2 THEN BAZA_SERV ELSE 0 END
      BS160_BMIN,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 2 THEN TVA_STOC  ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 2 THEN TVA_SERV  ELSE 0 END
      BS160_TMIN,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 1 THEN BAZA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 1 THEN BAZA_SERV ELSE 0 END
      BS160_BMED,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 1 THEN TVA_STOC  ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 1 THEN TVA_SERV  ELSE 0 END
      BS160_TMED,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 4 THEN BAZA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 4 THEN BAZA_SERV ELSE 0 END
      BS160_BREG,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 4 THEN TVA_STOC  ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 4 THEN TVA_SERV  ELSE 0 END
      BS160_TREG,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 5 THEN BAZA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 5 THEN BAZA_SERV ELSE 0 END
      BS160_BREG2,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 5 THEN TVA_STOC  ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 5 THEN TVA_SERV  ELSE 0 END
      BS160_TREG2,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 6 THEN BAZA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 6 THEN BAZA_SERV ELSE 0 END
      BS160_BREG3,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 6 THEN TVA_STOC  ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 6 THEN TVA_SERV  ELSE 0 END
      BS160_TREG3,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 7 THEN BAZA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 7 THEN BAZA_SERV ELSE 0 END
      BS160_BREG4,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 7 THEN TVA_STOC  ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 7 THEN TVA_SERV  ELSE 0 END
      BS160_TREG4,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 8 THEN BAZA_STOC ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 8 THEN BAZA_SERV ELSE 0 END
      BS160_BREG5,
      CASE WHEN BAZA_STOC = 0 THEN 0 WHEN CAZ_STOC = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_STOC*100/BAZA_STOC,ALTVA) = 8 THEN TVA_STOC  ELSE 0 END +
      CASE WHEN BAZA_SERV = 0 THEN 0 WHEN CAZ_SERV = ''BS160'' AND PKG_LIST_BASE_UTILS_MATCH_TVA(TVA_SERV*100/BAZA_SERV,ALTVA) = 8 THEN TVA_SERV  ELSE 0 END
      BS160_TREG5,
      SUBUNITATEA, DATACREARE, USERID, AN, LUNA,
      DOCVAL, (BAZA_STOC+BAZA_SERV) DOCBAZA, (TVA_STOC+TVA_SERV ) DOCTVA
    FROM x)
  SELECT
    jc.CODNC NAV_CodDoc, NULL NAV_CodDoc1, 35 NAV_TipDoc, 1 ORDDOC,
    ''NC'' PREFIXDOC, PKG_LIST_BASE_UTILS_DECODE_TIPDOC_SCURT(35) TIPDOC, jc.nrdoc, NULL NRI, jc.datadoc, dc.serie, p.den_part, cfp.codfiscal,
    jc.valoare VALDOC,
    JC.BMAX BAZA_MAX, JC.TMAX TVA_MAX, JC.BMIN BAZA_MIN, JC.TMIN TVA_MIN, JC.BMED BAZA_MED, JC.TMED TVA_MED,
    0 BAZA_REGMAX, 0 TVA_REGMAX, 0 BAZA_REGMIN, 0 TVA_REGMIN,
    JC.BREG BAZA_REG, JC.TREG TVA_REG, JC.BREG2 BAZA_REG2, JC.TREG2 TVA_REG2, JC.BREG3 BAZA_REG3, JC.TREG3 TVA_REG3, JC.BREG4 BAZA_REG4, JC.TREG4 TVA_REG4, JC.BREG5 BAZA_REG5, JC.TREG5 TVA_REG5, JC.T0 TVA_0,
    JC.AICB_BAZA, JC.AICB_TVA, JC.AICB_SCUT, JC.AICB_NEIMP, JC.AICS_SCUT, JC.AICS_NEIMP,
    JC.RS315_BAZA,  JC.RS315_TVA,
    JC.BS150_BAZA,  JC.BS150_TVA,
    JC.BS160_BAZA,  JC.BS160_TVA,
    JC.BS160_BMAX,  JC.BS160_TMAX,
    JC.BS160_BMIN,  JC.BS160_TMIN,
    JC.BS160_BMED,  JC.BS160_TMED,
    JC.BS160_BREG,  JC.BS160_TREG,
    JC.BS160_BREG2, JC.BS160_TREG2,
    JC.BS160_BREG3, JC.BS160_TREG3,
    JC.BS160_BREG4, JC.BS160_TREG4,
    JC.BS160_BREG5, JC.BS160_TREG5,
    0 PRORATA, 0 TVANMAX, 0 TVANMIN, 0 TVANMED, 0 TVANREG, 0 TVANREG2, 0 TVANREG3, 0 TVANREG4, 0 TVANREG5, 0 TVANEDED, 0 TVANPRORATA, 0 TVAMPRORATA,
    JC.OBS, SUB.DEN_SUBUNIT, CASE WHEN t.statcomunitar = 1 THEN ''DA'' ELSE ''NU'' END UE, CASE WHEN jc.tiptva = 2 THEN ''DA'' ELSE ''NU'' END TI,
    JC.DATACREARE, UT.USERNAME, JC.AN, JC.LUNA, ''NU'' TVALAINC, ''NU'' TVALAINCF,
    NULL RESTOL, NULL BAZAOBLIG, NULL TVANOBLIG,
    NULL PLATAPREFIX, NULL PLATATIP, NULL PLATANR, NULL PLATADATA,
    NULL PLATAVAL, NULL PLATAVFT, NULL PLATATVA,
    NULL RESTVAL, NULL RESTTVA, NULL SOLDVAL, NULL SOLDTVA,
    JC.DOCVAL, JC.DOCBAZA, JC.DOCTVA,
    NULL TIPTVADOC,
    0 TVA_RET' || gUserAlias || '
  FROM JC_NC jc
    LEFT JOIN INTRARI I         ON I.CODINTR         = jc.codnc - jc.codnc
    LEFT JOIN NPART P           ON P.CODPART         = JC.PART
    LEFT JOIN NPARTCODFISC CFP  ON CFP.CODPART       = JC.PART AND CFP.PRINCIPAL = 1
    LEFT JOIN NPARTCODFISC CFD  ON CFD.COD_CODFISCAL = CFP.COD_CODFISCAL
    LEFT JOIN NSUBUNIT SUB      ON SUB.CODSUBUNIT    = JC.SUBUNITATEA
    LEFT JOIN NAGENDA SDOC      ON SDOC.CODAGENDA    = JC.CODLOCATIE
    LEFT JOIN NAGENDA SSOC      ON SSOC.CODPART      = JC.PART AND Coalesce(SSOC.INACTIV,0) = 0 AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND SSOC.TIP = 0
    LEFT JOIN NLOCALIT L        ON L.CODLOCALIT      = SSOC.CODLOCALIT
    LEFT JOIN NTARI T           ON T.CODTARA         = Coalesce(L.CODTARA, 0)
    LEFT JOIN DOCCARNETE DC     ON DC.CODCARNET      = JC.CARNETDOC
    LEFT JOIN TMP_UTILIZATOR UT ON UT.CODUTILIZATOR  = JC.USERID' || gSuplJoins;

  sSelect4 := '
 WITH x AS (
    SELECT
      C.CODCOMPENS,
      CASE
      WHEN G.SEMNIFICATIE = 1350 AND Coalesce(C.TIPCOMPENS,0) = 5 THEN 1
      WHEN G.SEMNIFICATIE = 1350 AND Coalesce(C.TIPCOMPENS,0) = 5 THEN 2
      ELSE NULL
      END coddoc1,
      P.CODPART PART, C.NRDOC, C.DATADOC, C.CARNETDOC, C.SUBUNITATEA, C.OBSC,
      CASE O.SEMNIFICATIE WHEN 1350 THEN -1 ELSE 1 END * O.VALOARE * Coalesce(NullIF(g.curs,0),1) VALOARE, CASE O.SEMNIFICATIE WHEN 1350 THEN -1 ELSE 1 END * G.TVA * Coalesce(NullIF(g.curs,0),1) TVA,
      CASE O.SEMNIFICATIE WHEN 1350 THEN -1 ELSE 1 END * (O.VALOARE - G.TVA) * Coalesce(NullIF(g.curs,0),1) BAZA,
      CASE WHEN Coalesce(abs(o.valoare) - abs(g.tva),0) = 0 THEN ' || coalesce(sPjTva, '') || ' ELSE G.TVA * 100 / (O.VALOARE - G.TVA) END PJTVA, '
      ||sAnLunaIni||' ALTVA,
      C.DATACREARE, C.USERID, C.AN, C.LUNA
    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
      INNER JOIN STINGERE S  ON S.CODSTINGATORPIF = O.CODOBLIGPIF
      INNER JOIN OBLIGPIF OS ON OS.CODOBLIGPIF    = S.CODSTINSPIF
      INNER JOIN NPART P     ON P.CODPART         = CASE WHEN O.SEMNIFICATIE = 1350 THEN C.PARTC ELSE C.PARTD END
    WHERE C.AN*12+C.LUNA ' || coalesce(sCondLuna,'') || '
      AND G.SEMNIFICATIE IN (1350,1300)
      AND CASE
            WHEN G.SEMNIFICATIE = 1350 AND Coalesce(C.TIPCOMPENS,0) = 5 AND     OS.SEMNIFICATIE IN (210)      THEN 0
            WHEN G.SEMNIFICATIE = 1350                                  AND NOT OS.SEMNIFICATIE IN (330,1303) THEN 1
            WHEN G.SEMNIFICATIE = 1300                                  AND     OS.SEMNIFICATIE IN (310,430)  THEN 1
            WHEN G.SEMNIFICATIE = 1300 AND Coalesce(C.TIPCOMPENS,0) = 5 AND     OS.SEMNIFICATIE IN (110)      THEN 1
            ELSE 0
          END = 1
      AND Coalesce(G.TVA,0) &lt;&gt; 0
      AND P.CODPART &lt;&gt; 0 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'C', NULL, NULL, getsubunitate())),'') || '),
  JC_COMPENS AS (
    SELECT
      CODCOMPENS, CODDOC1, 1 TIPTVA, 0 CODLOCATIE, PART, NRDOC, DATADOC, CARNETDOC, SUBUNITATEA, OBSC,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 3 THEN BAZA ELSE 0 END) BMAX,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 3 THEN TVA  ELSE 0 END) TMAX,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 2 THEN BAZA ELSE 0 END) BMIN,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 2 THEN TVA  ELSE 0 END) TMIN,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 1 THEN BAZA ELSE 0 END) BMED,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 1 THEN TVA  ELSE 0 END) TMED,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 4 THEN BAZA ELSE 0 END) BREG,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 4 THEN TVA  ELSE 0 END) TREG,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 5 THEN BAZA ELSE 0 END) BREG2,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 5 THEN TVA  ELSE 0 END) TREG2,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 6 THEN BAZA ELSE 0 END) BREG3,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 6 THEN TVA  ELSE 0 END) TREG3,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 7 THEN BAZA ELSE 0 END) BREG4,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 7 THEN TVA  ELSE 0 END) TREG4,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 8 THEN BAZA ELSE 0 END) BREG5,
      SUM(CASE WHEN PKG_LIST_BASE_UTILS_MATCH_TVA(PJTVA, ALTVA) = 8 THEN TVA  ELSE 0 END) TREG5,
      0 T0,
      0 AICB_BAZA, 0 AICB_TVA, 0 AICB_SCUT, 0 AICB_NEIMP, 0 AICS_SCUT, 0 AICS_NEIMP,
      0 RS315_BAZA, 0 RS315_TVA, 0 BS150_BAZA, 0 BS150_TVA, 0 BS160_BAZA, 0 BS160_TVA, 0 BS160_BMAX, 0 BS160_TMAX, 0 BS160_BMIN, 0 BS160_TMIN, 0 BS160_BMED, 0 BS160_TMED, 0 BS160_BREG, 0 BS160_TREG, 0 BS160_BREG2, 0 BS160_TREG2,
      0 BS160_BREG3, 0 BS160_TREG3, 0 BS160_BREG4, 0 BS160_TREG4, 0 BS160_BREG5, 0 BS160_TREG5,
      SUM(VALOARE) VALOARE, DATACREARE, USERID, AN, LUNA,
      SUM(BAZA+TVA) DOCVAL, SUM (BAZA) DOCBAZA, SUM (TVA) DOCTVA
    FROM X
    GROUP BY CODCOMPENS, CODDOC1, PART, NRDOC, DATADOC, CARNETDOC, SUBUNITATEA, OBSC, DATACREARE, USERID, AN, LUNA
  )
  SELECT
    JC.CODCOMPENS, NULL NAV_CodDoc1, 28, 1 ORDDOC,
    ''PV'' PREFIXDOC, PKG_LIST_BASE_UTILS_DECODE_TIPDOC_SCURT(28) TIPDOC, JC.NRDOC, NULL NRI, JC.DATADOC, DC.SERIE, P.DEN_PART, CFP.CODFISCAL ,
    JC.VALOARE VALDOC,
    JC.BMAX BAZA_MAX, JC.TMAX TVA_MAX, JC.BMIN BAZA_MIN, JC.TMIN TVA_MIN, JC.BMED BAZA_MED, JC.TMED TVA_MED,
    0 BAZA_REGMAX, 0 TVA_REGMAX, 0 BAZA_REGMIN, 0 TVA_REGMIN,
    JC.BREG BAZA_REG, JC.TREG TVA_REG, JC.BREG2 BAZA_REG2, JC.TREG2 TVA_REG2, JC.BREG3 BAZA_REG3, JC.TREG3 TVA_REG3, JC.BREG4 BAZA_REG4, JC.TREG4 TVA_REG4, JC.BREG5 BAZA_REG5, JC.TREG5 TVA_REG5, JC.T0 TVA_0,
    JC.AICB_BAZA, JC.AICB_TVA, JC.AICB_SCUT, JC.AICB_NEIMP, JC.AICS_SCUT, JC.AICS_NEIMP,
    JC.RS315_BAZA,  JC.RS315_TVA,
    JC.BS150_BAZA,  JC.BS150_TVA,
    JC.BS160_BAZA,  JC.BS160_TVA,
    JC.BS160_BMAX,  JC.BS160_TMAX,
    JC.BS160_BMIN,  JC.BS160_TMIN,
    JC.BS160_BMED,  JC.BS160_TMED,
    JC.BS160_BREG,  JC.BS160_TREG,
    JC.BS160_BREG2, JC.BS160_TREG2,
    JC.BS160_BREG3, JC.BS160_TREG3,
    JC.BS160_BREG4, JC.BS160_TREG4,
    JC.BS160_BREG5, JC.BS160_TREG5,
    0 PRORATA, 0 TVANMAX, 0 TVANMIN, 0 TVANMED, 0 TVANREG, 0 TVANREG2, 0 TVANREG3, 0 TVANREG4, 0 TVANREG5, 0 TVANEDED, 0 TVANPRORATA, 0 TVAMPRORATA,
    JC.OBSC, SUB.DEN_SUBUNIT, CASE WHEN t.statcomunitar = 1 THEN ''DA'' ELSE ''NU'' END  ue, CASE WHEN jc.tiptva = 2 THEN ''DA'' ELSE ''NU'' END  ti,
    JC.DATACREARE, UT.USERNAME, JC.AN, JC.LUNA, ''NU'' TVALAINC, ''NU'' TVALAINCF,
    NULL RESTOL, NULL BAZAOBLIG, NULL TVANOBLIG,
    NULL PLATAPREFIX, NULL PLATATIP, NULL PLATANR, NULL PLATADATA,
    NULL PLATAVAL, NULL PLATAVFT, NULL PLATATVA,
    NULL RESTVAL, NULL RESTTVA, NULL SOLDVAL, NULL SOLDTVA,
    JC.DOCVAL, JC.DOCBAZA, JC.DOCTVA,
    NULL TIPTVADOC,
    0 TVA_RET' || gUserAlias || '
  FROM JC_COMPENS JC
    LEFT JOIN INTRARI I         ON I.CODINTR         = jc.codcompens - jc.codcompens
    LEFT JOIN NPART P           ON P.CODPART         = JC.PART
    LEFT JOIN NPARTCODFISC CFP  ON CFP.CODPART       = JC.PART AND CFP.PRINCIPAL = 1
    LEFT JOIN NPARTCODFISC CFD  ON CFD.COD_CODFISCAL = CFP.COD_CODFISCAL
    LEFT JOIN NSUBUNIT SUB      ON SUB.CODSUBUNIT    = JC.SUBUNITATEA
    LEFT JOIN NAGENDA SDOC      ON SDOC.CODAGENDA    = JC.CODLOCATIE
    LEFT JOIN NAGENDA SSOC      ON SSOC.CODPART      = JC.PART AND Coalesce(SSOC.INACTIV,0) = 0 AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND SSOC.TIP = 0
    LEFT JOIN NLOCALIT L        ON L.CODLOCALIT      = SSOC.CODLOCALIT
    LEFT JOIN NTARI T           ON T.CODTARA         = Coalesce(L.CODTARA, 0)
    LEFT JOIN DOCCARNETE DC     ON DC.CODCARNET      = JC.CARNETDOC
    LEFT JOIN TMP_UTILIZATOR UT ON UT.CODUTILIZATOR  = JC.USERID' || gSuplJoins;

  sSelect5 := '
  WITH X AS (' || coalesce(pkg_list_base_jurncump_sxintr(sPjTva), '') || '
      AND I.CODINTR IN (SELECT DISTINCT CODDOC FROM TMP_LST_TVAINCAS) ),
  JC AS (' || coalesce(pkg_list_base_jurncump_sjcintr(), '') || ')
  SELECT
    I.CODINTR, NULL NAV_CodDoc1, I.TIPDOC, TVAI.ORDDOC,
    I.PREFIXDOC, PKG_LIST_BASE_UTILS_DECODE_TIPDOC_SCURT(I.TIPDOC) TIPDOC, I.NRDOC, I.NRI, I.DATADOC, Coalesce(I.SERIADOC,DC.SERIE) SERIADOC, P.DEN_PART, COALESCE(CFD.CODFISCAL,SDOC.CODFISCAL,CFP.CODFISCAL) CODFISCAL,
    CASE
      WHEN Coalesce(TVAI.CoefDoc,1) &lt;&gt; 1 OR Coalesce(TVAI.CoefDocTva,1) &lt;&gt; 1 OR Coalesce(TVAI.ORDDOC,1) &gt; 1 OR '||sAnLunaIni||' &gt; i.an*12+luna THEN NULL
      ELSE JC.BMAX + JC.TMAX + JC.BMIN + JC.TMIN + JC.BMED + JC.TMED + JC.BREG + JC.TREG + JC.BREG2 + JC.TREG2 + JC.T0 END
    VALDOC,
  (CASE WHEN JC.DOC_REG = 1 THEN 0 ELSE 1 END) *
    (CASE WHEN JC.AUX_X = 0 THEN JC.BNMAX  ELSE JC.BXMAX  END*TVAI.COEFBAZA+CASE WHEN JC.AUX_X &lt;&gt; 0 AND i.an*12+luna '||sCondLuna||' AND Coalesce(TVAI.ORDDOC,1) = 1 THEN JC.BMAX  ELSE 0 END) BAZA_MAX,
    (CASE WHEN JC.DOC_REG = 1 THEN 0 ELSE 1 END) *
    (CASE WHEN JC.AUX_X = 0 THEN JC.TNMAX  ELSE JC.TXMAX  END*TVAI.COEFTVA +CASE WHEN JC.AUX_X &lt;&gt; 0 AND i.an*12+luna '||sCondLuna||' AND Coalesce(TVAI.ORDDOC,1) = 1 THEN JC.TMAX  ELSE 0 END) TVA_MAX,
    (CASE WHEN JC.DOC_REG = 1 THEN 0 ELSE 1 END) *
    (CASE WHEN JC.AUX_X = 0 THEN JC.BNMIN  ELSE JC.BXMIN  END*TVAI.COEFBAZA+CASE WHEN JC.AUX_X &lt;&gt; 0 AND i.an*12+luna '||sCondLuna||' AND Coalesce(TVAI.ORDDOC,1) = 1 THEN JC.BMIN  ELSE 0 END) BAZA_MIN,
    (CASE WHEN JC.DOC_REG = 1 THEN 0 ELSE 1 END) *
    (CASE WHEN JC.AUX_X = 0 THEN JC.TNMIN  ELSE JC.TXMIN  END*TVAI.COEFTVA +CASE WHEN JC.AUX_X &lt;&gt; 0 AND i.an*12+luna '||sCondLuna||' AND Coalesce(TVAI.ORDDOC,1) = 1 THEN JC.TMIN  ELSE 0 END) TVA_MIN,
    (CASE WHEN JC.AUX_X = 0 THEN JC.BNMED  ELSE JC.BXMED  END*TVAI.COEFBAZA+CASE WHEN JC.AUX_X &lt;&gt; 0 AND i.an*12+luna '||sCondLuna||' AND Coalesce(TVAI.ORDDOC,1) = 1 THEN JC.BMED  ELSE 0 END) BAZA_MED,
    (CASE WHEN JC.AUX_X = 0 THEN JC.TNMED  ELSE JC.TXMED  END*TVAI.COEFTVA +CASE WHEN JC.AUX_X &lt;&gt; 0 AND i.an*12+luna '||sCondLuna||' AND Coalesce(TVAI.ORDDOC,1) = 1 THEN JC.TMED  ELSE 0 END) TVA_MED,
    (CASE WHEN JC.DOC_REG = 1 THEN 1 ELSE 0 END) *
    (CASE WHEN JC.AUX_X = 0 THEN JC.BNMAX  ELSE JC.BXMAX  END*TVAI.COEFBAZA+CASE WHEN JC.AUX_X &lt;&gt; 0 AND i.an*12+luna '||sCondLuna||' AND Coalesce(TVAI.ORDDOC,1) = 1 THEN JC.BMAX  ELSE 0 END) BAZA_REGMAX,
    (CASE WHEN JC.DOC_REG = 1 THEN 1 ELSE 0 END) *
    (CASE WHEN JC.AUX_X = 0 THEN JC.TNMAX  ELSE JC.TXMAX  END*TVAI.COEFTVA +CASE WHEN JC.AUX_X &lt;&gt; 0 AND i.an*12+luna '||sCondLuna||' AND Coalesce(TVAI.ORDDOC,1) = 1 THEN JC.TMAX  ELSE 0 END) TVA_REGMAX,
    (CASE WHEN JC.DOC_REG = 1 THEN 1 ELSE 0 END) *
    (CASE WHEN JC.AUX_X = 0 THEN JC.BNMIN  ELSE JC.BXMIN  END*TVAI.COEFBAZA+CASE WHEN JC.AUX_X &lt;&gt; 0 AND i.an*12+luna '||sCondLuna||' AND Coalesce(TVAI.ORDDOC,1) = 1 THEN JC.BMIN  ELSE 0 END) BAZA_REGMIN,
    (CASE WHEN JC.DOC_REG = 1 THEN 1 ELSE 0 END) *
    (CASE WHEN JC.AUX_X = 0 THEN JC.TNMIN  ELSE JC.TXMIN  END*TVAI.COEFTVA +CASE WHEN JC.AUX_X &lt;&gt; 0 AND i.an*12+luna '||sCondLuna||' AND Coalesce(TVAI.ORDDOC,1) = 1 THEN JC.TMIN  ELSE 0 END) TVA_REGMIN,
    (CASE WHEN JC.AUX_X = 0 THEN JC.BNREG  ELSE JC.BXREG  END*TVAI.COEFBAZA+CASE WHEN JC.AUX_X &lt;&gt; 0 AND i.an*12+luna ' || coalesce(sCondLuna,'') || ' AND Coalesce(TVAI.ORDDOC,1) = 1 THEN JC.BREG  ELSE 0 END) BAZA_REG,
    (CASE WHEN JC.AUX_X = 0 THEN JC.TNREG  ELSE JC.TXREG  END*TVAI.COEFTVA +CASE WHEN JC.AUX_X &lt;&gt; 0 AND i.an*12+luna ' || coalesce(sCondLuna,'') || ' AND Coalesce(TVAI.ORDDOC,1) = 1 THEN JC.TREG  ELSE 0 END) TVA_REG,
    (CASE WHEN JC.AUX_X = 0 THEN JC.BNREG2 ELSE JC.BXREG2 END*TVAI.COEFBAZA+CASE WHEN JC.AUX_X &lt;&gt; 0 AND i.an*12+luna ' || coalesce(sCondLuna,'') || ' AND Coalesce(TVAI.ORDDOC,1) = 1 THEN JC.BREG2 ELSE 0 END) BAZA_REG2,
    (CASE WHEN JC.AUX_X = 0 THEN JC.TNREG2 ELSE JC.TXREG2 END*TVAI.COEFTVA +CASE WHEN JC.AUX_X &lt;&gt; 0 AND i.an*12+luna ' || coalesce(sCondLuna,'') || ' AND Coalesce(TVAI.ORDDOC,1) = 1 THEN JC.TREG2 ELSE 0 END) TVA_REG2,
    (CASE WHEN JC.AUX_X = 0 THEN JC.BNREG3 ELSE JC.BXREG3 END*TVAI.COEFBAZA+CASE WHEN JC.AUX_X &lt;&gt; 0 AND i.an*12+luna ' || coalesce(sCondLuna,'') || ' AND Coalesce(TVAI.ORDDOC,1) = 1 THEN JC.BREG3 ELSE 0 END) BAZA_REG3,
    (CASE WHEN JC.AUX_X = 0 THEN JC.TNREG3 ELSE JC.TXREG3 END*TVAI.COEFTVA +CASE WHEN JC.AUX_X &lt;&gt; 0 AND i.an*12+luna ' || coalesce(sCondLuna,'') || ' AND Coalesce(TVAI.ORDDOC,1) = 1 THEN JC.TREG3 ELSE 0 END) TVA_REG3,
    (CASE WHEN JC.AUX_X = 0 THEN JC.BNREG4 ELSE JC.BXREG4 END*TVAI.COEFBAZA+CASE WHEN JC.AUX_X &lt;&gt; 0 AND i.an*12+luna ' || coalesce(sCondLuna,'') || ' AND Coalesce(TVAI.ORDDOC,1) = 1 THEN JC.BREG4 ELSE 0 END) BAZA_REG4,
    (CASE WHEN JC.AUX_X = 0 THEN JC.TNREG4 ELSE JC.TXREG4 END*TVAI.COEFTVA +CASE WHEN JC.AUX_X &lt;&gt; 0 AND i.an*12+luna ' || coalesce(sCondLuna,'') || ' AND Coalesce(TVAI.ORDDOC,1) = 1 THEN JC.TREG4 ELSE 0 END) TVA_REG4,
    (CASE WHEN JC.AUX_X = 0 THEN JC.BNREG5 ELSE JC.BXREG5 END*TVAI.COEFBAZA+CASE WHEN JC.AUX_X &lt;&gt; 0 AND i.an*12+luna ' || coALESCE(sCondLuna,'') || ' AND Coalesce(TVAI.ORDDOC,1) = 1 THEN JC.BREG5 ELSE 0 END) BAZA_REG5,
    (CASE WHEN JC.AUX_X = 0 THEN JC.TNREG5 ELSE JC.TXREG5 END*TVAI.COEFTVA +CASE WHEN JC.AUX_X &lt;&gt; 0 AND i.an*12+luna ' || COALESCE(sCondLuna,'') || ' AND Coalesce(TVAI.ORDDOC,1) = 1 THEN JC.TREG5 ELSE 0 END) TVA_REG5,
    CASE WHEN Coalesce(TVAI.CoefDoc,1) &lt;&gt; 1 OR Coalesce(TVAI.ORDDOC,1) &gt; 1 OR '||sAnLunaIni||' &gt; i.an*12+luna THEN NULL ELSE JC.T0 END TVA_0,
    NULL AICB_BAZA, NULL AICB_TVA, NULL AICB_SCUT, NULL AICB_NEIMP, NULL AICS_SCUT, NULL AICS_NEIMP,
    NULL RS315_BAZA,  NULL RS315_TVA,
    NULL BS150_BAZA,  NULL BS150_TVA,
    NULL BS160_BAZA,  NULL BS160_TVA,
    NULL BS160_BMAX,  NULL BS160_TMAX,
    NULL BS160_BMIN,  NULL BS160_TMIN,
    NULL BS160_BMED,  NULL BS160_TMED,
    NULL BS160_BREG,  NULL BS160_TREG,
    NULL BS160_BREG2, NULL BS160_TREG2,
    NULL BS160_BREG3, NULL BS160_TREG3,
    NULL BS160_BREG4, NULL BS160_TREG4,
    NULL BS160_BREG5, NULL BS160_TREG5,
    CASE WHEN Coalesce(TVAI.CoefDoc,1) &lt;&gt; 1 OR Coalesce(TVAI.ORDDOC,1) &gt; 1 OR '||sAnLunaIni||' &gt; i.an*12+luna THEN NULL ELSE JC.PRORATA   END PRORATA,
    CASE WHEN Coalesce(TVAI.CoefDoc,1) &lt;&gt; 1 OR Coalesce(TVAI.ORDDOC,1) &gt; 1 OR '||sAnLunaIni||' &gt; i.an*12+luna THEN NULL ELSE JC.TNMAX     END TVAN_MAX,
    CASE WHEN Coalesce(TVAI.CoefDoc,1) &lt;&gt; 1 OR Coalesce(TVAI.ORDDOC,1) &gt; 1 OR '||sAnLunaIni||' &gt; i.an*12+luna THEN NULL ELSE JC.TNMIN     END TVAN_MIN,
    CASE WHEN Coalesce(TVAI.CoefDoc,1) &lt;&gt; 1 OR Coalesce(TVAI.ORDDOC,1) &gt; 1 OR '||sAnLunaIni||' &gt; i.an*12+luna THEN NULL ELSE JC.TNMED     END TVAN_MED,
    CASE WHEN Coalesce(TVAI.CoefDoc,1) &lt;&gt; 1 OR Coalesce(TVAI.ORDDOC,1) &gt; 1 OR '||sAnLunaIni||' &gt; i.an*12+luna THEN NULL ELSE JC.TNREG     END TVAN_REG,
    CASE WHEN Coalesce(TVAI.CoefDoc,1) &lt;&gt; 1 OR Coalesce(TVAI.ORDDOC,1) &gt; 1 OR '||sAnLunaIni||' &gt; i.an*12+luna THEN NULL ELSE JC.TNREG2    END TVAN_REG2,
    CASE WHEN Coalesce(TVAI.CoefDoc,1) &lt;&gt; 1 OR Coalesce(TVAI.ORDDOC,1) &gt; 1 OR '||sAnLunaIni||' &gt; i.an*12+luna THEN NULL ELSE JC.TNREG3    END TVAN_REG3,
    CASE WHEN Coalesce(TVAI.CoefDoc,1) &lt;&gt; 1 OR Coalesce(TVAI.ORDDOC,1) &gt; 1 OR '||sAnLunaIni||' &gt; i.an*12+luna THEN NULL ELSE JC.TNREG4    END TVAN_REG4,
    CASE WHEN Coalesce(TVAI.CoefDoc,1) &lt;&gt; 1 OR Coalesce(TVAI.ORDDOC,1) &gt; 1 OR '||sAnLunaIni||' &gt; i.an*12+luna THEN NULL ELSE JC.TNREG5    END TVAN_REG5,
    CASE WHEN Coalesce(TVAI.CoefDoc,1) &lt;&gt; 1 OR Coalesce(TVAI.ORDDOC,1) &gt; 1 OR '||sAnLunaIni||' &gt; i.an*12+luna THEN NULL ELSE JC.TNEDED    END TVANEDED,
    CASE WHEN Coalesce(TVAI.CoefDoc,1) &lt;&gt; 1 OR Coalesce(TVAI.ORDDOC,1) &gt; 1 OR '||sAnLunaIni||' &gt; i.an*12+luna THEN NULL ELSE JC.TNPRORATA END TVANPRORATA,
    CASE WHEN Coalesce(TVAI.CoefDoc,1) &lt;&gt; 1 OR Coalesce(TVAI.ORDDOC,1) &gt; 1 OR '||sAnLunaIni||' &gt; i.an*12+luna THEN NULL ELSE JC.TMPRORATA END TVAMPRORATA,
    I.OBS, SUB.DEN_SUBUNIT, CASE WHEN t.statcomunitar = 1 THEN ''DA'' ELSE ''NU'' END UE, CASE WHEN jc.tiptva = 2 THEN ''DA'' ELSE ''NU'' END TI,
    I.DATACREARE, UT.USERNAME, I.AN, I.LUNA, ''DA'' TVALAINC, CASE WHEN I.TVAINCASARE_F = 1 THEN ''DA'' ELSE ''NU'' END TVALAINCF,
    CASE WHEN TVAI.ORDDOC = 1 OR TVAI.ORDDOC IS NULL THEN JC.BAZAX*Coalesce(TVAI.CoefDocBaza,1)+JC.TVAX*Coalesce(TVAI.CoefDocTva,1) ELSE NULL END RESTOL,
    CASE WHEN TVAI.ORDDOC = 1 OR TVAI.ORDDOC IS NULL THEN JC.BAZAX*Coalesce(TVAI.CoefDocBaza,1)                                     ELSE NULL END BAZAOBLIG,
    CASE WHEN TVAI.ORDDOC = 1 OR TVAI.ORDDOC IS NULL THEN                                       JC.TVAX*Coalesce(TVAI.CoefDocTva,1) ELSE NULL END TVANOBLIG,
    TVAI.PREFIXSTINGERE PLATAPREFIX, PKG_LIST_BASE_UTILS_DECODE_TIPDOC_SCURT(TVAI.TIPSTINGERE) PLATATIP, TVAI.NRSTINGERE PLATANR, TVAI.DATASTINGERE PLATADATA,
    Round(JC.BAZAX*TVAI.COEFBAZA+JC.TVAX*TVAI.COEFTVA, 7) PLATAVAL, Round(JC.BAZAX*TVAI.COEFBAZA, 7) PLATAVFT, Round(JC.TVAX*TVAI.COEFTVA, 7) PLATATVA,
    Round(JC.BAZAX*(Coalesce(TVAI.CoefDocBaza,1)-TVAI.CoefPlataBaza) + JC.TVAX*(Coalesce(TVAI.CoefDocTva,1)-TVAI.CoefPlataTva),7) RESTVAL, Round(JC.TVAX*(Coalesce(TVAI.CoefDocTva,1)-TVAI.CoefPlataTva),7) RESTTVA,
    Round(CASE WHEN TVAI.ORDDOC IS NULL OR TVAI.ORDDOC = TVAI.CountDoc THEN JC.BAZAX*(Coalesce(TVAI.CoefDocBaza,1)-TVAI.CoefPlataBaza)+JC.TVAX*(Coalesce(TVAI.CoefDocTva,1)-TVAI.CoefPlataTva) ELSE NULL END,7) SOLDVAL,
    Round(CASE WHEN TVAI.ORDDOC IS NULL OR TVAI.ORDDOC = TVAI.CountDoc THEN                                                            JC.TVAX*(Coalesce(TVAI.CoefDocTva,1)-TVAI.CoefPlataTva) ELSE NULL END,7) SOLDTVA,
    I.VALDOC * Coalesce(NULLIf(I.Curs,0),1) DOCVAL, (I.VALDOC-I.TVADOC) * Coalesce(NULLIf(I.Curs,0),1) DOCBAZA, I.TVADOC * Coalesce(NULLIf(I.Curs,0),1) DOCTVA,
    CASE i.tiptva WHEN 1 THEN ''Taxare normala'' WHEN 2 THEN ''Taxare inversa'' WHEN 3 THEN ''Tranzactie triunghiulara'' WHEN 4 THEN ''Suspendare temporara'' END TIPTVADOC,
    0 TVA_RET ' || gUserAlias || '
  FROM JC
    INNER JOIN INTRARI I             ON I.CODINTR         = JC.CODINTR
    INNER JOIN TMP_LST_TVAINCAS TVAI ON TVAI.CodDoc       = I.CodIntr AND TVAI.TIPDOC = I.TIPDOC
    LEFT JOIN NPART P                ON P.CODPART         = I.PARTENER
    LEFT JOIN NPARTCODFISC CFP       ON CFP.CODPART       = I.PARTENER AND CFP.PRINCIPAL = 1
    LEFT JOIN NPARTCODFISC CFD       ON CFD.COD_CODFISCAL = I.CODFISCAL
    LEFT JOIN NSUBUNIT SUB           ON SUB.CODSUBUNIT    = I.SUBUNITATEA
    LEFT JOIN NAGENDA SDOC           ON SDOC.CODAGENDA    = I.CODLOCATIE
    LEFT JOIN NAGENDA SSOC           ON SSOC.CODPART      = I.PARTENER AND Coalesce(SSOC.INACTIV,0) = 0 AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND SSOC.TIP = 0
    LEFT JOIN NLOCALIT L             ON L.CODLOCALIT      = Coalesce(SDOC.CODLOCALIT, SSOC.CODLOCALIT)
    LEFT JOIN NTARI T                ON T.CODTARA         = Coalesce(L.CODTARA, 0)
    LEFT JOIN DOCCARNETE DC          ON DC.CODCARNET      = I.CARNETDOC
    LEFT JOIN TMP_UTILIZATOR UT      ON UT.CODUTILIZATOR  = I.USERID' || gSuplJoins;
  PERFORM pkg_list_base_jurncump_Pregateste_TMP_LST_TVAINCAS(aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert|| sSelect1, aListID, aListVer);

  IF vCountArt &gt; 0 THEN
    DELETE FROM TMP_JC_AUX1;
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsAux1, aListID, aListVer);
    PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate1, aListID, aListVer);
  END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert|| sSelect2, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert|| sSelect3, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert|| sSelect4, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert|| sSelect5, aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_jurncump_sxintr</obj_name>
  <obj_hashval>7ea42429e6aa8c75aaf286291e64a14b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_jurncump_sxintr(spjtva character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnLunaFin    VARCHAR := coalesce(NULLIF(current_setting('PKG_LIST_BASE_JURNCUMP.vAnLunaFin'   , true), ''),  '0');
  sServAicb     VARCHAR := coalesce(NULLIF(current_setting('PKG_LIST_BASE_JURNCUMP.sServAICB'    , true), ''), '-1');
  vISIVB        BOOLEAN := coalesce(NULLIF(current_setting('PKG_LIST_BASE_JURNCUMP.vISIVB'       , true), ''),  '0')  = '1';
  vIMFEStoc     BOOLEAN := coalesce(NULLIF(current_setting('PKG_LIST_BASE_JURNCUMP.vIMFEStoc'    , true), ''),  '0')  = '1';
  sCImbMifix    VARCHAR := coalesce(NULLIF(current_setting('PKG_LIST_BASE_JURNCUMP.sCImbMifix'   , true), ''), '-1');
  sFiltruCodArt VARCHAR := coalesce(NULLIF(current_setting('PKG_LIST_BASE_JURNCUMP.sFiltruCodArt', true), ''),   '');
BEGIN
  --Florin 09.12.2025 - sinc. Oracle
  --Stef  28.04.2025
  RETURN '
    SELECT
      I.CODINTR, Coalesce(I.TVAINCASARE,0) TVAINC, I1.TIPLINIE, I.TIPTVA,
      CASE
        WHEN                                                                                              I.TIPTVA = 9                                                                   THEN ''RS315''
        WHEN I1.TIPLINIE IN (''G'',''T'')       AND Coalesce(I.TIPTRANZACTIE,1) = 2 AND I.TIPDOC  = 5                  AND Coalesce(D1.TVA, 0) = 0                                       THEN ''AICBS''
        WHEN I1.TIPLINIE IN (''G'',''T'')       AND Coalesce(I.TIPTRANZACTIE,1) = 2 AND I.TIPDOC &lt;&gt; 5                  AND Coalesce(I1.TVA, 0) = 0                                       THEN ''AICBS''
        WHEN I1.TIPLINIE IN (''S'',''V'',''='') AND Coalesce(I.TIPTRANZACTIE,1) = 2 AND I.TIPDOC  = 5                  AND Coalesce(D1.TVA, 0) = 0 AND T1.PROCENT = 0                    THEN ''AICBS''
        WHEN I1.TIPLINIE IN (''S'',''V'',''='') AND Coalesce(I.TIPTRANZACTIE,1) = 2 AND I.TIPDOC &lt;&gt; 5                  AND Coalesce(I1.TVA, 0) = 0 AND T1.PROCENT = 0                    THEN ''AICBS''
        WHEN I1.TIPLINIE IN (''S'',''V'',''='') AND Coalesce(I.TIPTRANZACTIE,1) = 2 AND I.TIPDOC  = 5                  AND Coalesce(D1.TVA, 0) = 0                                       THEN ''AICBN''
        WHEN I1.TIPLINIE IN (''S'',''V'',''='') AND Coalesce(I.TIPTRANZACTIE,1) = 2 AND I.TIPDOC &lt;&gt; 5                  AND Coalesce(I1.TVA, 0) = 0                                       THEN ''AICBN'''||
    CASE
      WHEN sServAICB &lt;&gt; '-1' THEN '
        WHEN I1.TIPLINIE IN (''S'')             AND Coalesce(I.TIPTRANZACTIE,1) = 2                                                                AND I1.CODOBIECT IN ('||sServAICB||') THEN ''AICB'''
      ELSE ''
    END||
    CASE
      WHEN vISIVB THEN '
        WHEN I1.TIPLINIE = ''S''                AND Coalesce(I.TIPTRANZACTIE,1) = 2
         AND MAX(CASE WHEN I1.TIPLINIE = ''='' THEN 1 ELSE 0 END) OVER (PARTITION BY I.CodIntr) = 1                                                                                      THEN ''AICB'''
      ELSE ''
    END||'
        WHEN                                                                            I.TIPDOC &lt;&gt; 5                  AND Coalesce(I1.TVA, 0) = 0                                       THEN ''N0''
        WHEN                                                                            I.TIPDOC  = 5                  AND Coalesce(D1.TVA, 0) = 0                                       THEN ''N0''
        WHEN I1.TIPLINIE IN (''='')             AND Coalesce(I.TIPTRANZACTIE,1) = 2                   AND I.TIPTVA = 8                                                                   THEN ''BS150''
        WHEN I1.TIPLINIE IN (''S'',''V'',''G'',''T'')                               AND I.TIPDOC  = 5 AND I.TIPTVA = 2                                                                   THEN ''BS150''
        WHEN I1.TIPLINIE IN (''S'',''V'',''G'',''T'') AND Coalesce(I.TIPTRANZACTIE,1) = 3             AND I.TIPTVA = 2                                                                   THEN ''BS150''
        WHEN I1.TIPLINIE IN (''S'',''V'',''G'',''T'') AND Coalesce(I.TIPTRANZACTIE,1) = 3                                                          AND Coalesce(I1.IMPOZABIL,0) = 3      THEN ''BS150''
        WHEN I1.TIPLINIE IN (''S'',''G'',''T'') AND Coalesce(I.TIPTRANZACTIE,1) = 2                   AND I.TIPTVA = 2                                                                   THEN ''BS150''
        WHEN I1.TIPLINIE IN (''S'',''G'',''T'') AND Coalesce(I.TIPTRANZACTIE,1) = 2                                                                AND Coalesce(I1.IMPOZABIL,0) = 3      THEN ''BS150''
        WHEN I1.TIPLINIE IN (''S'',''G'',''T'')                                     AND I.TIPDOC  = 5                                              AND Coalesce(I1.IMPOZABIL,0) = 3      THEN ''BS150''
        WHEN I1.TIPLINIE IN (''S'',''G'',''T'') AND Coalesce(I.TIPTRANZACTIE,1) = 2 AND I.TIPDOC &lt;&gt; 5 AND I.TIPTVA = 1                                                                   THEN ''BS150''
        WHEN I1.TIPLINIE IN (''S'',''G'',''T'') AND Coalesce(I.TIPTRANZACTIE,1) = 2 AND I.TIPDOC &lt;&gt; 5 AND I.TIPTVA = 8                                                                   THEN ''BS150''
        WHEN I1.TIPLINIE IN (''V'',''='')       AND Coalesce(I.TIPTRANZACTIE,1) = 1 AND I.TIPDOC &lt;&gt; 5 AND I.TIPTVA = 2                                                                   THEN ''BS160''
        WHEN I1.TIPLINIE IN (''V'',''='')       AND Coalesce(I.TIPTRANZACTIE,1) = 1 AND I.TIPDOC &lt;&gt; 5 AND I.TIPTVA = 3                                                                   THEN ''BS160''
        WHEN I1.TIPLINIE IN (''V'',''='')       AND Coalesce(I.TIPTRANZACTIE,1) = 1 AND I.TIPDOC &lt;&gt; 5                                              AND Coalesce(I1.IMPOZABIL,0) = 3      THEN ''BS160''
        WHEN I1.TIPLINIE IN (''S'',''G'',''T'') AND Coalesce(I.TIPTRANZACTIE,1) = 1 AND I.TIPDOC &lt;&gt; 5 AND I.TIPTVA = 2                                                                   THEN ''BS160''
        WHEN I1.TIPLINIE IN (''S'',''G'',''T'') AND Coalesce(I.TIPTRANZACTIE,1) = 1 AND I.TIPDOC &lt;&gt; 5                                              AND Coalesce(I1.IMPOZABIL,0) = 3      THEN ''BS160'''||
    CASE
      WHEN vIMFEStoc AND sCImbMifix &lt;&gt; '-1'
      THEN '
        WHEN I1.TIPLINIE = ''S'' AND A.CONTSERVICIU IN ('||sCImbMifix||') THEN
          CASE
            WHEN                                    Coalesce(I.TIPTRANZACTIE,1) = 1 AND I.TIPDOC &lt;&gt; 5 AND I.TIPTVA = 3                                                                   THEN ''BS160''
            WHEN                                                                        I.TIPDOC &lt;&gt; 5                  AND Coalesce(I1.TVA, 0) = 0                                       THEN ''N0''
            WHEN                                                                        I.TIPDOC  = 5                  AND Coalesce(D1.TVA, 0) = 0                                       THEN ''N0''
            WHEN                                    Coalesce(I.TIPTRANZACTIE,1) = 2                                                                                                      THEN ''AICB''
            ELSE                                                                                                                                                                              ''NTVA''
          END'
      ELSE ''
    END||'
        WHEN EXISTS(SELECT 1 FROM General G INNER JOIN OBLIGPIF O ON O.CODGENERAL = G.CODGENERAL WHERE G.CodDoc = i.CodIntr AND G.TipDoc = I.TipDoc AND G.SEMNIFICATIE IN (110,111) AND O.Icont IN (12,19))
         AND I1.TIPLINIE IN (''V'')             AND Coalesce(I.TIPTRANZACTIE,1) = 2                                                                                                      THEN ''BS150''
        WHEN I1.TIPLINIE IN (''V'',''='')       AND Coalesce(I.TIPTRANZACTIE,1) = 2                                                                                                      THEN ''AICB''
        WHEN                                                                            I.TIPDOC  = 5                  AND Coalesce(D1.TVA, 0) = 0                                       THEN ''N0''
        WHEN                                                                            I.TIPDOC &lt;&gt; 5                  AND Coalesce(I1.TVA, 0) = 0                                       THEN ''N0''
        ELSE                                                                                                                                                                                  ''NTVA''
      END CAZ,
      PKG_LIST_BASE_UTILS_MATCH_TVA(
        CASE
          WHEN I1.TIPLINIE IN (''='',''S'',''V'',''R'') AND (Coalesce(I1.CANT * I1.PU,0) = 0)               THEN T1.PROCENT
          WHEN I1.TIPLINIE IN (''G'',''T'')             AND Coalesce(I1.RESTFACT,0) = 0                     THEN '||sPjTva||'
          WHEN I1.TIPLINIE IN (''G'',''T'')                                                                 THEN Coalesce(I1.TVA,0)/I1.RESTFACT*100
          WHEN I.TIPDOC = 5 AND D1.TIPLINIE IN (''X'', ''A'', ''C'') AND Coalesce(D1.VALOARETAXA,0) = 0     THEN '||sPjTva||'
          WHEN I.TIPDOC = 5 AND D1.TIPLINIE IN (''X'', ''A'', ''C'')                                        THEN Coalesce(d1.TVA,0)/ D1.VALOARETAXA*100
          WHEN I.TIPDOC = 5 AND Coalesce(D1.CANT * D1.PRETIMPORT,0) = 0                                     THEN T1.PROCENT
          WHEN I.TIPDOC = 5                                                                                 THEN Coalesce(d1.TVA,0) / (D1.CANT * D1.PRETIMPORT) *100
          ELSE PKG_LIST_BASE_UTILS_CALC_PROC_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, T1.PROCENT, I.ROTEFACT)
        END,
        '||vAnLunaFin||'
      ) xMATCH_TVA,
      ROUND(CASE
        WHEN I.TIPDOC = 5 AND D1.TIPLINIE IN (''X'', ''A'', ''C'') THEN Coalesce(D1.VALOARETAXA,0)
        WHEN I.TIPDOC = 5 AND I.TIPTRANZACTIE = 2 THEN Coalesce(D1.CANT * D1.PRETVALUTA,0) * Coalesce(NULLIf(I.Curs,0),1)
        WHEN I.TIPDOC = 5 THEN Coalesce(D1.CANT * D1.PRETIMPORT,0)
        WHEN I1.TIPLINIE IN (''G'',''T'') THEN (I1.RESTFACT - CASE WHEN I.TIPDOC = 3 THEN Coalesce(I1.TVA,0) ELSE 0 END)* Coalesce(NULLIf(I.Curs,0),1)
        ELSE ((Coalesce(I1.PU,0) * I1.CANT) - CASE WHEN I.TIPDOC = 3 THEN Coalesce(I1.TVA,0) ELSE 0 END) * Coalesce(NULLIf(I.Curs,0),1)
      END,7) BAZA,
      ROUND(CASE WHEN I.TIPDOC = 5 THEN Coalesce(d1.TVA,0) ELSE Coalesce(I1.TVA,0) * Coalesce(NULLIf(I.Curs,0),1) END,7) TVA,
      CASE WHEN Coalesce(I.TIPTVA,0) = 4 AND COALESCE(D1.TVANEDED, I1.TVANEDED,0) IN (0,3) THEN Coalesce(I.PRORATA,0) ELSE 0 END PRORATA,
      CASE COALESCE(D1.TVANEDED, I1.TVANEDED,0) WHEN 3 THEN 0.5 WHEN 1 THEN 1 ELSE 0 END +
      CASE WHEN Coalesce(I.TIPTVA,0) &lt;&gt; 4 THEN 0 WHEN COALESCE(D1.TVANEDED, I1.TVANEDED,0) = 0 THEN 1-Coalesce(I.PRORATA,0)/100 WHEN COALESCE(D1.TVANEDED, I1.TVANEDED,0) = 3 THEN 0.5*(1-Coalesce(I.PRORATA,0)/100) ELSE 0 END COEFNEDED,
      CASE WHEN Coalesce(I.TIPTVA,0) &lt;&gt; 4 THEN 0 ELSE CASE COALESCE(D1.TVANEDED, I1.TVANEDED,0) WHEN 3 THEN 0.5 WHEN 1 THEN 1 ELSE 0 END * (1-Coalesce(I.PRORATA,0) / 100) END COEFNPRORATA,
      CASE WHEN Coalesce(I.TIPTVA,0) &lt;&gt; 4 THEN 0 ELSE CASE COALESCE(D1.TVANEDED, I1.TVANEDED,0) WHEN 3 THEN 0.5 WHEN 1 THEN 1 ELSE 0 END END COEFMPRORATA,
      COALESCE(D1.TVANEDED, I1.TVANEDED,0) TVANEDED, Coalesce(I.SPLITTVA, 0) SPLITTVA,
      CASE WHEN Coalesce(i.an*100+i.luna, 0) = To_Number(Coalesce(To_Char(Coalesce(i.datatva, i.datadoc), ''yyyymm''),''0'')) THEN 0 ELSE 1 END DOC_REG
    FROM INTRARI I
      LEFT JOIN DVI       D    ON D.CODINTR     = I.CODINTR
      LEFT JOIN DVI1      D1   ON D1.CODDVI     = D.CODDVI
      LEFT JOIN INTRARI1  I1   ON I1.CODINTR    = I.CODINTR AND I1.CODINTR1 = CASE I.TIPDOC WHEN 5 THEN D1.CODINTR1 ELSE I1.CODINTR1 END
      LEFT JOIN NARTOBJ   O    ON O.CODOBIECT   = I1.CODOBIECT
      LEFT JOIN NART      A    ON A.CODARTICOL  = O.CODARTICOL
      LEFT JOIN NART1     A1   ON a1.codarticol = o.codarticol AND i.an*12+i.luna BETWEEN a1.alstart AND a1.alstop
      LEFT JOIN NTVA1     T1   ON t1.codtva     = a1.codtva    AND i.an*12+i.luna BETWEEN t1.alstart AND t1.alstop
      LEFT JOIN INTRARI1  I1ST ON I1ST.CODINTR1 = I1.CODINTR1STORNO
      LEFT JOIN INTRARI   IST  ON IST.CODINTR   = I1ST.CODINTR
      LEFT JOIN CONTRACT0 C0   ON C0.CODDOC     = I.CODINTR AND C0.TIPDOC = I.TIPDOC AND I.TIPFACTURA = 2 AND C0.TIPLINIE = 1
    WHERE I.TIPDOC IN (1,3,4,5,9) AND I.OPERAT = 1 AND I.ANULAT = 0
      AND EXISTS (SELECT 1 FROM GENERAL G WHERE G.CODDOC = I.CODINTR AND G.TIPDOC = I.TIPDOC)
      AND (
            (I.TIPTVA &lt;&gt; 3) OR
            (I.TIPTVA = 3 AND Coalesce(I1.TIPLINIE,''~'') IN (''V'',''=''))'||
      CASE
        WHEN sServAICB &lt;&gt; '-1' THEN ' OR
            (I.TIPTVA = 3 AND Coalesce(I1.TIPLINIE,''~'') IN (''S'') AND Coalesce(I.TIPTRANZACTIE,1) = 2 AND I1.CODOBIECT IN ('||sServAICB||'))'
        ELSE ''
      END||'
          )
      AND NOT Coalesce(I.TIPTRANZACTIE,1)  IN (4, 5) AND Coalesce(i1.impozabil, 0) &lt;&gt; 4
      AND NOT (Coalesce(I1.TIPLINIE,''~'') IN (''G'',''T'') AND Coalesce(I1.CONTDISCOUNT,0) = 0)
      AND NOT (Coalesce(I1.TIPLINIE,''~'') IN (''G'',''T'') AND Coalesce(I1.RESTFACT,0) = 0)
      AND NOT (Coalesce(D1.TIPLINIE,''~'') IN (''A'',''C'',''X'') AND Coalesce(D.TAXEINCLUSE,0) = 1)
      AND Coalesce(D.TIPIMPORT,0) = 0
      AND C0.CODCONTRACT IS NULL '||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', NULL, NULL, getsubunitate())||
      sFiltruCodArt;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_livrdoc_processlist</obj_name>
  <obj_hashval>e931f246121e0d6b6b8e5ebc4f89ac68</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrdoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC RECORD;
  sInsert         varchar := '';
  sSelect         varchar := '';
  vWhere           varchar := '';
  sPMP             varchar := '';
  sInsertPlus     varchar := '';
  sSelectPlus     varchar := '';
  sSelectXATR     varchar := '';
  sJoinPlus       varchar := '';
  vXATR           BOOLEAN;
  sXATR           varchar := '';
  gSuplCols        VARCHAR :=  'IESIRI I, NARTOBJ NAO, NART NA, NUM1 UM, NGEST NG, NLOCATII NL, DOCCARNETE DC, NUM1 UM1, NUM1 UM2, NPART PROD, NPART FURN, NCLASEA CA, TMP_UTILIZATOR UT,'||
                              'IOART IO, IOART1 IO1, NCONT NC, NARTOBJ1 NAO1, NIRSTOC NS, COMANDA1 C1, COMANDA C, IESLINK IL, NARTCLI FOBJ';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodGest        NUMERIC := current_setting('PKG_LIST_BASE_LIVRDOC.vCodGest', true)::NUMERIC;
  sATRIB          varchar := current_setting('PKG_LIST_BASE_LIVRDOC.sATRIB'  , true);
  vAuxNSIN        varchar := current_setting('PKG_LIST_BASE_LIVRDOC.vAuxNSIN', true);
BEGIN
  --Adina 02.04.2021 - alstart, alstop
  --Adina 09.03.2021 - prc_al_check
  --Adina 21 septembrie 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPART',         'P',       'P.CODPART = I.PARTENER',NULL);
  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_addsupltabs(gSuplCols, 'COMANDA1',     'C1I',     'C1I.CODCOMANDA1 = LG.CODCMDINT1', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA',       'CI',     'CI.CODCOMANDA = C1I.CODCOMANDA',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJ',       'CIO',     'CIO.CODOBIECT = C1I.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CMDLINK',       'CL1',     'CL1.CODCOMANDA1 = IL.CODLINIECOMANDA',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CMDLIVRLINK',   'CL2',     'CL2.CODCOMANDA1 = COALESCE(CL1.CODLINIECOMANDA,IL.CODLINIECOMANDA)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA1',     'C1C',     'C1C.CODCOMANDA1 = COALESCE(CL1.CODLINIECOMANDA,CL1.CODLINIECOMANDA,IL.CODLINIECOMANDA)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA',       'CC',     'CC.CODCOMANDA = C1C.CODCOMANDA',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTCLI',       'AC',     'AC.CODARTCLI = PKG_LIST_BASE_UTILS_GETCODARTCLI(LG.CODOBIECT, I.PARTENER, P.CODCLASA)', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI1EXT',   'I1EXT',   'I1EXT.CODIES1 = LG.CODIES1', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRIEXT',     'IEXT',   'IEXT.CODIES = LG.CODIES', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARI',       'INOR',   'INOR.CODINTR = LG.CODINTR', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI1',       'I1',     'I1.CODIES1 = LG.CODIES1', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'LIVR1',         'L1',     'L1.CODLIVR1 = LG.CODLIVR1', 1);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_LIVRDOC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  CALL PRC_AL_CHECK('ioart1');

  IF  vCodGest &gt;= 0 THEN
    vWhere := '
      WHERE COALESCE(l1.CodGestOrig, lv.gest, n.Gest, 0) = ' || coalesce(current_setting('PKG_LIST_BASE_LIVRDOC.vCodGest', true)::varchar ,'');
  END IF;

  IF ( getANCURENT() * 12 + getLUNACURENTA() ) &lt; ( getANLUCRU() * 12 + getLUNALUCRU() ) THEN
    sPMP := ',
    (case when io1.mg=3 then (Select wme_result From pkg_PMP_GET_PMP_LEI(null,lg.codobiect,i.subunitatea,i.an,i.luna) ) else NULL end),
    (case when io1.mg=3 then (Select wme_result From pkg_PMP_GET_PMP_VALUTA_FROM_VAR(null,null)) else NULL end), lg.pmpdoc, lg.pmpvalutadoc ';
  ELSE
    sPMP := ',
    lg.pmp, lg.pmpvaluta, lg.pmpdoc, lg.pmpvalutadoc ';
  END IF;

  SELECT sinsertuma, sselectuma, sjoinuma INTO sInsertPlus, sSelectPlus, sJoinPlus
  FROM PKG_LIST_BASE_UTILS_UMA_UTILS('lg.cant', 'lg.codobiect', sInsertPlus, sSelectPlus, sJoinPlus,NULL);

  vXATR := FALSE;
  sSelectXATR := '';

  FOR vRec IN (SELECT FIELDNAME, COD, INDEXLOCAL
               FROM tmp_dinamic_cols
               ORDER BY INDEXLOCAL
              )
  LOOP
    vXATR := TRUE;
    sInsertPlus := coalesce(sInsertPlus,'') || ', ' || coalesce(vRec.FIELDNAME,'');
    sSelectPlus := coalesce(sSelectPlus,'') || ', coalesce(X.' || coalesce(vRec.FIELDNAME,'') || '*lg.cant/um.paritate,0) ' || coalesce(vRec.FIELDNAME,'');
    sSelectXATR := coalesce(sSelectXATR,'') || ', Max((case when A1.CODVALATR= ' || coalesce(vRec.COD::varchar ,'') || ' then 1 else 0 end)) ' || coalesce(vRec.FIELDNAME,'');
  END LOOP;

  sXATR := '
  X AS (
    SELECT I1.CODOBIECT' || coalesce(sSelectXATR,'') || '
    FROM IESIRI1_MAN I1
      INNER JOIN NATROBJ AO ON AO.CODOBIECT = I1.CODOBIECT
      LEFT  JOIN NARTATR AA ON AA.CODARTATR = AO.CODARTATR AND AA.CODATRIBUT IN (' || coalesce(sATRIB,'') || ')
      LEFT  JOIN NATRIB1 A1 ON A1.CODVALATR = AO.CODVALATR
    GROUP BY I1.CODOBIECT),';

  IF vXATR THEN
    sJoinPlus := coalesce(sJoinPlus,'') || '
    LEFT JOIN X ON x.codobiect = lg.codobiect';
  ELSE
    sXATR := '';
  END IF;

  sInsert :=
  'INSERT INTO ' || TMPNAME || ' (
    ART, UM, CANTDOC, CANTLIVR,
    PACH, PINREG, PVANZ,
    VALACH, VALINREG, VALVANZ,
    GESTIUNE, GESTORIG, LOCATIE, NRLIVR, DATALIVR, DENCARNET, SIMBCARNET, SERCARNET, OBSLIVR, GAR, DATAEXP, DATAPROD, CODINTERN, CODEXTERN,
    DENCLASAA, SIMBCLASAA, MASA, VOLUM, PRODUCATOR, FURNIZOR, ARTFURN, UM1, UM2, CANT1, CANT2,
    TIPSERIE, SERII, SER, SEROBS, SEROBSDIST, CERTIFSER, CERTIFSERD, DENIOART, SIMBCONT,
    PREFIXDOC, NRDOC, DATADOC, NRCERTIF, PUMAXIMAL, D1, D2, D3, DENCLASEAS, NRCOM, DATACOM, OBSDOC, CUSTODIE, CENTRUCOST,
    TIPLIVRARE,
    PMP, PMPVALUTA, PMPDOC, PMPVALUTADOC' || coalesce(sInsertPlus,'') || gUserFields || ' )';

  sSelect := '
  WITH ' || coalesce(sXatr,'') || '
  NSIN AS (
    SELECT distinct codnirstoc, codintr1, coddvi1 FROM
      (
      WITH RECURSIVE a (rootcodnirstoc, codnirstoc, codintr1, coddvi1, CODNIRSTOCPARINTE) AS (
          SELECT codnirstoc rootcodnirstoc, codnirstoc, codintr1, coddvi1, CODNIRSTOCPARINTE
          FROM nirstoc
          where CODNIRSTOC IN (SELECT DISTINCT l1.codnirstoc FROM livr l INNER JOIN livr1 l1 ON l1.codlivr = l.codlivr ' || coalesce(vAuxNSIN,'') || ')
          UNION ALL
          SELECT A.codnirstoc, a.CODNIRSTOCPARINTE codnirstoc, o.codintr1, O.coddvi1, o.CODNIRSTOCPARINTE
          FROM nirstoc O  inner join A ON o.codnirstoc = a.CODNIRSTOCPARINTE
          )
      SELECT rootcodnirstoc as codnirstoc, codintr1, coddvi1 FROM A WHERE codnirstocparinte IS NULL
      ) A_PG
  ),
  LG AS (
    SELECT
      l1.codlivr1,ns.codnirstoc,i1.codies, i1.codies1, i1.indexlocal, i1.codobiect,i1.codcmdint1,
      COALESCE(lv.gest, n.gest, 0) gest, COALESCE(l1.codgestorig, lv.gest, n.gest, 0) gestorig, ns.codlocatie, l1.umsec,
      i1.pu, i1.cant canti, i1.obs obsdoc, i1.garantie, l.carnetlivr, l.nrlivr, l.datalivr, l.obs obslivr, i1.codcentru,
      coalesce(ns.codioart,lv.codioart) codioart, ns.furn, ns.codgestprod gestfurn,
      SUM(coalesce(lv.pretinreg,ns.pret)*l1.cant) valinreg,
      SUM(coalesce(lv.pretachiz,ns.pret - ns.adaos)*l1.cant) valachiz,
      sum(l1.cant) cant, sum(l1.cantum1) cantum1, sum(l1.cantum2) cantum2, ns.d1, ns.d2, ns.d3,
      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,
      fnc_array_to_vc3200(array_agg(s.serie)) ser,
      fnc_array_to_vc3200(array_agg(nser.obs)) serobs,
      fnc_array_to_vc3200(array_agg(DISTINCT nser.obs)) serobsdist,
      coalesce(i1.pumaximal,max(coalesce(ns.pumaximal,0))) pumaximal,
      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 to_char(nser.dataprod,''dd.mm.yyyy''),'''          ||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''') dp,
      string_agg(DISTINCT int1.nrcertif,'''                                  ||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''') nrcertif,
      string_agg(DISTINCT c.nrcertif,'''                                     ||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''') certifser,
      string_agg(DISTINCT to_char(c.dataprimire,''dd.mm.yyyy''),'''          ||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''') certifserd,
      (case ns.tipserie when 1 then ''serie pe bucata'' when 2 then ''serie pe lot'' else ''fara serie'' end) tipserie,
      i1.tiplivrare,
      max(l1.pmp) pmp, max(l1.pmpvaluta) pmpvaluta, max(l1.pmpdoc) pmpdoc, max(l1.pmpvalutadoc) pmpvalutadoc,
      int1.codintr
    FROM IESIRI1_MAN i1
      INNER JOIN nartobj nao  ON nao.codobiect   = i1.codobiect
      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 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 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)
      LEFT JOIN nirser   nser ON nser.codnirser  = l1.codnirser
      LEFT JOIN nserii   s    on s.codserie      = nser.codserie
      LEFT JOIN certif   c    ON c.codcertif     = nser.codcertif' || coalesce(vWhere,'') || '
    GROUP BY
      l1.codlivr1,i1.codies, i1.codies1, i1.indexlocal, i1.codobiect, i1.cant, i1.garantie, i1.pu, i1.pumaximal, i1.obs,  i1.codcentru, i1.tiplivrare,
      l.carnetlivr, l.nrlivr, l.datalivr, l.obs, l1.umsec, lv.codioart, ns.codnirstoc, i1.codcmdint1,
      ns.codlocatie, ns.codioart, ns.furn, ns.codgestprod, ns.tipserie, ns.d1, ns.d2, ns.d3,
      COALESCE(lv.gest, n.gest, 0), COALESCE(l1.codgestorig, lv.gest, n.gest, 0), int1.codintr)
  SELECT
    nao.denumire, um.den_um1, lg.canti / um.paritate, lg.cant/um.paritate,
    (case when lg.cant=0 then 0 else lg.valachiz*um.paritate/lg.cant end), (case when lg.cant=0 then 0 else lg.valinreg*um.paritate/lg.cant end), lg.pu*um.paritate,
    lg.valachiz, lg.valinreg, lg.pu * lg.cant,
    ng.den_gest, ngo.den_gest, nl.denumire, lg.nrlivr, lg.datalivr, dc.denumire, dc.simbol, dc.serie, lg.obslivr, lg.garantie, lg.tg, lg.dp, nao.codintern, nao.codextern,
    ca.den_clasea, ca.simbol, nao.masa, nao.volum, prod.den_part,
    case when gfurn.codgest &gt; 0 then gfurn.den_gest else furn.den_part end, fobj.denumire,
    um1.den_um, um2.den_um, lg.cantum1, lg.cantum2,
    lg.tipserie, lg.serii, lg.ser, lg.serobs, lg.serobsdist, lg.certifser, lg.certifserd, io.den_ioart, nc.simbol,
    i.prefixdoc, i.nrdoc, i.datadoc, lg.nrcertif,
    CASE WHEN coalesce(nao1.tippretmax,0) IN (1,2,3) THEN lg.pumaximal WHEN coalesce(nao1.tippretmax,0) IN (4,5,6) THEN nao1.pretmaximal ELSE NULL END,
    lg.d1,lg.d2,lg.d3,cs.den_claseas,c.nrdoc,c.datadoc,lg.obsdoc, (case when i.custodie=1 then ''Da'' else ''Nu'' end), cec.denumire,
    (case lg.tiplivrare when 1 then ''Ridicata'' when 2 then ''Custodie'' when 3 then ''Nesosita'' when 4 then ''De ridicat'' end)' || coalesce(sPMP,'') || coalesce(sSelectPlus,'') || gUserAlias || '
  FROM lg
    INNER JOIN iesiri         i     ON i.codies         = lg.codies
    INNER JOIN nartobj        nao   ON nao.codobiect    = lg.codobiect
    INNER JOIN nart           na    ON na.codarticol    = nao.codarticol
    INNER JOIN num1           um    ON um.codum1        = lg.umsec
    INNER JOIN ngest          ng    ON ng.codgest       = lg.gest
    INNER JOIN ngest          ngo   ON ngo.codgest      = lg.gestorig
    LEFT  JOIN nirstoc        ns    on lg.codnirstoc    = ns.codnirstoc
    LEFT  JOIN nlocatii       nl    ON nl.codlocatie    = lg.codlocatie
    LEFT  JOIN doccarnete     dc    ON dc.codcarnet     = lg.carnetlivr
    LEFT  JOIN num            um1   ON um1.codum        = na.um1
    LEFT  JOIN num            um2   ON um2.codum        = na.um2
    LEFT  JOIN npart          prod  ON prod.codpart     = nao.codproducator
    LEFT  JOIN npart          furn  ON furn.codpart     = lg.furn
    LEFT  JOIN ngest          gfurn ON gfurn.codgest    = lg.gestfurn
    LEFT  JOIN nclasea        ca    ON ca.codclasea     = na.clasa
    LEFT  JOIN nclaseas       cs    ON cs.codclaseas    = na.clasastatist
    LEFT  JOIN ioart          io    ON io.codioart      = lg.codioart
    LEFT  JOIN ioart1         io1   ON io1.codioart     = lg.codioart  AND (i.an*12+i.luna) BETWEEN  io1.ALStart and  io1.ALStop
    LEFT  JOIN ncont          nc    ON nc.codcont       = io1.cont
    LEFT  JOIN nartobj1       nao1  ON nao1.codobiect   = lg.codobiect AND (i.an*12+i.luna) BETWEEN nao1.ALStart and nao1.ALStop
    LEFT  JOIN ieslink        il    ON il.codies1       = lg.codies1
    LEFT  JOIN comanda1       c1    ON c1.codcomanda1   = il.codliniecomanda
    LEFT  JOIN comanda        c     ON c.codcomanda     = c1.codcomanda
    LEFT  JOIN nartcli        fobj  ON fobj.codartcli   = PKG_LIST_BASE_UTILS_GetCodArtCli(lg.codobiect, lg.furn, furn.codclasa)
    LEFT  JOIN centrecost     cec   ON cec.codcentru    = lg.codcentru
    LEFT  JOIN tmp_utilizator ut    ON ut.codutilizator = i.userid ' || coalesce(sJoinPlus,'') || gSuplJoins || '
  ORDER BY lg.codies, lg.indexlocal';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
  PERFORM pkg_list_base_livrdoc_processparams();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_livrdoc_processparams</obj_name>
  <obj_hashval>e5f2d534e93d5c9ac3dc99aee0736651</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrdoc_processparams()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  vCodDoc     numeric;
  vTipDoc     numeric;
  vCodLocatie numeric;
  vPartener   numeric;
  vCodGest    NUMERIC := current_setting('PKG_LIST_BASE_LIVRDOC.vCodGest',  true)::NUMERIC;
  vCntFLivr    NUMERIC := current_setting('PKG_LIST_BASE_LIVRDOC.vCntFLivr', true)::NUMERIC;
  vCodIes      NUMERIC := current_setting('PKG_LIST_BASE_LIVRDOC.vCodIes',   true)::NUMERIC;
BEGIN
  --Florin 10.04.2024 - fixat 61640
  --Florin 21.06.2022 - sinc. Oracle
  --Laura 22.10.2021 - sinc Oracle (22.10.2021)
  --Adina 21 septembrie 2020
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  IF  COALESCE(getSUBUNITATE(), 0) = 0 THEN
    PERFORM pkg_globals_SetSubunitate(current_setting('PKG_LIST_BASE_LIVRDOC.vSubCur', true));
  END IF;

  FOR v_rec IN (SELECT G.DEN_GEST, NumePrenume(NP.Nume, NP.Prenume) GESTIONAR
                FROM   NGEST G
                      LEFT JOIN NPERS NP ON  G.CODGESTIONAR = NP.CODPERS
                WHERE G.CODGEST = vCodGest
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('GESTIUNE',            v_rec.Den_Gest);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('GESTIUNE GESTIONAR', v_rec.Gestionar);
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT   STRING_AGG(I.PREFIXDOC,',') PREFIXDOC,
                        STRING_AGG(I.NRDOC::varchar,',') NRDOC,
                        STRING_AGG(To_Char(I.DATADOC, 'dd.mm.yyyy'),',') DATADOC,
                        STRING_AGG(I.OBS,',') OBSDOC,
                        Min(i.CodIes) CODDOC, Min(i.TipDoc) TIPDOC
                FROM   (SELECT  DISTINCT codies FROM IESIRI1_MAN) tmp
                      INNER JOIN IESIRI I ON  i.codies = tmp.codies
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT',         v_rec.PrefixDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR',   v_rec.NrDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT DATA',   v_rec.DataDoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT OBS',     v_rec.ObsDoc);
    vCodDoc := v_rec.CodDoc;
    vTipDoc := v_rec.TipDoc;
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT   STRING_AGG(NrLivr::varchar,',') NRLIVR,
                        STRING_AGG(DataLivr,',') DATALIVR,
                        STRING_AGG(ObsLivr,',') OBSLIVR,
                        STRING_AGG(ZiLivr::varchar,',') ZILIVR
                FROM (SELECT  DISTINCT L.NRLIVR, To_Char(L.DATALIVR, 'dd.mm.yyyy') DATALIVR, L.OBS OBSLIVR, EXTRACT( DAY FROM L.DATALIVR) ZILIVR
                      FROM   IESIRI1_MAN tmp
                            INNER JOIN livr    l  ON  l.codies      = tmp.codies
                            INNER JOIN livr1   l1 ON  l1.codies1    = tmp.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
                      WHERE (vCntFLivr = 0 OR l.codlivr::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE UPPER(filtru) = 'CODLIVR')
                            )  AND (vCodGest= -1 OR  COALESCE(l1.CodGestOrig, lv.gest, n.Gest, 0) = vCodGest)
                     ) A_PG
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOC.LIVR.NUMAR',   v_rec.NrLivr);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOC.LIVR.DATA',   v_rec.DataLivr);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOC.LIVR.OBS',     v_rec.ObsLivr);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOC.LIVR.ZI',     v_rec.ZiLivr);
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT   n.nume, n.prenume, n.cnp, d.delegat, d.doc DELDOC, d.nrdoc NRDOCTRANSP, d.seriedoc,
                        d.eliberat, d.cnp DELCNP, d.mijltransp, d.nrtransp, d.datadoc DELDATADOC,
                        A.NUME NUMEA, A.PRENUME PRENUMEA, A.CNP CNPA
                FROM   IESIRI I
                      LEFT JOIN NPERS   N ON  I.USERID  = N.LOGONNAME
                      LEFT JOIN NPARTTR D ON  I.DELEGAT = D.CODPARTTR
                      LEFT JOIN NPERS   A ON  A.CODPERS = I.AGENT
                WHERE i.codies = vCodDoc
               )
  LOOP
    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('Agent nume ',          v_rec.NUMEA);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Agent prenume',          v_rec.PRENUMEA);
       PERFORM pkg_list_Struct_ADAUGA_PARAM('Agent CNP',            v_rec.CNPA);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DELEGAT',         v_rec.DELEGAT);
    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.NRDOCTRANSP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT SERIE DOCUMENT',   v_rec.SERIedoc);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DOC ELIBERAT',     v_rec.ELIBERAT);
    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.MIJLTRANSP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT NR MIJLOC',       v_rec.NRTRANSP);
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT SUM(L1.CANT * COALESCE(O.MASA, 0)) MASA, SUM(L1.CANT * COALESCE(O.Volum, 0)) VOLUM
                FROM   LIVR L
                      INNER JOIN LIVR1   L1 ON  L.CODLIVR     = L1.CODLIVR
                      INNER JOIN IESIRI1 I1 ON  I1.CODIES1    = L1.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
                      INNER JOIN NARTOBJ O  ON  O.CODOBIECT   = I1.CODOBIECT
                WHERE L.CODIES = vCodIes AND (vCodGest = -1 OR  COALESCE(l1.CodGestOrig, lv.gest, n.Gest, 0) = vCodGest)
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MASA FACTURATA', TO_CHAR(v_rec.Masa, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VOLUM FACTURAT', TO_CHAR(v_rec.Volum,'fm9G999G999G990D00'));
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT   PK.NRDOC, DC.SERIE, PK.NRPACHETE, PK.IDENTIFICATORP, PK.DATAP,
                        Numeprenume(PC.NUME, PC.PRENUME) PCC,
                        Numeprenume(PV.NUME, PV.PRENUME) PVV,
                        Numeprenume(PT.NUME, PT.PRENUME) PTT,
                        PK.DATACOLECTARE, PK.DATAVERIFICARE, PK.DATATRANSPORT
                FROM   IESIRI I
                      LEFT JOIN PACHETE1   PK1 ON  I.CODIES         = PK1.CODDOC AND  PK1.TIPDOC = I.TipDoc
                      LEFT JOIN PACHETE    PK  ON  PK1.CODPACHETE   = PK.CODPACHETE
                      LEFT JOIN DOCCARNETE DC  ON  PK.CARNETDOC     = DC.CODCARNET
                      LEFT JOIN NPERS      PC  ON  PK.COLECTOR      = PC.CODPERS
                      LEFT JOIN NPERS      PV  ON  PK.VERIFICATOR   = PV.CODPERS
                      LEFT JOIN NPERS      PT  ON  PK.TRANSPORTATOR = PT.CODPERS
                WHERE I.CODIES = vCodDoc
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET SERIE',                   v_rec.SERIE);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET NUMAR',                   v_rec.NRDOC::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET NUMAR PACHETE',           v_rec.NRPACHETE::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET DATA',                     to_char(v_rec.DATACOLECTARE,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET Identificator',           v_rec.IDENTIFICATORP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET PERSOANA COLECTARE',       to_char(v_rec.DATACOLECTARE,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET DATA COLECTARE',           v_rec.PCC);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET PERSOANA VERIFICATOARE',   v_rec.PVV);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET DATA VERIFICARE',         to_char(v_rec.DATAVERIFICARE,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET TRANSPORT PERSOANA',       v_rec.PTT);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET TRANSPORT DATA',           to_char(v_rec.DATATRANSPORT,'dd.mm.yyyy'));
    EXIT ;
  END LOOP;

  IF vTipDoc IN (19, 20, 21, 22, 26) THEN
    SELECT CODLOCATIE, PARTENER
    INTO vCodLocatie, vPartener
    FROM IESIRI
    WHERE CodIes = vCodDoc;

   FOR v_rec IN (
      SELECT
        PB.CONTBANCA, B.DENUMIRE, B.SIMBOL, I.VALDOC, I.TVADOC
      FROM IESIRI I
        LEFT JOIN NPARTB PB ON PB.CODPART = I.PARTENER AND PB.IMPLICIT = 1
        LEFT JOIN NBANK B ON B.CODBANK = PB.CODBANK
      WHERE I.CODIES = vCodDoc
    ) LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT CONT', v_rec.CONTBANCA);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT BANCA', v_rec.DENUMIRE);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT SIMBOL BANCA', v_rec.SIMBOL);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA', TO_CHAR(TRUNC(COALESCE(v_rec.TVADOC,0), 2)));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VALOARE', TO_CHAR(TRUNC(COALESCE(v_rec.VALDOC,0)-COALESCE(v_rec.TVADOC,0), 2)));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL', TO_CHAR(TRUNC(COALESCE(v_rec.VALDOC,0), 2)));
      EXIT;
    END LOOP;

    FOR v_rec IN (SELECT   A.Obs, J.Den_Judet, A.TELEFON,
                          fnc_GetAdresa(A.sector, A.strada, A.nr1, A.nr2, A.bloc, A.scara, A.etaj, A.apart, A.codpostal) AS ADRESA,
                          L.DEN_LOCALIT, J.SIMBAUTO, A.CODCLIENT
                  FROM   NAGENDA A
                        LEFT JOIN NLOCALIT L ON  A.CODLOCALIT = L.CODLOCALIT
                        LEFT JOIN NJUDET   J ON  L.CODJUDET   = J.CODJUDET
                  WHERE CODAGENDA = vCodLocatie
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE ADRESA',         v_rec.Adresa);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE DENUMIRE',       v_rec.OBS);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE LOCALITATE',     v_rec.Den_Localit);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE JUDET',         v_rec.DEN_JUDET);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE TELEFON',       v_rec.Telefon);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE COD LA CLIENT', v_rec.CodClient);
      EXIT ;
    END LOOP;

    FOR v_rec IN (SELECT   P.DEN_PART, C.CODFISCAL, P.AUTORIZATIE, A.OBS, L.DEN_LOCALIT, J.Den_Judet,
                          CASE WHEN  P.PERSOANAFIZICA=1 THEN NULL ELSE  P.REGCOM END  REGCOM,
                          coalesce(PC.NUME,'') || ' ' || coalesce(PC.PRENUME,'') PERSC
                  FROM   NPART P
                        LEFT JOIN NPARTCODFISC C  ON  C.CODPART    = P.CODPART AND  C.PRINCIPAL = 1
                        LEFT JOIN NAGENDA      A  ON  A.CODPART    = P.CODPART AND  COALESCE(a.Inactiv, 0) = 0 AND A.SEDIUSOCIAL IN (4, 5, 6, 7)
                        LEFT JOIN NLOCALIT     L  ON  A.CODLOCALIT = L.CODLOCALIT
                        LEFT JOIN NJUDET       J  ON  L.CODJUDET   = J.CODJUDET
                        LEFT JOIN NPERSCONTACT PC ON  PC.CODPART   = P.CODPART
                  WHERE P.CODPART = vPartener
                  )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT DENUMIRE',                   v_rec.Den_Part);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT COD FISCAL',                 v_rec.CodFiscal);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT REGISTRU COMERT',             v_rec.RegCom);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT AUTORIZATIE SPECIALA',       v_rec.Autorizatie);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT SEDIU SOCIAL',               v_rec.Obs);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT LOCALITATE SEDIU SOCIAL',     v_rec.Den_Localit);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT JUDET SEDIU SOCIAL',         v_rec.Den_Judet);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT PERSOANA CONTACT IMPLICITA', v_rec.PersC);
      EXIT ;
    END LOOP;
  ELSIF vTipDoc = 12 THEN  -- parametrii transfer
    NULL;
  ELSIF vTipDoc = 24 THEN -- parametrii consum intern
    FOR v_rec IN (SELECT CASE coalesce(TIPCONSUMATOR,0)
                           WHEN 1 THEN 'GESTIUNE'
                           WHEN 2 THEN 'PERSOANA'
                           WHEN 3 THEN  'AUTO'
                         END TIPCONSUMATOR,
                         CASE coalesce(TIPCONSUMATOR,0)
                           WHEN 1 THEN G.DEN_GEST
                           WHEN 2 THEN NumePrenume(P.NUME,P.PRENUME)
                           WHEN 3 THEN OB.DENUMIRE||'-'||PA.NRINREG
                         END CONSUMATOR
                  FROM IESIRI I
                      LEFT JOIN NGEST    G  ON I.CODGESTPROD = G.CODGEST
                      LEFT JOIN NPERS    P  ON I.CODPERS     = P.CODPERS
                      LEFT JOIN NPARCAUT PA ON I.CODAUTO     = PA.CODNPARCAUT
                      LEFT JOIN NARTOBJ  OB ON PA.CODART     = OB.CODOBIECT
                  WHERE CODIES  = vCodDoc
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TIP CONSUMATOR'         , v_rec.TIPCONSUMATOR);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CONSUMATOR'             , v_rec.CONSUMATOR);
      EXIT;
    END LOOP;

  ELSIF vTipDoc = 23 THEN -- parametrii subunitati
    FOR v_rec IN (SELECT S.Den_Subunit, L.DEN_LOCALIT, S.RegCom, BK.DENUMIRE as banca, BC.nrCONT as contbanca,
                         fnc_GetAdresa(A.sector, A.strada, A.nr1, A.nr2, A.bloc, A.scara, A.etaj, A.apart, A.codpostal) ADRESA,
                         S.CIF
                  FROM IESIRI I
                    LEFT JOIN NSUBUNIT  S  ON I.CODSUBUNIT  = S.CODSUBUNIT
                    LEFT JOIN NAGENDA   A  ON S.CODSUBUNIT  = A.CODSUBUNIT
                    LEFT JOIN nbankcont BC ON S.codbankcont = BC.codbankcont
                    LEFT JOIN nbank     BK ON BC.codbank    = BK.codbank
                    LEFT JOIN NLOCALIT  L  ON A.CODLOCALIT  = L.CODLOCALIT
                  WHERE I.Codies = vCodDoc
                 )
    LOOP
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SUBUNITATE DESTINATIE DENUMIRE'   , v_rec.DEN_SUBUNIT);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SUBUNITATE DESTINATIE LOCALITATE' , v_rec.DEN_LOCALIT);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('SUBUNITATE DESTINATIE ADRESA'     , v_rec.ADRESA);
      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 BANCA'      , v_rec.banca);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Subunitate DESTINATIE CONT'       , v_rec.contbanca);
      EXIT;
    END LOOP;
  END IF;

  PERFORM pkg_list_Struct_ADAUGA_PARAM_EXT('IESIRIEXT', 'CODIES', vCodDoc, '');
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_livrsimpl_processlist</obj_name>
  <obj_hashval>035982b43b9a2f8ef84d9f115a7bc30c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrsimpl_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sSelectIes  varchar;
  sSelectT    varchar;
  sSelectInt  varchar;
  sCondDataI  varchar;
  sCondDataT  varchar;
  sJoinUM     varchar;
  vFiltru     varchar;
  sTipIes     varchar;
  sTipIntr    varchar;
  sTipT       varchar;
  vFiltruIes  varchar;
  vFiltruIntr varchar;
  vFiltruT    varchar;
  gSuplCols   varchar := 'livr l, iesiri ies, intrari intr, transf t, livr1 l1, livrval lv, nirstoc ns, nir n, num1 u1, nartobj nao, nart na, NUM UM1, NUM UM2, ngest g, nlocatii nl, nsubunit ss, doccarnete dc, '||
                         'ioart io, ioart1 io1, ncont nc, ioart ioi, npart np, ngest gd, nsubunit sd';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 10.02.2022 - sinc. Oracle
  --Adina 09.03.2021 - prc_al_check
  --Adina 25.02.2021 - sinc.Oracle din 23.02.2021
  --Florin 14.08.2020
  --Adina 27.11.2020 tichet 41312
  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 = 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_LIVRSIMPL.gSuplCols', gSuplCols,false);

  CALL PRC_AL_CHECK('ioart1');

  IF current_setting('PKG_LIST_SELLIVRARI.vTipData', TRUE)::NUMERIC = 2 THEN
    vFiltruIes := '
      AND ies.an*12+ies.luna ' || current_setting('PKG_LIST_SELLIVRARI.vPerioada', TRUE);
    vFiltruIntr := '
      AND intr.an*12+intr.luna ' || current_setting('PKG_LIST_SELLIVRARI.vPerioada', TRUE);
    vFiltruT := '
      AND t.an*12+t.luna ' || current_setting('PKG_LIST_SELLIVRARI.vPerioada', TRUE);
  ELSIF current_setting('PKG_LIST_SELLIVRARI.vTipData', TRUE):: NUMERIC = 1 THEN
    vFiltruIes := '
      AND ies.datadoc ' || current_setting('PKG_LIST_SELLIVRARI.vPerioada', TRUE);
    vFiltruIntr := '
      AND intr.datadoc ' || current_setting('PKG_LIST_SELLIVRARI.vPerioada', TRUE);
    vFiltruT := '
      AND t.datadoc ' || current_setting('PKG_LIST_SELLIVRARI.vPerioada', TRUE);
  ELSE
    vFiltru := '
      AND l.datalivr ' || current_setting('PKG_LIST_SELLIVRARI.vPerioada', TRUE);
  END IF;

  IF current_setting('PKG_LIST_SELLIVRARI.vToateGest', TRUE)::NUMERIC = 0 THEN
    vFiltru := coalesce(vFiltru,'') || '
      AND COALESCE(l1.codgestorig, lv.gest, n.gest)::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' ) ';
  END IF;

  IF current_setting('PKG_LIST_SELLIVRARI.vToateArt', TRUE)::NUMERIC = 0 THEN
    vFiltru := coalesce(vFiltru,'') || '
      AND Coalesce(lv.codobiect, ns.codobiect)::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' ) ';
  END IF;

  IF current_setting('PKG_LIST_SELLIVRARI.vUm', TRUE)::NUMERIC = 0 THEN
    sJoinUM := '
      LEFT  JOIN num1 u1            ON u1.codum1       = l1.umsec';
  ELSE
    sJoinUM := '
      LEFT  JOIN num1 u1            ON u1.codum        = na.um AND secundara = 0';
  END IF;

  IF current_setting('PKG_LIST_SELLIVRARI.vToateDoc', TRUE)::NUMERIC = 1 THEN
    SELECT STRING_AGG(tipdoc::varchar, ',')
    INTO sTipIntr
    FROM (SELECT DISTINCT tipdoc FROM intrari) A_PG
    WHERE TIPDOC &lt;&gt; 9;

    SELECT STRING_AGG(tipdoc::varchar, ',')
    INTO sTipIes
    FROM (SELECT DISTINCT tipdoc FROM iesiri) B_PG
    WHERE TIPDOC &lt;&gt; 26;

    SELECT STRING_AGG(tipdoc::varchar, ',')
    INTO sTipT
    FROM (SELECT DISTINCT tipdoc FROM transf) C_PG;
  ELSE
    SELECT STRING_AGG(tipdoc::varchar, ',')
    INTO sTipIntr
    FROM (SELECT DISTINCT tipdoc FROM intrari) D_PG
    WHERE TIPDOC::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'TIPDOC');

    SELECT STRING_AGG(tipdoc::varchar, ',')
    INTO sTipIes
    FROM (SELECT DISTINCT tipdoc FROM iesiri) E_PG
    WHERE TIPDOC::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'TIPDOC');

    SELECT STRING_AGG(tipdoc::varchar, ',')
    INTO sTipT
    FROM (SELECT DISTINCT tipdoc FROM transf) F_PG
    WHERE TIPDOC::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'TIPDOC');
  END IF;

  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(
      NAV_CodDoc, NAV_TipDoc,
      DenArt, DenUM, DenGest, DenLGest, SimbolCont,
      Document, PrefixDoc, NrDoc, DataDoc, NumeDoc,
      DocLivr, NrLivr, DataLivr, DenCarnetLivr, SimbCarnetLivr, SerCarnetLivr,
      CantLivr, PInreg, PretAch,
      Destinatie,
      DenIOART, UM1,UM2,CantUM1,CantUM2, MASA,VOLUM,
      DataAchiz, STipDoc, AnDoc,LunaDoc, Luna,
      IOARTInterm ' || gUserFields || ')';
  sSelectIes := '
    SELECT
      ies.codies NAV_CodDoc, ies.tipdoc NAV_TipDoc,
      nao.denumire DenArt, u1.den_um1 DenUM, g.den_gest DenGest, nl.denumire DenLGest, nc.simbol SimbolCont,
      ies.prefixdoc||''.''||ies.nrdoc||'' / ''||to_char(ies.datadoc,''dd.mm.yyyy'') as Document, ies.PrefixDoc, ies.NrDoc, ies.DataDoc,
      (SELECT PKG_LIST_BASE_UTILS_decode_tipdoc.wme_result from PKG_LIST_BASE_UTILS_decode_tipdoc(NULL, ies.tipdoc)) NumeDoc,
      ''LIVR ''||l.nrlivr||'' / ''||to_char(l.datalivr,''dd.mm.yyyy'') DocLivr, l.NrLivr, l.DataLivr, dc.denumire DenCarnetLivr, dc.simbol SimbCarnetLivr, dc.serie SerCarnetLivr,
      l1.cant / u1.paritate, Coalesce(lv.pretinreg,ns.pret) * u1.paritate * CASE WHEN ies.tipdoc = 15 THEN -1 ELSE 1 END PInreg, Coalesce(lv.pretachiz,ns.pret - ns.adaos) * u1.paritate * CASE WHEN ies.tipdoc = 15 THEN -1 ELSE 1 END PretAch,
      CASE WHEN ies.tipdoc IN (15,16) THEN ''-'' WHEN ies.tipdoc = 23 THEN sd.den_subunit WHEN ies.tipdoc = 24 THEN gd.den_gest ELSE np.den_part END Destinatie,
      io.den_ioart DenIOART, um1.den_um UM1, um2.den_um UM2, l1.CantUM1, l1.CantUM2, nao.masa, nao.volum,
      ns.DataAchiz, pkg_list_base_utils_decode_tipdoc_scurt(ies.tipdoc) STipDoc, 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,
      ioi.den_ioart IOARTInterm' || gUserAlias || '
    FROM livr l
      INNER JOIN iesiri ies         ON ies.codies      = l.codies AND l.tiplivr = ies.tipdoc
      LEFT  JOIN intrari intr       ON intr.codintr    = 0
      LEFT  JOIN transf t           ON t.codtransf     = 0
      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
      LEFT  JOIN nartobj nao        ON nao.codobiect   = Coalesce(lv.codobiect, ns.codobiect)
      LEFT  JOIN nart na            ON na.codarticol   = nao.codarticol' || coalesce(sJoinUM,'') || '
      LEFT  JOIN NUM UM1            ON um1.codum       = na.um1
      LEFT  JOIN NUM UM2            ON um2.codum       = na.um2
      LEFT  JOIN ngest g            ON g.codgest       = Coalesce(lv.gest, n.gest, 0)
      LEFT  JOIN nlocatii nl        ON nl.codlocatie   = ies.codlocatie
      LEFT  JOIN nsubunit ss        ON ss.codsubunit   = ies.subunitatea
      LEFT  JOIN doccarnete dc      ON dc.codcarnet    = l.carnetlivr
      LEFT  JOIN ioart io           ON io.codioart     = Coalesce(lv.codioart,ns.codioart)
      LEFT  JOIN ioart1         io1 ON io1.codioart    = io.codioart AND io1.alstart &lt;= ies.an*12+ies.luna AND io1.alstop &gt;= ies.an*12+ies.luna
      LEFT  JOIN ncont nc           ON nc.codcont      = io1.cont
      LEFT  JOIN ioart ioi          ON ioi.codioart    = Coalesce(NULLIF(l1.contintermed,0),ies.contintermed,0)
      LEFT  JOIN npart np           ON np.codpart      = ies.partener
      LEFT  JOIN ngest gd           ON gd.codgest      = ies.codgestprod
      LEFT  JOIN nsubunit sd        ON sd.codsubunit   = ies.codsubunit' || gSuplJoins || '
  WHERE (l.codies IS NOT NULL) AND (l.operat = 1) AND (l.anulat = 0)
      AND l.tiplivr  IN (' || coalesce(sTipIes,'') || ')
      AND ies.tipdoc IN (' || coalesce(sTipIes,'') || ') ' || coalesce(vFiltru,'') || coalesce(vFiltruIes,'')
      || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'IES',NULL,NULL,NULL)),'') || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_USERID.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_USERID(NULL,'IES',NULL,NULL)),'');
  sSelectInt := '
    SELECT
      intr.codintr NAV_CodDoc, intr.tipdoc NAV_TipDoc,
      nao.denumire DenArt, u1.den_um1 DenUM, g.den_gest DenGest, nl.denumire DenLGest, nc.simbol SimbolCont,
      intr.prefixdoc||''.''||intr.nrdoc||'' / ''||to_char(intr.datadoc,''dd.mm.yyyy'') as Document, intr.PrefixDoc, intr.NrDoc, intr.DataDoc,
      (SELECT PKG_LIST_BASE_UTILS_decode_tipdoc.wme_result FROM PKG_LIST_BASE_UTILS_decode_tipdoc(NULL, intr.tipdoc)) NumeDoc,
      ''LIVR ''||l.nrlivr||'' / ''||to_char(l.datalivr,''dd.mm.yyyy'') DocLivr, l.NrLivr, l.DataLivr, dc.denumire DenCarnetLivr, dc.simbol SimbCarnetLivr, dc.serie SerCarnetLivr,
      l1.cant / u1.paritate, Coalesce(lv.pretinreg,ns.pret) * u1.paritate * CASE WHEN intr.tipdoc = 15 THEN -1 ELSE 1 END PInreg, Coalesce(lv.pretachiz,ns.pret - ns.adaos) * u1.paritate * CASE WHEN intr.tipdoc = 15 THEN -1 ELSE 1 END PretAch,
      CASE WHEN intr.tipdoc = 6 THEN sd.den_subunit WHEN intr.tipdoc = 7 THEN gd.den_gest ELSE np.den_part END Destinatie,
      io.den_ioart DenIOART, um1.den_um UM1, um2.den_um UM2, l1.CantUM1, l1.CantUM2, nao.masa, nao.volum,
      ns.DataAchiz, pkg_list_base_utils_decode_tipdoc_scurt(intr.tipdoc) STipDoc, intr.an AnDoc, intr.luna LunaDoc, to_char(intr.an,''fm0000'')||''.''||to_char(intr.luna,''fm00'')||''.''||pkg_list_base_utils_decode_luna(intr.Luna) Luna,
      ioi.den_ioart IOARTInterm' || gUserAlias || '
    FROM livr l
      INNER JOIN intrari intr       ON intr.codintr    = l.codintr AND intr.tipdoc = l.tiplivr
      LEFT  JOIN iesiri ies         ON ies.codies      = 0
      LEFT  JOIN transf t           ON t.codtransf     = 0
      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
      LEFT  JOIN nartobj nao        ON nao.codobiect   = Coalesce(lv.codobiect, ns.codobiect)
      LEFT  JOIN nart na            ON na.codarticol   = nao.codarticol' || coalesce(sJoinUM,'') || '
      LEFT  JOIN NUM UM1            ON um1.codum       = na.um1
      LEFT  JOIN NUM UM2            ON um2.codum       = na.um2
      LEFT  JOIN ngest g            ON g.codgest       = Coalesce(lv.gest, n.gest, 0)
      LEFT  JOIN nlocatii nl        ON nl.codlocatie   = intr.codlocatie
      LEFT  JOIN nsubunit ss        ON ss.codsubunit   = intr.subunitatea
      LEFT  JOIN doccarnete dc      ON dc.codcarnet    = l.carnetlivr
      LEFT  JOIN ioart io           ON io.codioart     = Coalesce(lv.codioart,ns.codioart)
      LEFT  JOIN ioart1         io1 ON io1.codioart    = io.codioart AND io1.alstart &lt;= intr.an*12+intr.luna AND io1.alstop &gt;= intr.an*12+intr.luna
      LEFT  JOIN ncont nc           ON nc.codcont      = io1.cont
      LEFT  JOIN ioart ioi          ON ioi.codioart    = 0
      LEFT  JOIN npart np           ON np.codpart      = intr.partener
      LEFT  JOIN ngest gd           ON gd.codgest      = intr.codgestprod
      LEFT  JOIN nsubunit sd        ON sd.codsubunit   = intr.codsubunit' || gSuplJoins || '
    WHERE (l.codintr IS NOT NULL) AND (l.operat = 1) AND (l.anulat = 0)
      AND l.tiplivr   IN (' || coalesce(sTipIntr,'') || ')
      AND intr.tipdoc IN (' || coalesce(sTipIntr,'') || ') ' || coalesce(vFiltru,'') || coalesce(vFiltruIntr,'')
      || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'INTR',NULL,NULL,NULL)),'')
      || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_USERID.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_USERID(NULL,'INTR',NULL,NULL)),'');
  sSelectT := '
    SELECT
      t.codtransf NAV_CodDoc, t.tipdoc NAV_TipDoc,
      nao.denumire DenArt, u1.den_um1 DenUM, g.den_gest DenGest, nl.denumire DenLGest, nc.simbol SimbolCont,
      t.prefixdoc||''.''||t.nrdoc||'' / ''||to_char(t.datadoc,''dd.mm.yyyy'') as Document, t.PrefixDoc, t.NrDoc, t.DataDoc,
      (SELECT PKG_LIST_BASE_UTILS_decode_tipdoc.wme_result FROM PKG_LIST_BASE_UTILS_decode_tipdoc(NULL, t.tipdoc)) NumeDoc,
      ''LIVR ''||l.nrlivr||'' / ''||to_char(l.datalivr,''dd.mm.yyyy'') DocLivr, l.NrLivr, l.DataLivr, dc.denumire DenCarnetLivr, dc.simbol SimbCarnetLivr, dc.serie SerCarnetLivr,
      l1.cant / u1.paritate, Coalesce(lv.pretinreg,ns.pret) * u1.paritate * CASE WHEN t.tipdoc = 15 THEN -1 ELSE 1 END PInreg, Coalesce(lv.pretachiz,ns.pret - ns.adaos) * u1.paritate * CASE WHEN t.tipdoc = 15 THEN -1 ELSE 1 END PretAch,
      gd.den_gest||CASE WHEN Coalesce(nld.codlocatie,0) &lt;&gt; 0 THEN '' (''||nld.denumire||'')'' END Destinatie,
      io.den_ioart DenIOART, um1.den_um UM1, um2.den_um UM2, l1.CantUM1, l1.CantUM2, nao.masa, nao.volum,
      ns.DataAchiz, pkg_list_base_utils_decode_tipdoc_scurt(t.tipdoc) STipDoc, t.an AnDoc, t.luna LunaDoc, to_char(t.an,''fm0000'')||''.''||to_char(t.luna,''fm00'')||''.''||pkg_list_base_utils_decode_luna(t.Luna) Luna,
      ioi.den_ioart IOARTInterm' || gUserAlias || '
    FROM livr l
      INNER JOIN transf t           ON t.codtransf     = l.codtransf AND l.tiplivr = t.tipdoc
      LEFT  JOIN iesiri ies         ON ies.codies      = 0
      LEFT  JOIN intrari intr       ON intr.codintr    = 0
      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
      LEFT  JOIN nirstoc nsd        ON nsd.codlivr1    = l1.codlivr1
      LEFT  JOIN nir nd             ON nd.codnir       = nsd.codnir
      LEFT  JOIN nartobj nao        ON nao.codobiect   = Coalesce(lv.codobiect, ns.codobiect)
      LEFT  JOIN nart na            ON na.codarticol   = nao.codarticol' || coalesce(sJoinUM,'') || '
      LEFT  JOIN NUM UM1            ON um1.codum       = na.um1
      LEFT  JOIN NUM UM2            ON um2.codum       = na.um2
      LEFT  JOIN ngest g            ON g.codgest       = Coalesce(lv.gest, n.gest, 0)
      LEFT  JOIN nlocatii nl        ON nl.codlocatie   = ns.codlocatie
      LEFT  JOIN nsubunit ss        ON ss.codsubunit   = t.subunitatea
      LEFT  JOIN doccarnete dc      ON dc.codcarnet    = l.carnetlivr
      LEFT  JOIN ioart io           ON io.codioart     = Coalesce(lv.codioart,ns.codioart)
      LEFT  JOIN ioart1         io1 ON io1.codioart    = io.codioart AND io1.alstart &lt;= t.an*12+t.luna AND io1.alstop &gt;= t.an*12+t.luna
      LEFT  JOIN ncont nc           ON nc.codcont      = io1.cont
      LEFT  JOIN ioart ioi          ON ioi.codioart    = 0
      LEFT  JOIN npart np           ON np.codpart      = 0
      LEFT  JOIN ngest gd           ON gd.codgest      = nd.gest
      LEFT  JOIN nlocatii nld       ON nld.codlocatie  = nsd.codlocatie
      LEFT  JOIN nsubunit sd        ON sd.codsubunit   = 0' || gSuplJoins || '
    WHERE (l.codtransf IS NOT NULL) AND (l.operat = 1) AND (l.anulat = 0)
      AND l.tiplivr IN (' || coalesce(sTipT,'') || ')
      AND t.tipdoc  IN (' || coalesce(sTipT,'') || ') ' || coalesce(vFiltru,'') || coalesce(vFiltruT,'')
      || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'T',NULL,NULL,NULL)),'')
      || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_USERID.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_USERID(NULL,'T',NULL,NULL)),'');
  PERFORM pkg_globals_SetDebugMode(TRUE);

  IF sTipIes IS NOT NULL THEN
    --INSERT INTO x (view_name, test) VALUES ('liv1', coalesce(sInsert,'') || coalesce(sselecties,''));
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sselecties,''), aListID, aListVer);
  END IF;

  IF sTipIntr IS NOT NULL THEN
    --INSERT INTO x (view_name, test) VALUES ('liv2', coalesce(sInsert,'') || coalesce(sselectint,''));
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sselectint,''), aListID, aListVer);
  END IF;

  IF sTipT IS NOT NULL THEN
    --INSERT INTO x (view_name, test) VALUES ('liv1', coalesce(sInsert,'') || coalesce(sselectt,''));
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sselectt,''), aListID, aListVer);
  END IF;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz2_processlist</obj_name>
  <obj_hashval>2278338485e03034791545bed5f34ffb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz2_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert           varchar := '';
  sSelect           varchar := '';
  sColMinMax         varchar := ', NAOS.STOCMIN, NAOS.STOCMED, NAOS.STOCMAX';
  vAux               varchar := '';
  vSelStocReal       varchar := '';
  vSelStocInit       varchar := '';
  vSelIes_Per       varchar := '';
  vSelIes_Prec      VARCHAR(3000);
  vSelTr_Per         varchar := '';
  vSelIes_Emul       varchar := '';
  vAnPrec           numeric;
  vLunaPrec         numeric;
  vZiuaFin          date := to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', true),'dd.mm.yyyy');
  vZiuaIni          date := to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', true),'dd.mm.yyyy');
  vNrLuni           NUMERIC := extract( year FROM vZiuaFin) * 12 + extract( month FROM vZiuaFin) - extract( year FROM vZiuaIni) * 12 - extract( month FROM vZiuaIni) + 1;
  vNrZilePer         NUMERIC := to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', true),'dd.mm.yyyy') - to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', true),'dd.mm.yyyy') + 1;
  vCateGest         NUMERIC := 0;
  vCateLGest         NUMERIC := 0;
  vCondSub_C         varchar := '';
  vCondSub_CS       varchar := '';
  vCondSub_G         varchar := '';
  sUltNirstoc       varchar := '';
  vUserID           numeric;
  sAfectare         varchar := '';
  pUsername         varchar := '';
  pStocExternFirma   varchar := COALESCE(fnc_GetValConstanta('StocExternFirma', getANLUCRU(), getlunalucru()),'');
  pStocExternCamp   varchar := PKG_LIST_BASE_UTILS_Get_StocExternCamp();
  vFiltruTermen     varchar := '';
  Luni               numeric;
  vAnV               numeric;
  vLunaV             numeric;
  vZiV               NUMERIC(2);
  sLuna             varchar := '';
  sJoinRestCmd       varchar := '';
  sJoinSub          varchar(1000);
  vCodIdent         varchar := '';
  oSkema            varchar(100);
  acount            NUMERIC(20);
  vZiuaIniP         date;
  vZiuaFinP         date;
  gSuplCols         VARCHAR := '';
   gUserFields       VARCHAR := '';
  gUserAlias        VARCHAR := '';
  gNullAlias        VARCHAR := '';
  gSuplJoins        VARCHAR := '';
  vZiuaFinC          date := to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFinC', true),'dd.mm.yyyy');
  vZiuaIniC          date := to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIniC', true),'dd.mm.yyyy');
  vDefalcare         boolean := current_setting('PKG_LIST_BASE_NAPROVIZ2.vDefalcare', true)::boolean;
  vStocuriGest       boolean := current_setting('PKG_LIST_BASE_NAPROVIZ2.vStocuriGest', true)::boolean;
  v_sub              record;
  vSub               NUMERIC(20);
BEGIN
  --Florin 18/21.02.2025 - fixat 64791
  --Florin 05.02.2025 - sinc. Oracle
  --Florin 26.03.2024 - fixat vAllCls
  --Florin 27.10.2023 - sinc. Oracle
  --Florin 12.10.2023 - fixat 59687
  --Florin 11.08.2023 - fixat 59133
  --Florin 28.07.2023 - fixat 59027
  --Florin 26.07.2023 - fixat 58998
  --Florin 03/17.07.2023 - fixat 58574
  --Florin 26.06.2023 - fixat 58675
  --Florin 12.06.2023 - sinc. Oracle
  --Florin 01.06.2023 - sinc. Oracle (29.05.2023)
  --Florin 30.05.2023 - fixat 58456
  --Florin 17.11.2022 - fixat 56296
  --Florin 27.09.2022 - fixat 55715
  --Florin 19.09.2022 - sinc. Oracle (08.09.2022)
  --Florin 01.09.2021 - sinc. Oracle (03.08.2021)
  --Adina 30.06.2021 - modif.param.fct.pkg_list_selfisamag_setallparams din bool in numeric
  --Adina 20.04.2021 - sinc.Oracle
  --Adina 08.12.2020 tuning - adaugat index la tmp_stocreal
  --Adina 28 august 2020
  IF  vNrLuni &lt;= 0     THEN  vNrLuni := 1;    END IF;
  IF  vNrZilePer &lt;= 0 THEN  vNrZilePer := 1; END IF;

  vUserId     := COALESCE(current_setting('PKG_GLOBALS.USERID', true)::numeric, 0);
  vCondSub_C  := COALESCE(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'');
  vCondSub_CS := COALESCE(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C', 'SubunitSursa',NULL,NULL),'');
  vCondSub_G  := COALESCE(PKG_LIST_BASE_UTILS_COND_SUBUNIT('G', 'CODSUBUNIT'  ,NULL,NULL),'');
  DELETE FROM tmp_stocreal;

  IF  tmpName &lt;&gt; 'TMP_LST_NAPR2' THEN
    gSuplCols :=  'NARTOBJ NAO, NART NA, NARTOBJSUBUNIT NAOS, NUM NUM, NPART PROD, NCLASEA CLSA, NCLASEAS CLSAS';
    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_STOCEXTERN', 'TSE',   'TSE.CODCOMUN = NAO.' || coalesce(pStocExternCamp,''));
    CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
    PERFORM set_config('PKG_LIST_BASE_NAPROVIZ2.gSuplCols',gSuplCols,false);
    gUserFields := coalesce(gUserFields,'');
    gUserAlias  := coalesce(gUserAlias,'') ;
    gNullAlias  := coalesce(gNullAlias,'') ;
    gSuplJoins  := coalesce(gSuplJoins,'') ;
    gSuplCols   := coalesce(gSuplCols,'')  ;
    IF inStr(gSuplJoins, 'TMP_STOCEXTERN') &gt; 0 THEN
      pUSERNAME := current_setting('PKG_GLOBALS.FIRMANAME', true);
      PERFORM winmadmin.PKG_USERFIRME_POPULEAZA_STOCURI_EXTERNE(pUSERNAME, pStocExternFirma, pStocExternCamp);
    END IF;
  ELSE
    gUserFields := '';
    gUserAlias  := '';
    gNullAlias  := '';
    gSuplCols   := '';
    gSuplJoins  := '';
  END IF;

  sJoinSub := '';
  if tmpName = 'TMP_LST_NAPR2' then
    vSub := GETSUBUNITATE();
    if vSub = 1 then vSub := 2; end if;
    if vStocuriGest then
      sJoinSub := 'LEFT JOIN (
                     select sum(OBJS.STOCMIN) STOCMIN, sum(OBJS.STOCMED) STOCMED, sum(OBJS.STOCMAX) STOCMAX, OBJS.CODOBIECT
                     from NARTOBJSUBUNIT OBJS, TMP_MANEVRA_LISTE TMP, TMP_GESTDEDICATE TD
                     WHERE TD.CODGEST::varchar = TMP.VALOARE AND TMP.FILTRU = ''CODGEST''
                           AND OBJS.CODGEST = TD.CODGEST
                     GROUP BY OBJS.CODOBIECT
                   ) NAOS ON NAO.CODOBIECT = NAOS.CODOBIECT '||CHR(13);
    else
      sJoinSub := 'LEFT JOIN NARTOBJSUBUNIT NAOS ON NAO.CODOBIECT = NAOS.CODOBIECT
                                      and (NAOS.codgest is null or NAOS.codgest = 0)
                                      AND NAOS.SUBUNITATE = '||vSub||CHR(13);
    end if;
  end if;

  if Length(pStocExternFirma) &gt; 0 and tmpName &lt;&gt; 'TMP_LST_NAPR2' then
    oSkema := CURRENT_SCHEMA();
    PERFORM WINMADMIN.PKG_USERFIRME_SetGranturiN2(pStocExternFirma,oSkema);
    vZiV := extract(day from vZiuaIni);
    vLunaV := extract(month from vZiuaIni);
    vAnV := extract(year from vZiuaIni) - 1;
    begin
      vZiuaIniP := to_date((LPAD(to_char(vZiV),2,'0')||'.'||LPAD(to_char(vLunaV),2,'0')||'.'||to_char(vAnV))::varchar,'dd.mm.yyyy');
    exception when others then
      vZiuaIniP := Last_day(to_date('01.'||LPAD(to_char(vLunaV),2,'0')||'.'||to_char(vAnV),'dd.mm.yyyy'));
    end;
    vZiV := extract(day from vZiuaFin);
    vLunaV := extract(month from vZiuaFin);
    vAnV := extract(year from vZiuaFin) - 1;
    begin
      vZiuaFinP := to_date(LPAD(to_char(vZiV),2,'0')||'.'||LPAD(to_char(vLunaV),2,'0')||'.'||to_char(vAnV),'dd.mm.yyyy');
    exception when others then
      vZiuaFinP := Last_day(to_date('01.'||LPAD(to_char(vLunaV),2,'0')||'.'||to_char(vAnV),'dd.mm.yyyy'));
    end;
    if current_setting('PKG_LIST_BASE_NAPROVIZ2.vDim', true)::boolean then
      vSelIes_Prec  := '
      SELECT O.CODOBIECT, SUM(I1.CANT) CANT, ''IESPREC'', I1.D1, I1.D2, I1.D3
      FROM '||pStocExternFirma||'.IESIRI I
           INNER JOIN '||pStocExternFirma||'.IESIRI1 I1 ON I1.CODIES = I.CODIES
           INNER JOIN '||pStocExternFirma||'.NARTOBJ OS ON OS.CODOBIECT = I1.CODOBIECT
           INNER JOIN NARTOBJ O ON OS.CODINTERN = O.CODINTERN
      WHERE I.DATADOC BETWEEN '''||to_char(vZiuaIniP)||''' AND '''||to_char(vZiuaFinP)||'''
            AND NVL(I.ANULAT,0) = 0 AND I.OPERAT = 1 AND I.TIPDOC IN ('||current_setting('PKG_LIST_BASE_NAPROVIZ2.vTipVanz', true)||')
      GROUP BY O.CODOBIECT, I1.D1, I1.D2, I1.D3';
      EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip,D1,D2,D3) '||vSelIes_Prec;
    else
      vSelIes_Prec  := '
      SELECT O.CODOBIECT, SUM(I1.CANT) CANT, ''IESPREC''
      FROM '||pStocExternFirma||'.IESIRI I
           INNER JOIN '||pStocExternFirma||'.IESIRI1 I1 ON I1.CODIES = I.CODIES
           INNER JOIN '||pStocExternFirma||'.NARTOBJ OS ON OS.CODOBIECT = I1.CODOBIECT
           INNER JOIN NARTOBJ O ON OS.CODINTERN = O.CODINTERN
      WHERE I.DATADOC BETWEEN '''||to_char(vZiuaIniP)||''' AND '''||to_char(vZiuaFinP)||'''
        AND NVL(I.ANULAT,0) = 0 AND I.OPERAT = 1 AND I.TIPDOC IN ('||current_setting('PKG_LIST_BASE_NAPROVIZ2.vTipVanz', true)||')
      GROUP BY O.CODOBIECT';
      EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip) '||vSelIes_Prec;
    end if;
  end if;
  IF GETSUBUNITATE() = 1 and not vDefalcare THEN
    sColMinMax := ', NAO.STOCMIN, NAO.STOCMED, NAO.STOCMAX';
  END IF;
  SELECT  NEWAN, newLuna INTO vAnPrec, vLunaPrec from pkg_globals_Calculeaza_Luna_Precedenta(Extract( Year FROM vZiuaIni)::numeric, Extract( Month FROM vZiuaIni)::numeric, vAnPrec, vLunaPrec);
  PERFORM pkg_globals_SetLunaTemp(Extract( Year FROM vZiuaIni)::numeric, Extract( Month FROM vZiuaIni)::numeric);
  PERFORM pkg_globals_SetLunaPrecedenta(vAnPrec, vLunaPrec);
  PERFORM PKG_LIST_SELFISAMAG_setAllParams(NULL, null, current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', true), 0, 0, 0);
  IF current_setting('PKG_LIST_BASE_NAPROVIZ2.vDim', true)::boolean and  tmpName &lt;&gt; 'TMP_LST_NAPR2' THEN
  if vDefalcare then
      vSelStocInit := '
      SELECT NS.CODOBIECT, SUM(V.REST) CANT, ''INIT'', NS.D1, NS.D2, NS.D3, G.CODSUBUNIT
      FROM V_STOC_INI_NECESAR2 V
        INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = V.CODNIRSTOC
        INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
        INNER JOIN NGEST G ON G.CODGEST = N.GEST '||vCondSub_G||'
      WHERE V.REST &lt;&gt; 0';

      vSelStocReal := '
      SELECT NS.CODOBIECT, SUM(NS.REST) CANT, ''REAL'', NS.D1, NS.D2, NS.D3, G.CODSUBUNIT
      FROM NIRSTOC NS
        INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
        INNER JOIN NGEST G ON G.CODGEST = N.GEST '||vCondSub_G||'
      WHERE NS.REST &lt;&gt; 0';
      vSelIes_Per  := '
      SELECT NS.CODOBIECT, SUM(L1.CANT) CANT, ''IES'', NS.D1, NS.D2, NS.D3, G.CODSUBUNIT
      FROM LIVR L
        INNER JOIN LIVR1 l1 ON L1.CODLIVR = L.CODLIVR
        INNER JOIN IESIRI I ON L.CODIES = I.CODIES
        INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES AND L1.CODIES1 = I1.CODIES1
        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 '||vCondSub_G||'
      WHERE L.DATALIVR BETWEEN '''||to_char(vZiuaIni)||''' AND '''||to_char(vZiuaFin)||'''
        AND NVL(I.ANULAT,0) = 0 AND I.OPERAT = 1 AND I.TIPDOC IN ('||current_setting('PKG_LIST_BASE_NAPROVIZ2.vTipVanz', true)||')';
      vSelTr_Per := '';
      if Instr(current_setting('PKG_LIST_BASE_NAPROVIZ2.vTipVanz', true),'12') &gt; 0 then
        vSelTr_Per  := '
          SELECT NS.CODOBIECT, SUM(L1.CANT) CANT, ''IES'', NS.D1, NS.D2, NS.D3, G.CODSUBUNIT
          FROM LIVR L
            INNER JOIN LIVR1 l1 ON L1.CODLIVR = L.CODLIVR
            INNER JOIN TRANSF T ON T.CODTRANSF = L.CODTRANSF
            INNER JOIN TRANSF1 T1 ON T1.CODTRANSF = T.CODTRANSF AND L1.CODIES1 = T1.CODTRANSF1
            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 '||vCondSub_G||'
          WHERE L.DATALIVR BETWEEN '''||to_char(vZiuaIni)||''' AND '''||to_char(vZiuaFin)||'''
            AND NVL(T.ANULAT,0) = 0 AND T.OPERAT = 1 AND T.TIPDOC = 12 ';
      end if;
      IF NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', true)::boolean 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';
        vAux := '
        AND';
        IF    vCateLGest = 0 THEN vAux := vAux||' N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
        ELSIF vCateGest  = 0 THEN vAux := vAux||' NS.CODLOCATIE::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'') ';
        ELSE vAux := vAux||' (N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') OR NS.CODLOCATIE IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'')) ';
        END IF;
        vSelStocReal := vSelStocReal ||vAux;
        vSelStocInit := vSelStocInit ||vAux;
        vSelIes_Per := vSelIes_Per   ||vAux;
        if Length(vSelTr_Per) &gt; 0 then
          vSelTr_Per := vSelTr_Per   ||vAux;
        end if;
      END IF;
      IF NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateIOArt', true)::boolean THEN
        vAux := '
        AND NS.CODIOART::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
        vSelStocReal := vSelStocReal ||vAux;
        vSelStocInit := vSelStocInit ||vAux;
        vSelIes_Per := vSelIes_Per   ||vAux;
        if Length(vSelTr_Per) &gt; 0 then
          vSelTr_Per := vSelTr_Per   ||vAux;
        end if;
      END IF;
      vSelStocReal := vSelStocReal ||'
      GROUP BY NS.CODOBIECT, NS.D1, NS.D2, NS.D3, G.CODSUBUNIT';
      vSelStocInit := vSelStocInit ||'
      GROUP BY NS.CODOBIECT, NS.D1, NS.D2, NS.D3, G.CODSUBUNIT';
      vSelIes_Per  := vSelIes_Per||'
      GROUP BY NS.CODOBIECT, NS.D1, NS.D2, NS.D3, G.CODSUBUNIT';
      if Length(vSelTr_Per) &gt; 0 then
        vSelTr_Per  := vSelTr_Per||'
        GROUP BY NS.CODOBIECT, NS.D1, NS.D2, NS.D3, G.CODSUBUNIT';
      end if;

      sJoinRestCmd := '';
      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vRestCmd', true)::boolean then
        sJoinRestCmd := ' INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = C1.GESTACT::varchar AND FILTRU = ''CODGEST'' ';
      end if;

      vFiltruTermen := '';
      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vCuTermen', true)::boolean then
        vFiltruTermen := ' AND C1.TERMEN &lt;= '''||current_setting('PKG_LIST_BASE_NAPROVIZ2.vTermen', true)||''' ';
      end if;
      /************************ Sfarsit Constructie Selecturi Auxiliare ***************************/
      PERFORM PKG_GLOBALS_SetSeparator(',');
      DELETE FROM TMP_CMD_TMP;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,auxfield,D1,D2,D3,CodSubunit)
      SELECT C1.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
        SUM(C1.RestAcceptat) RestA, ''CF'', String_Agg(to_char(C.nrdoc), ''''),C1.D1,C1.D2,C1.D3,C.Subunitatea
      FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 8 '||vCondSub_C||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
        '||vFiltruTermen||'
      GROUP BY C1.CodObiect,C1.D1,C1.D2,C1.D3,C.Subunitatea';
    INSERT INTO x (view_name, test) VALUES ('sSelect', sSelect);
      --EXECUTE sSelect;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,D1,D2,D3,CodSubunit)
      SELECT C1.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
        SUM(C1.RestAcceptat) RestA, ''CC'',C1.D1,C1.D2,C1.D3,C.Subunitatea
      FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 18 '||vCondSub_C||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
      GROUP BY C1.CodObiect,C1.D1,C1.D2,C1.D3,C.Subunitatea';
      EXECUTE sSelect;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,D1,D2,D3,CodSubunit)
      SELECT C1.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
        SUM(C1.RestAcceptat) RestA, ''CSERV'',C1.D1,C1.D2,C1.D3,C.Subunitatea
      FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 92 '||vCondSub_C||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
      GROUP BY C1.CodObiect,C1.D1,C1.D2,C1.D3,C.Subunitatea';
      EXECUTE sSelect;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,D1,D2,D3,CodSubunit)
      SELECT C1.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
        SUM(C1.RestAcceptat) RestA, ''CSIN'',C1.D1,C1.D2,C1.D3,C.Subunitatea
      FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 44 '||vCondSub_C||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
      GROUP BY C1.CodObiect,C1.D1,C1.D2,C1.D3,C.Subunitatea';
      EXECUTE sSelect;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,D1,D2,D3,CodSubunit)
      SELECT C1.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
        SUM(C1.RestAcceptat) RestA, ''CSIES'',C1.D1,C1.D2,C1.D3,C.Subunitatea
      FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 44 '||vCondSub_CS||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
      GROUP BY C1.CodObiect,C1.D1,C1.D2,C1.D3,C.Subunitatea';
      EXECUTE sSelect;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,D1,D2,D3,CodSubunit)
      SELECT C1.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
        SUM(C1.RestAcceptat) RestA, ''CG'',C1.D1,C1.D2,C1.D3,C.Subunitatea
      FROM COMANDA1 C1
        INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
        INNER JOIN NGEST G ON C.CodGest = G.CodGest'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND G.Tip = 1 AND C.TipDoc = 43 '||vCondSub_C||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
      GROUP BY C1.CodObiect,C1.D1,C1.D2,C1.D3,C.Subunitatea';
      EXECUTE sSelect;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,D1,D2,D3,CodSubunit)
      SELECT CMDMAT.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then CMDMAT.Cant else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then CMDMAT.Cant else 0 end) CantA,
        SUM(CMDMAT.Rest) RestA, ''CIIN'',CMDMAT.D1,CMDMAT.D2,CMDMAT.D3,C.Subunitatea
      FROM CMDPRODMAT CMDMAT
        INNER JOIN COMANDA1 C1 ON CMDMAT.CodComanda1 = C1.CodComanda1
        INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 53 '||vCondSub_C||'
        AND CMDMAT.Rest &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
        AND ((C1.Consum = 1 AND CMDMAT.Tip &lt;&gt; 1) OR (C1.Consum = 2 AND CMDMAT.Tip = 2))
      GROUP BY CMDMAT.CodObiect,CMDMAT.D1,CMDMAT.D2,CMDMAT.D3,C.Subunitatea';
      EXECUTE sSelect;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,D1,D2,D3,CodSubunit)
      SELECT CMDMAT.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then CMDMAT.Cant else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then CMDMAT.Cant else 0 end) CantA,
        SUM(CMDMAT.Rest) RestA, ''CIIES'',CMDMAT.D1,CMDMAT.D2,CMDMAT.D3,C.Subunitatea
      FROM CMDPRODMAT CMDMAT
        INNER JOIN COMANDA1 C1 ON CMDMAT.CodComanda1 = C1.CodComanda1
        INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 '||vCondSub_C||'
        AND CMDMAT.Rest &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
        AND ((C1.Consum = 1 AND CMDMAT.Tip = 1) OR (C1.Consum = 2 AND CMDMAT.Tip &lt;&gt; 2))
      GROUP BY CMDMAT.CodObiect,CMDMAT.D1,CMDMAT.D2,CMDMAT.D3,C.Subunitatea';
      EXECUTE sSelect;
      --DELETE FROM TMP_STOCREAL;
      EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip,D1,D2,D3,codgest) '||vSelStocReal;
      EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip,D1,D2,D3,codgest) '||vSelStocInit;
      EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip,D1,D2,D3,codgest) '||vSelIes_Per;
      if Length(vSelTr_Per) &gt; 0 THEN
        EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip,D1,D2,D3,codgest) '||vSelTr_Per;
      end if;
      Luni := 0;
      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vPeLuni', true)::boolean then
        for v_rec in (extract(year from vZiuaIni)*12+extract(month from vZiuaIni)) .. (extract(year from vZiuaFin)*12+extract(month from vZiuaFin)) loop
          if Luni &gt; 12 then Exit; end if;
          Luni := Luni + 1;
          if v_rec/12 = trunc(v_rec/12) then
            vLunaV := 12;
            vAnV   := v_rec/12 - 1;
          else
            vLunaV := v_rec - trunc(v_rec/12)*12;
            vAnV   := trunc(v_rec/12);
          end if;
          if vLunaV =  1 then sLuna := 'Ian'; end if;
          if vLunaV =  2 then sLuna := 'Feb'; end if;
          if vLunaV =  3 then sLuna := 'Mar'; end if;
          if vLunaV =  4 then sLuna := 'Apr'; end if;
          if vLunaV =  5 then sLuna := 'Mai'; end if;
          if vLunaV =  6 then sLuna := 'Jun'; end if;
          if vLunaV =  7 then sLuna := 'Jul'; end if;
          if vLunaV =  8 then sLuna := 'Aug'; end if;
          if vLunaV =  9 then sLuna := 'Sep'; end if;
          if vLunaV = 10 then sLuna := 'Oct'; end if;
          if vLunaV = 11 then sLuna := 'Nov'; end if;
          if vLunaV = 12 then sLuna := 'Dec'; end if;

          vSelIes_Per  := '
          SELECT I1.CODOBIECT, SUM(L1.CANT) CANT,'''||sLuna||''',I1.D1,I1.D2,I1.D3,G.CODSUBUNIT
          FROM LIVR L
            INNER JOIN LIVR1 l1 ON L1.CODLIVR = L.CODLIVR
            INNER JOIN IESIRI I ON L.CODIES = I.CODIES
            INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES 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
            LEFT JOIN NGEST G ON G.CODGEST = COALESCE(N.GEST,LV.GEST) '||vCondSub_G||'
          WHERE I.AN*12+I.LUNA = '||to_char(vAnV*12+vLunaV)||'
            AND NVL(I.ANULAT,0) = 0 AND I.OPERAT = 1 AND I.TIPDOC IN ('||current_setting('PKG_LIST_BASE_NAPROVIZ2.vTipVanz', true)||')';
          vAux := '';
          IF NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', true)::boolean 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';
            vAux := '
            AND';
            IF    vCateLGest = 0 THEN vAux := vAux||' COALESCE(N.GEST,LV.GEST)::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
            ELSIF vCateGest  = 0 THEN vAux := vAux||' NS.CODLOCATIE::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'') ';
            ELSE vAux := vAux||' (COALESCE(N.GEST,LV.GEST)::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') OR NS.CODLOCATIE IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'')) ';
            END IF;
            vSelIes_Per := vSelIes_Per   ||vAux;
          END IF;

          IF NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateIOArt', true)::boolean THEN
            vAux := '
            AND COALESCE(NS.CODIOART,LV.CODIOART)::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
            vSelIes_Per := vSelIes_Per   ||vAux;
          END IF;
          vSelIes_Per  := vSelIes_Per||'
          GROUP BY I1.CODOBIECT,I1.D1,I1.D2,I1.D3,G.CODSUBUNIT';
          EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip,D1,D2,D3,codgest) '||vSelIes_Per;
        end loop;
      end if;
      DELETE FROM TMP_STOCREZ;
      sSelect := 'INSERT INTO tmp_stocrez(codobiect,rezervat,D1,D2,D3,codgest)
      SELECT NS.CODOBIECT, SUM(R.REST) REZERVAT,NS.D1,NS.D2,NS.D3,G.CODSUBUNIT
      FROM REZERVATS R
        INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = R.CODNIRSTOC
        INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
        INNER JOIN NGEST G ON G.CODGEST = N.GEST '||vCondSub_G||'
      WHERE NVL(R.REST,0) &gt; 0';
      if NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', true)::boolean 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
          sSelect := sSelect || ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = N.GEST::varchar)';
        elsif vCateGest = 0 then
          sSelect := sSelect || ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND VALOARE = NS.CODLOCATIE::varchar)';
        else
          sSelect := sSelect || ' 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;
      if NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateIOArt', true)::boolean then
        sSelect := sSelect || ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND VALOARE = NS.CODIOART::varchar ) ';
      end if;
      sSelect := sSelect ||' GROUP BY NS.CODOBIECT,NS.D1,NS.D2,NS.D3,G.CODSUBUNIT';
      EXECUTE sSelect;
      IF current_setting('PKG_LIST_BASE_NAPROVIZ2.vUltAchiz', true)::boolean
      THEN  sUltNirstoc := 'SELECT CODOBIECT,D1,D2,D3,MAX(CODNIRSTOC) CODNIRSTOC
                      FROM (SELECT CODOBIECT,D1,D2,D3,CODNIRSTOC,dense_rank() over(partition by CODOBIECT,D1,D2,D3 ORDER BY DATAACHIZ desc, CODNIRSTOC desc) NR
                            FROM NIRSTOC
                            WHERE FURN &gt; 0 AND coalesce(CODNIRSTOCPARINTE,0) = 0 ) xx
                      WHERE xx.NR=1
                      GROUP BY CODOBIECT,D1,D2,D3';
      ELSE sUltNirstoc := 'SELECT 0 CODOBIECT, 0 CODNIRSTOC';
      END IF;
    ELSE
      vSelStocInit := '
      SELECT NS.CODOBIECT, SUM(V.REST) CANT, ''INIT'', NS.D1, NS.D2, NS.D3
      FROM V_STOC_INI_NECESAR2 V
        INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = V.CODNIRSTOC
        INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
        INNER JOIN NGEST G ON G.CODGEST = N.GEST '||vCondSub_G||'
      WHERE V.REST &lt;&gt; 0';

      vSelStocReal := '
      SELECT NS.CODOBIECT, SUM(NS.REST) CANT, ''REAL'', NS.D1, NS.D2, NS.D3
      FROM NIRSTOC NS
        INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
        INNER JOIN NGEST G ON G.CODGEST = N.GEST '||vCondSub_G||'
      WHERE NS.REST &lt;&gt; 0';

      vSelIes_Per  := '
      SELECT NS.CODOBIECT, SUM(L1.CANT) CANT, ''IES'', NS.D1, NS.D2, NS.D3
      FROM LIVR L
        INNER JOIN LIVR1 l1 ON L1.CODLIVR = L.CODLIVR
        INNER JOIN IESIRI I ON L.CODIES = I.CODIES
        INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES AND L1.CODIES1 = I1.CODIES1
        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 '||vCondSub_G||'
      WHERE L.DATALIVR BETWEEN '''||to_char(vZiuaIni)||''' AND '''||to_char(vZiuaFin)||'''
        AND NVL(I.ANULAT,0) = 0 AND I.OPERAT = 1 AND I.TIPDOC IN ('||current_setting('PKG_LIST_BASE_NAPROVIZ2.vTipVanz', true)||')';

      vSelTr_Per := '';
      if Instr(current_setting('PKG_LIST_BASE_NAPROVIZ2.vTipVanz', true),'12') &gt; 0 then
        vSelTr_Per  := '
          SELECT NS.CODOBIECT, SUM(L1.CANT) CANT, ''IES'', NS.D1, NS.D2, NS.D3
          FROM LIVR L
            INNER JOIN LIVR1 l1 ON L1.CODLIVR = L.CODLIVR
            INNER JOIN TRANSF T ON T.CODTRANSF = L.CODTRANSF
            INNER JOIN TRANSF1 T1 ON T1.CODTRANSF = T.CODTRANSF AND L1.CODIES1 = T1.CODTRANSF1
            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 '||vCondSub_G||'
          WHERE L.DATALIVR BETWEEN '''||to_char(vZiuaIni)||''' AND '''||to_char(vZiuaFin)||'''
            AND NVL(T.ANULAT,0) = 0 AND T.OPERAT = 1 AND T.TIPDOC = 12 ';
      end if;

      IF NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', true)::boolean 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';
        vAux := '
        AND';
        IF    vCateLGest = 0 THEN vAux := vAux||' N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
        ELSIF vCateGest  = 0 THEN vAux := vAux||' NS.CODLOCATIE::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'') ';
        ELSE vAux := vAux||' (N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') OR NS.CODLOCATIE IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'')) ';
        END IF;
        vSelStocReal := vSelStocReal ||vAux;
        vSelStocInit := vSelStocInit ||vAux;
        vSelIes_Per := vSelIes_Per   ||vAux;
        if Length(vSelTr_Per) &gt; 0 then
          vSelTr_Per := vSelTr_Per   ||vAux;
        end if;
      END IF;

      IF NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateIOArt', true)::boolean THEN
        vAux := '
        AND NS.CODIOART::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
        vSelStocReal := vSelStocReal ||vAux;
        vSelStocInit := vSelStocInit ||vAux;
        vSelIes_Per := vSelIes_Per   ||vAux;
        if Length(vSelTr_Per) &gt; 0 then
          vSelTr_Per := vSelTr_Per   ||vAux;
        end if;
      END IF;

      vSelStocReal := vSelStocReal ||'
      GROUP BY NS.CODOBIECT, NS.D1, NS.D2, NS.D3';
      vSelStocInit := vSelStocInit ||'
      GROUP BY NS.CODOBIECT, NS.D1, NS.D2, NS.D3';
      vSelIes_Per  := vSelIes_Per||'
      GROUP BY NS.CODOBIECT, NS.D1, NS.D2, NS.D3';
      if Length(vSelTr_Per) &gt; 0 then
        vSelTr_Per  := vSelTr_Per||'
        GROUP BY NS.CODOBIECT, NS.D1, NS.D2, NS.D3';
      end if;

      sJoinRestCmd := '';
      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vRestCmd', true)::boolean then
        sJoinRestCmd := ' INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = C1.GESTACT::varchar AND FILTRU = ''CODGEST'' ';
      end if;

      vFiltruTermen := '';
      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vCuTermen', true)::boolean then
        vFiltruTermen := ' AND C1.TERMEN &lt;= '''||current_setting('PKG_LIST_BASE_NAPROVIZ2.vTermen', true)||''' ';
      end if;

      /************************ Sfarsit Constructie Selecturi Auxiliare ***************************/
      PERFORM PKG_GLOBALS_SetSeparator(',');
      DELETE FROM TMP_CMD_TMP;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,auxfield,D1,D2,D3)
      SELECT C1.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
        SUM(C1.RestAcceptat) RestA, ''CF'', String_Agg(to_char(C.nrdoc), ''''),C1.D1,C1.D2,C1.D3
      FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 8 '||vCondSub_C||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
        '||vFiltruTermen||'
      GROUP BY C1.CodObiect,C1.D1,C1.D2,C1.D3';
      EXECUTE sSelect;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,D1,D2,D3)
      SELECT C1.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
        SUM(C1.RestAcceptat) RestA, ''CC'',C1.D1,C1.D2,C1.D3
      FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 18 '||vCondSub_C||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
      GROUP BY C1.CodObiect,C1.D1,C1.D2,C1.D3';
      EXECUTE sSelect;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,D1,D2,D3)
      SELECT C1.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
        SUM(C1.RestAcceptat) RestA, ''CSERV'',C1.D1,C1.D2,C1.D3
      FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 92 '||vCondSub_C||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
      GROUP BY C1.CodObiect,C1.D1,C1.D2,C1.D3';
      EXECUTE sSelect;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,D1,D2,D3)
      SELECT C1.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
        SUM(C1.RestAcceptat) RestA, ''CSIN'',C1.D1,C1.D2,C1.D3
      FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 44 '||vCondSub_C||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
      GROUP BY C1.CodObiect,C1.D1,C1.D2,C1.D3';
      EXECUTE sSelect;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,D1,D2,D3)
      SELECT C1.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
        SUM(C1.RestAcceptat) RestA, ''CSIES'',C1.D1,C1.D2,C1.D3
      FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 44 '||vCondSub_CS||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
      GROUP BY C1.CodObiect,C1.D1,C1.D2,C1.D3';
      EXECUTE sSelect;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,D1,D2,D3)
      SELECT C1.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
        SUM(C1.RestAcceptat) RestA, ''CG'',C1.D1,C1.D2,C1.D3
      FROM COMANDA1 C1
        INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
        INNER JOIN NGEST G ON C.CodGest = G.CodGest'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND G.Tip = 1 AND C.TipDoc = 43 '||vCondSub_C||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
      GROUP BY C1.CodObiect,C1.D1,C1.D2,C1.D3';
      EXECUTE sSelect;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,D1,D2,D3)
      SELECT CMDMAT.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then CMDMAT.Cant else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then CMDMAT.Cant else 0 end) CantA,
        SUM(CMDMAT.Rest) RestA, ''CIIN'',CMDMAT.D1,CMDMAT.D2,CMDMAT.D3
      FROM CMDPRODMAT CMDMAT
        INNER JOIN COMANDA1 C1 ON CMDMAT.CodComanda1 = C1.CodComanda1
        INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 53 '||vCondSub_C||'
        AND CMDMAT.Rest &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
        AND ((C1.Consum = 1 AND CMDMAT.Tip &lt;&gt; 1) OR (C1.Consum = 2 AND CMDMAT.Tip = 2))
      GROUP BY CMDMAT.CodObiect,CMDMAT.D1,CMDMAT.D2,CMDMAT.D3';
      EXECUTE sSelect;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,D1,D2,D3)
      SELECT CMDMAT.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then CMDMAT.Cant else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then CMDMAT.Cant else 0 end) CantA,
        SUM(CMDMAT.Rest) RestA, ''CIIES'',CMDMAT.D1,CMDMAT.D2,CMDMAT.D3
      FROM CMDPRODMAT CMDMAT
        INNER JOIN COMANDA1 C1 ON CMDMAT.CodComanda1 = C1.CodComanda1
        INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 '||vCondSub_C||'
        AND CMDMAT.Rest &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
        AND ((C1.Consum = 1 AND CMDMAT.Tip = 1) OR (C1.Consum = 2 AND CMDMAT.Tip &lt;&gt; 2))
      GROUP BY CMDMAT.CodObiect,CMDMAT.D1,CMDMAT.D2,CMDMAT.D3';
      EXECUTE sSelect;

      --DELETE FROM TMP_STOCREAL;
      EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip,D1,D2,D3) '||vSelStocReal;
      EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip,D1,D2,D3) '||vSelStocInit;
      EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip,D1,D2,D3) '||vSelIes_Per;
      if Length(vSelTr_Per) &gt; 0 then
        EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip,D1,D2,D3) '||vSelTr_Per;
      end if;

      Luni := 0;
      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vPeLuni', true)::boolean then
        for v_rec in (extract(year from vZiuaIni)*12+extract(month from vZiuaIni)) .. (extract(year from vZiuaFin)*12+extract(month from vZiuaFin)) loop
          if Luni &gt; 12 then Exit; end if;
          Luni := Luni + 1;
          if v_rec/12 = trunc(v_rec/12) then
            vLunaV := 12;
            vAnV   := v_rec/12 - 1;
          else
            vLunaV := v_rec - trunc(v_rec/12)*12;
            vAnV   := trunc(v_rec/12);
          end if;
          if vLunaV =  1 then sLuna := 'Ian'; end if;
          if vLunaV =  2 then sLuna := 'Feb'; end if;
          if vLunaV =  3 then sLuna := 'Mar'; end if;
          if vLunaV =  4 then sLuna := 'Apr'; end if;
          if vLunaV =  5 then sLuna := 'Mai'; end if;
          if vLunaV =  6 then sLuna := 'Jun'; end if;
          if vLunaV =  7 then sLuna := 'Jul'; end if;
          if vLunaV =  8 then sLuna := 'Aug'; end if;
          if vLunaV =  9 then sLuna := 'Sep'; end if;
          if vLunaV = 10 then sLuna := 'Oct'; end if;
          if vLunaV = 11 then sLuna := 'Nov'; end if;
          if vLunaV = 12 then sLuna := 'Dec'; end if;

          vSelIes_Per  := '
          SELECT I1.CODOBIECT, SUM(L1.CANT) CANT,'''||sLuna||''',I1.D1,I1.D2,I1.D3
          FROM LIVR L
            INNER JOIN LIVR1 l1 ON L1.CODLIVR = L.CODLIVR
            INNER JOIN IESIRI I ON L.CODIES = I.CODIES
            INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES 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
            LEFT JOIN NGEST G ON G.CODGEST = COALESCE(N.GEST,LV.GEST) '||vCondSub_G||'
          WHERE I.AN*12+I.LUNA = '||to_char(vAnV*12+vLunaV)||'
            AND NVL(I.ANULAT,0) = 0 AND I.OPERAT = 1 AND I.TIPDOC IN ('||current_setting('PKG_LIST_BASE_NAPROVIZ2.vTipVanz', true)||')';

          vAux := '';
          IF NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', true)::boolean 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';
            vAux := '
            AND';
            IF    vCateLGest = 0 THEN vAux := vAux||' COALESCE(N.GEST,LV.GEST)::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
            ELSIF vCateGest  = 0 THEN vAux := vAux||' NS.CODLOCATIE::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'') ';
            ELSE vAux := vAux||' (COALESCE(N.GEST,LV.GEST)::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') OR NS.CODLOCATIE IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'')) ';
            END IF;
            vSelIes_Per := vSelIes_Per   ||vAux;
          END IF;

          IF NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateIOArt', true)::boolean THEN
            vAux := '
            AND COALESCE(NS.CODIOART,LV.CODIOART)::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
            vSelIes_Per := vSelIes_Per   ||vAux;
          END IF;
          vSelIes_Per  := vSelIes_Per||'
          GROUP BY I1.CODOBIECT,I1.D1,I1.D2,I1.D3';
          EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip,D1,D2,D3) '||vSelIes_Per;
        end loop;
      end if;

      DELETE FROM TMP_STOCREZ;
      sSelect := 'INSERT INTO tmp_stocrez(codobiect,rezervat,D1,D2,D3)
      SELECT NS.CODOBIECT, SUM(R.REST) REZERVAT,NS.D1,NS.D2,NS.D3
      FROM REZERVATS R
        INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = R.CODNIRSTOC
        INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
        INNER JOIN NGEST G ON G.CODGEST = N.GEST '||vCondSub_G||'
      WHERE NVL(R.REST,0) &gt; 0';

      if NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', true)::boolean 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
          sSelect := sSelect || ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = N.GEST::varchar)';
        elsif vCateGest = 0 then
          sSelect := sSelect || ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND VALOARE = NS.CODLOCATIE::varchar)';
        else
          sSelect := sSelect || ' 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;
      if NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateIOArt', true)::boolean then
        sSelect := sSelect || ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND VALOARE = NS.CODIOART::varchar ) ';
      end if;
      sSelect := sSelect ||' GROUP BY NS.CODOBIECT,NS.D1,NS.D2,NS.D3';
      EXECUTE sSelect;

      IF current_setting('PKG_LIST_BASE_NAPROVIZ2.vUltAchiz', true)::boolean
      THEN   sUltNirstoc := 'SELECT CODOBIECT,D1,D2,D3,MAX(CODNIRSTOC) CODNIRSTOC
                      FROM (SELECT CODOBIECT,D1,D2,D3,CODNIRSTOC,dense_rank() over(partition by CODOBIECT,D1,D2,D3 ORDER BY DATAACHIZ desc, CODNIRSTOC desc) NR
                            FROM NIRSTOC
                            WHERE FURN &gt; 0 AND coalesce(CODNIRSTOCPARINTE,0) = 0 ) xx
                      WHERE xx.NR=1
                      GROUP BY CODOBIECT,D1,D2,D3';
       ELSE sUltNirstoc := 'SELECT 0 CODOBIECT, 0 CODNIRSTOC';
      END IF;
    end if;
  ELSE
    if vDefalcare THEN
      vSelStocInit := '
      SELECT NS.CODOBIECT, SUM(V.REST) CANT, ''INIT'', G.CODSUBUNIT
      FROM V_STOC_INI_NECESAR2 V
        INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = V.CODNIRSTOC
        INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
        INNER JOIN NGEST G ON G.CODGEST = N.GEST '||vCondSub_G||'
      WHERE V.REST &lt;&gt; 0';

      vSelStocReal := '
      SELECT NS.CODOBIECT, SUM(NS.REST) CANT, ''REAL'', G.CODSUBUNIT
      FROM NIRSTOC NS
        INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
        INNER JOIN NGEST G ON G.CODGEST = N.GEST '||vCondSub_G||'
      WHERE NS.REST &lt;&gt; 0';
      vSelIes_Per  := '
      SELECT NS.CODOBIECT, SUM(L1.CANT) CANT, ''IES'', G.CODSUBUNIT
      FROM LIVR L
        INNER JOIN LIVR1 l1 ON L1.CODLIVR = L.CODLIVR
        INNER JOIN IESIRI I ON L.CODIES = I.CODIES
        INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES AND L1.CODIES1 = I1.CODIES1
        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 '||vCondSub_G||'
      WHERE L.DATALIVR BETWEEN '''||to_char(vZiuaIni)||''' AND '''||to_char(vZiuaFin)||'''
        AND NVL(I.ANULAT,0) = 0 AND I.OPERAT = 1 AND I.TIPDOC IN ('||current_setting('PKG_LIST_BASE_NAPROVIZ2.vTipVanz', true)||')';
      vSelTr_Per := '';
      if Instr(current_setting('PKG_LIST_BASE_NAPROVIZ2.vTipVanz', true),'12') &gt; 0 then
        vSelTr_Per  := '
          SELECT NS.CODOBIECT, SUM(L1.CANT) CANT, ''IES'', G.CODSUBUNIT
          FROM LIVR L
            INNER JOIN LIVR1 l1 ON L1.CODLIVR = L.CODLIVR
            INNER JOIN TRANSF T ON T.CODTRANSF = L.CODTRANSF
            INNER JOIN TRANSF1 T1 ON T1.CODTRANSF = T.CODTRANSF AND L1.CODIES1 = T1.CODTRANSF1
            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 '||vCondSub_G||'
          WHERE L.DATALIVR BETWEEN '''||to_char(vZiuaIni)||''' AND '''||to_char(vZiuaFin)||'''
            AND NVL(T.ANULAT,0) = 0 AND T.OPERAT = 1 AND T.TIPDOC = 12 ';
      end if;
      IF NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', true)::boolean 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';
        vAux := '
        AND';
        IF    vCateLGest = 0 THEN vAux := vAux||' N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
        ELSIF vCateGest  = 0 THEN vAux := vAux||' NS.CODLOCATIE::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'') ';
        ELSE vAux := vAux||' (N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') OR NS.CODLOCATIE IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'')) ';
        END IF;
        vSelStocReal := vSelStocReal ||vAux;
        vSelStocInit := vSelStocInit ||vAux;
        vSelIes_Per := vSelIes_Per   ||vAux;
        if Length(vSelTr_Per) &gt; 0 then
          vSelTr_Per := vSelTr_Per   ||vAux;
        end if;
      END IF;
      IF NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateIOArt', true)::boolean THEN
        vAux := '
        AND NS.CODIOART::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
        vSelStocReal := vSelStocReal ||vAux;
        vSelStocInit := vSelStocInit ||vAux;
        vSelIes_Per := vSelIes_Per   ||vAux;
        if Length(vSelTr_Per) &gt; 0 then
          vSelTr_Per := vSelTr_Per   ||vAux;
        end if;
      END IF;
      vSelStocReal := vSelStocReal ||'
      GROUP BY NS.CODOBIECT, G.CODSUBUNIT';
      vSelStocInit := vSelStocInit ||'
      GROUP BY NS.CODOBIECT, G.CODSUBUNIT';
      vSelIes_Per  := vSelIes_Per||'
      GROUP BY NS.CODOBIECT, G.CODSUBUNIT';
      if Length(vSelTr_Per) &gt; 0 then
        vSelTr_Per  := vSelTr_Per||'
        GROUP BY NS.CODOBIECT, G.CODSUBUNIT';
      end if;

      sJoinRestCmd := '';
      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vRestCmd', true)::boolean then
        sJoinRestCmd := ' INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = C1.GESTACT::varchar AND FILTRU = ''CODGEST'' ';
      end if;

      vFiltruTermen := '';
      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vCuTermen', true)::boolean then
        vFiltruTermen := ' AND C1.TERMEN &lt;= '''||current_setting('PKG_LIST_BASE_NAPROVIZ2.vTermen', true)||''' ';
      end if;

      /************************ Sfarsit Constructie Selecturi Auxiliare ***************************/

      PERFORM PKG_GLOBALS_SetSeparator(',');
      DELETE FROM TMP_CMD_TMP;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,auxfield,CodSubunit)
      SELECT C1.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
        SUM(C1.RestAcceptat) RestA, ''CF'', String_Agg(to_char(C.nrdoc), ''''),C.Subunitatea
      FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 8 '||vCondSub_C||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
        '||vFiltruTermen||'
      GROUP BY C1.CodObiect,C.Subunitatea';
      EXECUTE sSelect;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,CodSubunit)
      SELECT C1.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
        SUM(C1.RestAcceptat) RestA, ''CC'',C.Subunitatea
      FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 18 '||vCondSub_C||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
      GROUP BY C1.CodObiect,C.Subunitatea';
      EXECUTE sSelect;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,CodSubunit)
      SELECT C1.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
        SUM(C1.RestAcceptat) RestA, ''CSERV'',C.Subunitatea
      FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 92 '||vCondSub_C||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
      GROUP BY C1.CodObiect,C.Subunitatea';
      EXECUTE sSelect;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,CodSubunit)
      SELECT C1.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
        SUM(C1.RestAcceptat) RestA, ''CSIN'',C.Subunitatea
      FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 44 '||vCondSub_C||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
      GROUP BY C1.CodObiect,C.Subunitatea';
      EXECUTE sSelect;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,CodSubunit)
      SELECT C1.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
        SUM(C1.RestAcceptat) RestA, ''CSIES'',C.Subunitatea
      FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 44 '||vCondSub_CS||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
      GROUP BY C1.CodObiect,C.Subunitatea';
      EXECUTE sSelect;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,CodSubunit)
      SELECT C1.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
        SUM(C1.RestAcceptat) RestA, ''CG'',C.Subunitatea
      FROM COMANDA1 C1
        INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
        INNER JOIN NGEST G ON C.CodGest = G.CodGest'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND G.Tip = 1 AND C.TipDoc = 43 '||vCondSub_C||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
      GROUP BY C1.CodObiect,C.Subunitatea';
      EXECUTE sSelect;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,CodSubunit)
      SELECT CMDMAT.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then CMDMAT.Cant else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then CMDMAT.Cant else 0 end) CantA,
        SUM(CMDMAT.Rest) RestA, ''CIIN'',C.Subunitatea
      FROM CMDPRODMAT CMDMAT
        INNER JOIN COMANDA1 C1 ON CMDMAT.CodComanda1 = C1.CodComanda1
        INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 53 '||vCondSub_C||'
        AND CMDMAT.Rest &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
        AND ((C1.Consum = 1 AND CMDMAT.Tip &lt;&gt; 1) OR (C1.Consum = 2 AND CMDMAT.Tip = 2))
      GROUP BY CMDMAT.CodObiect,C.Subunitatea';
      EXECUTE sSelect;
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,CodSubunit)
      SELECT CMDMAT.CodObiect,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then CMDMAT.Cant else 0 end) CantC,
        SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then CMDMAT.Cant else 0 end) CantA,
        SUM(CMDMAT.Rest) RestA, ''CIIES'',C.Subunitatea
      FROM CMDPRODMAT CMDMAT
        INNER JOIN COMANDA1 C1 ON CMDMAT.CodComanda1 = C1.CodComanda1
        INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 '||vCondSub_C||'
        AND CMDMAT.Rest &gt; 0 AND C.DataDoc &lt;= '''||to_char(vZiuaFinC)||'''
        AND ((C1.Consum = 1 AND CMDMAT.Tip = 1) OR (C1.Consum = 2 AND CMDMAT.Tip &lt;&gt; 2))
      GROUP BY CMDMAT.CodObiect,C.Subunitatea';
      EXECUTE sSelect;

      --DELETE FROM TMP_STOCREAL;
      EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip,codgest) '||vSelStocReal;
      EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip,codgest) '||vSelStocInit;
      EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip,codgest) '||vSelIes_Per;
      if Length(vSelTr_Per) &gt; 0 then
        EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip,codgest) '||vSelTr_Per;
      end if;

      Luni := 0;
      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vPeLuni', true)::boolean then
        for v_rec in (extract(year from vZiuaIni)*12+extract(month from vZiuaIni)) .. (extract(year from vZiuaFin)*12+extract(month from vZiuaFin)) loop
          if Luni &gt; 12 then Exit; end if;
          Luni := Luni + 1;
          if v_rec/12 = trunc(v_rec/12) then
            vLunaV := 12;
            vAnV   := v_rec/12 - 1;
          else
            vLunaV := v_rec - trunc(v_rec/12)*12;
            vAnV   := trunc(v_rec/12);
          end if;
          if vLunaV =  1 then sLuna := 'Ian'; end if;
          if vLunaV =  2 then sLuna := 'Feb'; end if;
          if vLunaV =  3 then sLuna := 'Mar'; end if;
          if vLunaV =  4 then sLuna := 'Apr'; end if;
          if vLunaV =  5 then sLuna := 'Mai'; end if;
          if vLunaV =  6 then sLuna := 'Jun'; end if;
          if vLunaV =  7 then sLuna := 'Jul'; end if;
          if vLunaV =  8 then sLuna := 'Aug'; end if;
          if vLunaV =  9 then sLuna := 'Sep'; end if;
          if vLunaV = 10 then sLuna := 'Oct'; end if;
          if vLunaV = 11 then sLuna := 'Nov'; end if;
          if vLunaV = 12 then sLuna := 'Dec'; end if;

          vSelIes_Per  := '
          SELECT I1.CODOBIECT, SUM(L1.CANT) CANT,'''||sLuna||''',G.CODSUBUNIT
          FROM LIVR L
            INNER JOIN LIVR1 l1 ON L1.CODLIVR = L.CODLIVR
            INNER JOIN IESIRI I ON L.CODIES = I.CODIES
            INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES 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
            LEFT JOIN NGEST G ON G.CODGEST = COALESCE(N.GEST,LV.GEST) '||vCondSub_G||'
          WHERE I.AN*12+I.LUNA = '||to_char(vAnV*12+vLunaV)||'
            AND NVL(I.ANULAT,0) = 0 AND I.OPERAT = 1 AND I.TIPDOC IN ('||current_setting('PKG_LIST_BASE_NAPROVIZ2.vTipVanz', true)||')';

          vAux := '';
          IF NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', true)::boolean 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';
            vAux := '
            AND';
            IF    vCateLGest = 0 THEN vAux := vAux||' COALESCE(N.GEST,LV.GEST)::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
            ELSIF vCateGest  = 0 THEN vAux := vAux||' NS.CODLOCATIE::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'') ';
            ELSE vAux := vAux||' (COALESCE(N.GEST,LV.GEST)::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') OR NS.CODLOCATIE IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'')) ';
            END IF;
            vSelIes_Per := vSelIes_Per   ||vAux;
          END IF;

          IF NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateIOArt', true)::boolean THEN
            vAux := '
            AND COALESCE(NS.CODIOART,LV.CODIOART)::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
            vSelIes_Per := vSelIes_Per   ||vAux;
          END IF;
          vSelIes_Per  := vSelIes_Per||'
          GROUP BY I1.CODOBIECT,I1.D1,I1.D2,I1.D3,G.CODSUBUNIT';
          EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip,codgest) '||vSelIes_Per;
        end loop;
      end if;

      DELETE FROM TMP_STOCREZ;
      sSelect := 'INSERT INTO tmp_stocrez(codobiect,rezervat,codgest)
      SELECT NS.CODOBIECT, SUM(R.REST) REZERVAT,G.CODSUBUNIT
      FROM REZERVATS R
        INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = R.CODNIRSTOC
        INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
        INNER JOIN NGEST G ON G.CODGEST = N.GEST '||vCondSub_G||'
      WHERE NVL(R.REST,0) &gt; 0';

      if NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', true)::boolean 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
          sSelect := sSelect || ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = N.GEST::varchar)';
        elsif vCateGest = 0 then
          sSelect := sSelect || ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND VALOARE = NS.CODLOCATIE::varchar)';
        else
          sSelect := sSelect || ' 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;
      if NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateIOArt', true)::boolean then
        sSelect := sSelect || ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND VALOARE = NS.CODIOART::varchar ) ';
      end if;
      sSelect := sSelect ||' GROUP BY NS.CODOBIECT,G.CODSUBUNIT';
      EXECUTE sSelect;

      IF current_setting('PKG_LIST_BASE_NAPROVIZ2.vUltAchiz', true)::boolean
       THEN sUltNirstoc := 'SELECT CODOBIECT,D1,D2,D3,MAX(CODNIRSTOC) CODNIRSTOC
                      FROM (SELECT CODOBIECT,D1,D2,D3,CODNIRSTOC,dense_rank() over(partition by CODOBIECT,D1,D2,D3 ORDER BY DATAACHIZ desc, CODNIRSTOC desc) NR
                            FROM NIRSTOC
                            WHERE FURN &gt; 0 AND coalesce(CODNIRSTOCPARINTE,0) = 0 ) xx
                      WHERE xx.NR=1
                      GROUP BY CODOBIECT,D1,D2,D3';
       ELSE sUltNirstoc := 'SELECT 0 CODOBIECT, 0 CODNIRSTOC';
      END IF;
    ELSE
      vSelStocInit := '
      SELECT NS.CODOBIECT, SUM(V.REST) CANT, ''INIT''
      FROM V_STOC_INI_NECESAR2 V
        INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = V.CODNIRSTOC
        INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
        INNER JOIN NGEST G ON G.CODGEST = N.GEST '||vCondSub_G||'
      WHERE V.REST &lt;&gt; 0';

      vSelStocReal := '
      SELECT NS.CODOBIECT, SUM(NS.REST) CANT, ''REAL''
      FROM NIRSTOC NS
        INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
        INNER JOIN NGEST G ON G.CODGEST = N.GEST '||vCondSub_G||'
      WHERE NS.REST &lt;&gt; 0';

      vSelIes_Per  := '
      SELECT NS.CODOBIECT, SUM(L1.CANT) CANT, ''IES''
      FROM LIVR L
        INNER JOIN LIVR1 l1 ON L1.CODLIVR = L.CODLIVR
        INNER JOIN IESIRI I ON L.CODIES = I.CODIES
        INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES AND L1.CODIES1 = I1.CODIES1
        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 '||vCondSub_G||'
      WHERE L.DATALIVR BETWEEN '''||to_char(vZiuaIni)||''' AND '''||to_char(vZiuaFin)||'''
        AND NVL(I.ANULAT,0) = 0 AND I.OPERAT = 1 AND I.TIPDOC IN ('||current_setting('PKG_LIST_BASE_NAPROVIZ2.vTipVanz', true)||')';

      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vVanzEmul', true)::boolean then
        vSelIes_Emul  := '
        SELECT E1.CODOBIECT, SUM(E1.CANT) CANT, ''EMUL''
        FROM EMULARE1 E1
          INNER JOIN EMULARE E ON E.CODEMULARE = E1.CODEMULARE
          INNER JOIN NGEST G ON G.CODGEST = E1.CODGEST '||vCondSub_G||'
        WHERE E.DATABON BETWEEN '''||to_char(vZiuaIni)||''' AND '''||to_char(vZiuaFin)||'''
          AND NVL(E.PRELUAT, 0) = 0
          AND NVL(E.FACTURARE, 0) = 0
        GROUP BY E1.CODOBIECT';
      end if;

      vSelTr_Per := '';
      if Instr(current_setting('PKG_LIST_BASE_NAPROVIZ2.vTipVanz', true),'12') &gt; 0 then
        vSelTr_Per  := '
          SELECT NS.CODOBIECT, SUM(L1.CANT) CANT, ''IES''
          FROM LIVR L
            INNER JOIN LIVR1 l1 ON L1.CODLIVR = L.CODLIVR
            INNER JOIN TRANSF T ON T.CODTRANSF = L.CODTRANSF
            INNER JOIN TRANSF1 T1 ON T1.CODTRANSF = T.CODTRANSF AND L1.CODIES1 = T1.CODTRANSF1
            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 '||vCondSub_G||'
          WHERE L.DATALIVR BETWEEN '''||to_char(vZiuaIni)||''' AND '''||to_char(vZiuaFin)||'''
            AND NVL(T.ANULAT,0) = 0 AND T.OPERAT = 1 AND T.TIPDOC = 12 ';
      end if;

      IF NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', true)::boolean 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';
        vAux := '
        AND';
        IF    vCateLGest = 0 THEN vAux := vAux||' N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
        ELSIF vCateGest  = 0 THEN vAux := vAux||' NS.CODLOCATIE::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'') ';
        ELSE vAux := vAux||' (N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') OR NS.CODLOCATIE IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'')) ';
        END IF;
        vSelStocReal := vSelStocReal ||vAux;
        vSelStocInit := vSelStocInit ||vAux;
        vSelIes_Per := vSelIes_Per   ||vAux;
        if Length(vSelTr_Per) &gt; 0 then
          vSelTr_Per := vSelTr_Per   ||vAux;
        end if;
      END IF;

      IF NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateIOArt', true)::boolean THEN
        vAux := '
        AND NS.CODIOART::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
        vSelStocReal := vSelStocReal ||vAux;
        vSelStocInit := vSelStocInit ||vAux;
        vSelIes_Per := vSelIes_Per   ||vAux;
        if Length(vSelTr_Per) &gt; 0 then
          vSelTr_Per := vSelTr_Per   ||vAux;
        end if;
      END IF;

      vSelStocReal := vSelStocReal ||'
      GROUP BY NS.CODOBIECT';
      vSelStocInit := vSelStocInit ||'
      GROUP BY NS.CODOBIECT';
      vSelIes_Per  := vSelIes_Per||'
      GROUP BY NS.CODOBIECT';
      if Length(vSelTr_Per) &gt; 0 then
        vSelTr_Per  := vSelTr_Per||'
        GROUP BY NS.CODOBIECT';
      end if;
      sJoinRestCmd := '';
      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vRestCmd', true)::boolean then
        sJoinRestCmd := ' INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = C1.GESTACT::varchar AND FILTRU = ''CODGEST'' ';
      end if;

      vFiltruTermen := '';
      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vCuTermen', true)::boolean then
        vFiltruTermen := ' AND C1.TERMEN &lt;= '''||current_setting('PKG_LIST_BASE_NAPROVIZ2.vTermen', true)||''' ';
      end if;

      /************************ Sfarsit Constructie Selecturi Auxiliare ***************************/

      PERFORM PKG_GLOBALS_SetSeparator(',');
      DELETE FROM TMP_CMD_TMP;
      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vCuComenzi', true)::boolean then
        sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,auxfield)
        SELECT C1.CodObiect,
          SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
          SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
          SUM(C1.RestAcceptat) RestA, ''CF'', String_Agg(to_char(C.nrdoc), '''')
        FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
        WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
          AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 8 '||vCondSub_C||'
          AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= to_date('''||to_char(vZiuaFinC)||''',''dd.mm.yyyy'')
          '||vFiltruTermen||'
        GROUP BY C1.CodObiect';
        EXECUTE sSelect;
        sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip)
        SELECT C1.CodObiect,
          SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
          SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
          SUM(C1.RestAcceptat) RestA, ''CC''
        FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
        WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
          AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 18 '||vCondSub_C||'
          AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= to_date('''||to_char(vZiuaFinC)||''',''dd.mm.yyyy'')
        GROUP BY C1.CodObiect';
        EXECUTE sSelect;
        sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip)
        SELECT C1.CodObiect,
          SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
          SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
          SUM(C1.RestAcceptat) RestA, ''CSERV''
        FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
        WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
          AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 92 '||vCondSub_C||'
          AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= to_date('''||to_char(vZiuaFinC)||''',''dd.mm.yyyy'')
        GROUP BY C1.CodObiect';
        EXECUTE sSelect;
        sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip)
        SELECT C1.CodObiect,
          SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
          SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
          SUM(C1.RestAcceptat) RestA, ''CSIN''
        FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
        WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
          AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 44 '||vCondSub_C||'
          AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= to_date('''||to_char(vZiuaFinC)||''',''dd.mm.yyyy'')
        GROUP BY C1.CodObiect';
        EXECUTE sSelect;
        sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip)
        SELECT C1.CodObiect,
          SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
          SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
          SUM(C1.RestAcceptat) RestA, ''CSIES''
        FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
        WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
          AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 44 '||vCondSub_CS||'
          AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= to_date('''||to_char(vZiuaFinC)||''',''dd.mm.yyyy'')
        GROUP BY C1.CodObiect';
        EXECUTE sSelect;
        sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip)
        SELECT C1.CodObiect,
          SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantComandat else 0 end) CantC,
          SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then C1.CantAcceptat else 0 end) CantA,
          SUM(C1.RestAcceptat) RestA, ''CG''
        FROM COMANDA1 C1
          INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
          INNER JOIN NGEST G ON C.CodGest = G.CodGest'||sJoinRestCmd||'
        WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
          AND C.Operat = 1 AND C.Anulat = 0 AND G.Tip = 1 AND C.TipDoc = 43 '||vCondSub_C||'
          AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= to_date('''||to_char(vZiuaFinC)||''',''dd.mm.yyyy'')
        GROUP BY C1.CodObiect';
        EXECUTE sSelect;
        sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip)
        SELECT CMDMAT.CodObiect,
          SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then CMDMAT.Cant else 0 end) CantC,
          SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then CMDMAT.Cant else 0 end) CantA,
          SUM(CMDMAT.Rest) RestA, ''CIIN''
        FROM CMDPRODMAT CMDMAT
          INNER JOIN COMANDA1 C1 ON CMDMAT.CodComanda1 = C1.CodComanda1
          INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
        WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
          AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 53 '||vCondSub_C||'
          AND CMDMAT.Rest &gt; 0 AND C.DataDoc &lt;= to_date('''||to_char(vZiuaFinC)||''',''dd.mm.yyyy'')
          AND ((C1.Consum = 1 AND CMDMAT.Tip &lt;&gt; 1) OR (C1.Consum = 2 AND CMDMAT.Tip = 2))
        GROUP BY CMDMAT.CodObiect';
        EXECUTE sSelect;
        sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip)
        SELECT CMDMAT.CodObiect,
          SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then CMDMAT.Cant else 0 end) CantC,
          SUM(case when C.DataDoc BETWEEN '''||to_char(vZiuaIniC)||''' AND '''||to_char(vZiuaFinC)||''' then CMDMAT.Cant else 0 end) CantA,
          SUM(CMDMAT.Rest) RestA, ''CIIES''
        FROM CMDPRODMAT CMDMAT
          INNER JOIN COMANDA1 C1 ON CMDMAT.CodComanda1 = C1.CodComanda1
          INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
        WHERE Nvl(C.INCHISA, 0) = 0 AND COALESCE(C1.EXCEPTIONAL,0) = 0
          AND C.Operat = 1 AND C.Anulat = 0 '||vCondSub_C||'
          AND CMDMAT.Rest &gt; 0 AND C.DataDoc &lt;= to_date('''||to_char(vZiuaFinC)||''',''dd.mm.yyyy'')
          AND ((C1.Consum = 1 AND CMDMAT.Tip = 1) OR (C1.Consum = 2 AND CMDMAT.Tip &lt;&gt; 2))
        GROUP BY CMDMAT.CodObiect';
        EXECUTE sSelect;
      end if;

      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,resta,tip)
      SELECT I1.CodObiect,
        SUM(L1.RestIESVAL) RestA, ''IESNED''
      FROM LIVR1 L1
        INNER JOIN LIVR L ON L.CODLIVR = L1.CODLIVR
        INNER JOIN IESIRI I ON I.CODIES = L.CODIES
        INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES AND L1.CODIES1 = I1.CODIES1
        INNER JOIN LIVRVAL LV ON LV.CODLIVR1 = L1.CODLIVR1'||chr(13);
      if NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', true)::boolean THEN
        sSelect := sSelect||'INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = LV.GEST::varchar AND FILTRU = ''CODGEST'''||chr(13);
      end if;
      sSelect := sSelect||'
      WHERE I.Operat = 1 AND I.Anulat = 0 '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('I')||'
        AND L1.RestIESVAL &lt;&gt; 0
      GROUP BY I1.CodObiect';

      EXECUTE sSelect;

      --DELETE FROM TMP_STOCREAL;
      EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip) '||vSelStocReal;
      EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip) '||vSelStocInit;
      EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip) '||vSelIes_Per;
      if Length(vSelTr_Per) &gt; 0 then
        EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip) '||vSelTr_Per;
      end if;

      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vVanzEmul', true)::boolean then
        EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip) '||vSelIes_Emul;
      end if;

      Luni := 0;
      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vPeLuni', true)::boolean then
        for v_rec in (extract(year from vZiuaIni)*12+extract(month from vZiuaIni)) .. (extract(year from vZiuaFin)*12+extract(month from vZiuaFin)) loop
          if Luni &gt; 12 then Exit; end if;
          Luni := Luni + 1;
          if v_rec/12 = trunc(v_rec/12) then
            vLunaV := 12;
            vAnV   := v_rec/12 - 1;
          else
            vLunaV := v_rec - trunc(v_rec/12)*12;
            vAnV   := trunc(v_rec/12);
          end if;
          if vLunaV =  1 then sLuna := 'Ian'; end if;
          if vLunaV =  2 then sLuna := 'Feb'; end if;
          if vLunaV =  3 then sLuna := 'Mar'; end if;
          if vLunaV =  4 then sLuna := 'Apr'; end if;
          if vLunaV =  5 then sLuna := 'Mai'; end if;
          if vLunaV =  6 then sLuna := 'Jun'; end if;
          if vLunaV =  7 then sLuna := 'Jul'; end if;
          if vLunaV =  8 then sLuna := 'Aug'; end if;
          if vLunaV =  9 then sLuna := 'Sep'; end if;
          if vLunaV = 10 then sLuna := 'Oct'; end if;
          if vLunaV = 11 then sLuna := 'Nov'; end if;
          if vLunaV = 12 then sLuna := 'Dec'; end if;

          vSelIes_Per  := '
          SELECT I1.CODOBIECT, SUM(L1.CANT) CANT,'''||sLuna||'''
          FROM LIVR L
            INNER JOIN LIVR1 l1 ON L1.CODLIVR = L.CODLIVR
            INNER JOIN IESIRI I ON L.CODIES = I.CODIES
            INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES 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
            LEFT JOIN NGEST G ON G.CODGEST = COALESCE(N.GEST,LV.GEST) '||vCondSub_G||'
          WHERE I.AN*12+I.LUNA = '||to_char(vAnV*12+vLunaV)||'
            AND NVL(I.ANULAT,0) = 0 AND I.OPERAT = 1 AND I.TIPDOC IN ('||current_setting('PKG_LIST_BASE_NAPROVIZ2.vTipVanz', true)||')';

          vAux := '';
          IF NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', true)::boolean 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';
            vAux := '
            AND';
            IF    vCateLGest = 0 THEN vAux := vAux||' COALESCE(N.GEST,LV.GEST)::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
            ELSIF vCateGest  = 0 THEN vAux := vAux||' NS.CODLOCATIE::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'') ';
            ELSE vAux := vAux||' (COALESCE(N.GEST,LV.GEST)::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') OR NS.CODLOCATIE IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'')) ';
            END IF;
            vSelIes_Per := vSelIes_Per   ||vAux;
          END IF;

          IF NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateIOArt', true)::boolean THEN
            vAux := '
            AND COALESCE(NS.CODIOART,LV.CODIOART)::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
            vSelIes_Per := vSelIes_Per   ||vAux;
          END IF;
          vSelIes_Per  := vSelIes_Per||'
          GROUP BY I1.CODOBIECT';
          EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip) '||vSelIes_Per;
        end loop;
      end if;

      DELETE FROM TMP_STOCREZ;
      sSelect := 'INSERT INTO tmp_stocrez(codobiect,rezervat)
      SELECT NS.CODOBIECT, SUM(R.REST) REZERVAT
      FROM REZERVATS R
        INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = R.CODNIRSTOC
        INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
        INNER JOIN NGEST G ON G.CODGEST = N.GEST '||vCondSub_G||'
      WHERE NVL(R.REST,0) &gt; 0';

      if NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', true)::boolean 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
          sSelect := sSelect || ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = N.GEST::varchar)';
        elsif vCateGest = 0 then
          sSelect := sSelect || ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND VALOARE = NS.CODLOCATIE::varchar)';
        else
          sSelect := sSelect || ' 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;
      if NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateIOArt', true)::boolean then
        sSelect := sSelect || ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND VALOARE = NS.CODIOART::varchar ) ';
      end if;
      sSelect := sSelect ||' GROUP BY NS.CODOBIECT';
      EXECUTE sSelect;

      IF current_setting('PKG_LIST_BASE_NAPROVIZ2.vUltAchiz', true)::boolean
      THEN   sUltNirstoc := 'SELECT CODOBIECT,D1,D2,D3,MAX(CODNIRSTOC) CODNIRSTOC
                      FROM (SELECT CODOBIECT,D1,D2,D3,CODNIRSTOC,dense_rank() over(partition by CODOBIECT,D1,D2,D3 ORDER BY DATAACHIZ desc, CODNIRSTOC desc) NR
                            FROM NIRSTOC
                            WHERE FURN &gt; 0 AND coalesce(CODNIRSTOCPARINTE,0) = 0 ) xx
                      WHERE xx.NR=1
                      GROUP BY CODOBIECT,D1,D2,D3';
       ELSE sUltNirstoc := 'SELECT 0 CODOBIECT, 0 CODNIRSTOC';
      END IF;
    end if;
  end if;

  if tmpName &lt;&gt; 'TMP_LST_NAPR2' then
    if vDefalcare then
      sAfectare := '';
      --if pkg_list_base_naproviz2.GETPEZILE = 1 then
        if current_setting('PKG_LIST_BASE_NAPROVIZ2.vAfectare', true)::NUMERIC = 1 then
          sAfectare := ' - NVL(NAOS.STOCMIN,0) ';
        end if;
        if current_setting('PKG_LIST_BASE_NAPROVIZ2.vAfectare', true)::NUMERIC = 2 then
          sAfectare := ' - NVL(NAOS.STOCMED,0) ';
        end if;
        if current_setting('PKG_LIST_BASE_NAPROVIZ2.vAfectare', true)::NUMERIC = 3 then
          sAfectare := ' - NVL(NAOS.STOCMAX,0) ';
        end if;
      --end if;
      for v_sub in (select t.codsubunit, s.den_subunit
                    from tmp_subunitdedicate t
                         inner join nsubunit s on s.codsubunit = t.codsubunit
                   ) loop
        if current_setting('PKG_LIST_BASE_NAPROVIZ2.vDim', true)::boolean then
          INSERT INTO TMP_CMD_TMP(CODOBIECT, TIP, D1, D2, D3)
          SELECT DISTINCT CODOBIECT, 'OBJ', D1, D2, D3
          FROM
          (SELECT CODOBIECT, D1, D2, D3
           FROM TMP_CMD_TMP
           UNION ALL
           SELECT CODOBIECT, D1, D2, D3
           FROM TMP_STOCREAL
          )a_pg;
          sInsert:=
          'INSERT INTO '||tmpName||'(
            CodObiect,Articol, UM, TotVanz, MedieVanz, MedieVanzZ,
            Necesar,
            StocReal,
            CodExtern, CodIntern, Producator, StocMIN, StocMED, StocMAX,
            CantC_CF, CantA_CF, RestA_CF,
            CantC_CC, CantA_CC, RestA_CC,
            CantC_CSERV, CantA_CSERV, RestA_CSERV,
            CantC_CSIn, CantA_CSIn, RestA_CSIn,
            CantC_CSIes, CantA_CSIes, RestA_CSIes,
            CantC_CG, CantA_CG, RestA_CG,
            CantC_CIIn, CantA_CIIn, RestA_CIIn,
            CantC_CIIes, CantA_CIIes, RestA_CIIes,
            Rezervat, UltFurn, UltPrAchiz, NrComFurn, NrZile, NrZileNec, D1, D2, D3, CodSubunit, Subunitatea, VanzPrec'||gUserFields||')
          SELECT
            NAO.CODOBIECT, NAO.DENUMIRE, NUM.DEN_UM, COALESCE(IP.CANT,0) TOTVANZ, CEIL(COALESCE(IP.CANT,0) / '||vNrLuni||') MEDIEVANZ,
            COALESCE(IP.CANT,0) / '||vNrZilePer||' MEDIEVANZZ,
            --GREATEST(CEIL(COALESCE(IP.CANT,0) / '||vNrLuni||') - NVL(SR.Cant, 0) - NVL(SI.Cant, 0) - NVL(CG.RESTA,0) + NVL(CF.RESTA,0) - NVL(CC.RESTA,0) - NVL(CSERV.RESTA,0) + NVL(CSIN.RESTA,0) - NVL(CSIES.RESTA,0) + NVL(CIIN.RESTA,0) - NVL(CIIES.RESTA,0),0) Necesar,
            GREATEST(CEIL(COALESCE(COALESCE(IP.CANT,0),0) / '||vNrZilePer||' * '||current_setting('PKG_LIST_BASE_NAPROVIZ2.vNrZile', true)||') - NVL(SR.Cant, 0)'||sAfectare||' + NVL(CG.RESTA,0) - NVL(CF.RESTA,0) + NVL(CC.RESTA,0) + NVL(CSERV.RESTA,0) - NVL(CSIN.RESTA,0) + NVL(CSIES.RESTA,0) - NVL(CIIN.RESTA,0) + NVL(CIIES.RESTA,0),0) Necesar, '||chr(13);
          sInsert := sInsert||'
            NVL(SR.CANT,0) STOCREAL,
            NAO.CODEXTERN, NAO.CODINTERN, PROD.DEN_PART'||sColMinMax||',
            NVL(CF.CANTC,0), NVL(CF.CANTA,0), NVL(CF.RESTA,0),
            NVL(CC.CANTC,0), NVL(CC.CANTA,0), NVL(CC.RESTA,0),
            NVL(CSERV.CANTC,0), NVL(CSERV.CANTA,0), NVL(CSERV.RESTA,0),
            NVL(CSIN.CANTC,0), NVL(CSIN.CANTA,0), NVL(CSIN.RESTA,0),
            NVL(CSIES.CANTC,0), NVL(CSIES.CANTA,0), NVL(CSIES.RESTA,0),
            NVL(CG.CANTC,0), NVL(CG.CANTA,0), NVL(CG.RESTA,0),
            NVL(CIIN.CANTC,0), NVL(CIIN.CANTA,0), NVL(CIIN.RESTA,0),
            NVL(CIIES.CANTC,0), NVL(CIIES.CANTA,0), NVL(CIIES.RESTA,0),
            SREZ.REZERVAT, UF.DEN_PART, NVL(UNS.PRET,0) - Nvl(UNS.ADAOS,0), CF.AuxField,'||vNrZilePer||','||current_setting('PKG_LIST_BASE_NAPROVIZ2.vNrZile', true)||',
            TMP.D1, TMP.D2, TMP.D3,'||to_char(v_sub.codsubunit)||','''||v_sub.den_subunit||''', IPP.CANT'||gUserAlias||'
          FROM (SELECT CODOBIECT, D1, D2, D3 FROM TMP_CMD_TMP WHERE TIP = ''OBJ'') TMP
            INNER JOIN NARTOBJ NAO ON NAO.CODOBIECT = TMP.CODOBIECT
            INNER JOIN NART NA ON NA.CODARTICOL = NAO.CODARTICOL
            INNER JOIN NUM ON NUM.CODUM = NA.UM
            LEFT JOIN ('||sUltNirstoc||') X ON X.CODOBIECT = NAO.CODOBIECT
            LEFT JOIN NIRSTOC UNS ON UNS.CODNIRSTOC = X.CODNIRSTOC
            LEFt JOIN NPART UF ON UF.CODPART = UNS.FURN
            LEFT JOIN NIR UNIR ON UNIR.CODNIR = UNS.CODNIR
            LEFT JOIN INTRARI UINTR ON UINTR.CODINTR = UNIR.CODINTR AND UINTR.TIPDOC = 6
            LEFT JOIN NSUBUNIT USUB ON USUB.CODSUBUNIT = UINTR.CODSUBUNIT
            LEFT JOIN NARTOBJSUBUNIT NAOS ON NAO.CODOBIECT = NAOS.CODOBIECT
                                          and (NAOS.codgest is null or NAOS.codgest = 0)
                                          AND NAOS.SUBUNITATE = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_STOCREAL SR ON SR.CODOBIECT = NAO.CODOBIECT AND SR.TIP = ''REAL'' AND SR.D1 = TMP.D1 AND SR.D2 = TMP.D2 AND SR.D3 = TMP.D3 AND SR.CODGEST = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_STOCREZ SREZ ON SREZ.CODOBIECT = NAO.CODOBIECT AND SREZ.D1 = TMP.D1 AND SREZ.D2 = TMP.D2 AND SREZ.D3 = TMP.D3 AND SREZ.CODGEST = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_STOCREAL SI ON SI.CODOBIECT = NAO.CODOBIECT AND SI.TIP = ''INIT'' AND SI.D1 = TMP.D1 AND SI.D2 = TMP.D2 AND SI.D3 = TMP.D3 AND SI.CODGEST = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_CMD_TMP CF ON CF.CODOBIECT = NAO.CODOBIECT AND CF.TIP = ''CF'' AND CF.D1 = TMP.D1 AND CF.D2 = TMP.D2 AND CF.D3 = TMP.D3 AND CF.CODSUBUNIT = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_CMD_TMP CC ON CC.CODOBIECT = NAO.CODOBIECT AND CC.TIP = ''CC'' AND CC.D1 = TMP.D1 AND CC.D2 = TMP.D2 AND CC.D3 = TMP.D3 AND CC.CODSUBUNIT = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_CMD_TMP CSERV ON CSERV.CODOBIECT = NAO.CODOBIECT AND CSERV.TIP = ''CSERV'' AND CSERV.D1 = TMP.D1 AND CSERV.D2 = TMP.D2 AND CSERV.D3 = TMP.D3 AND CSERV.CODSUBUNIT = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_CMD_TMP CSIN ON CSIN.CODOBIECT = NAO.CODOBIECT AND CSIN.TIP = ''CSIN'' AND CSIN.D1 = TMP.D1 AND CSIN.D2 = TMP.D2 AND CSIN.D3 = TMP.D3 AND CSIN.CODSUBUNIT = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_CMD_TMP CSIES ON CSIES.CODOBIECT = NAO.CODOBIECT AND CSIES.TIP = ''CSIES'' AND CSIES.D1 = TMP.D1 AND CSIES.D2 = TMP.D2 AND CSIES.D3 = TMP.D3 AND CSIES.CODSUBUNIT = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_CMD_TMP CG ON CG.CODOBIECT = NAO.CODOBIECT AND CG.TIP = ''CG'' AND CG.D1 = TMP.D1 AND CG.D2 = TMP.D2 AND CG.D3 = TMP.D3 AND CG.CODSUBUNIT = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_CMD_TMP CIIN ON CIIN.CODOBIECT = NAO.CODOBIECT AND CIIN.TIP = ''CIIN'' AND CIIN.D1 = TMP.D1 AND CIIN.D2 = TMP.D2 AND CIIN.D3 = TMP.D3 AND CIIN.CODSUBUNIT = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_CMD_TMP CIIES ON CIIES.CODOBIECT = NAO.CODOBIECT AND CIIES.TIP = ''CIIES'' AND CIIES.D1 = TMP.D1 AND CIIES.D2 = TMP.D2 AND CIIES.D3 = TMP.D3 AND CIIES.CODSUBUNIT = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN NPART PROD ON PROD.CODPART = NAO.CODPRODUCATOR
            LEFT JOIN (select codobiect, sum(cant) cant, tip, D1, D2, D3 from TMP_STOCREAL where tip = ''IES''  AND CODGEST = '||to_char(v_sub.codsubunit)||' group by codobiect, tip, D1, D2, D3) IP ON IP.CODOBIECT = NAO.CODOBIECT AND IP.TIP = ''IES''
                      AND IP.D1 = TMP.D1 AND IP.D2 = TMP.D2 AND IP.D3 = TMP.D3
            LEFT JOIN (select codobiect, sum(cant) cant, tip, D1, D2, D3 from TMP_STOCREAL where tip = ''IESPREC'' group by codobiect, tip, D1, D2, D3) IPP ON IPP.CODOBIECT = NAO.CODOBIECT AND IPP.TIP = ''IESPREC''
                      AND IPP.D1 = TMP.D1 AND IPP.D2 = TMP.D2 AND IPP.D3 = TMP.D3
            LEFT JOIN NCLASEA CLSA ON CLSA.CODCLASEA = NA.CLASA
            LEFT JOIN NCLASEAS CLSAS ON CLSAS.CODCLASEAS = NA.CLASASTATIST'||
            gSuplJoins||'
          WHERE NA.TIPARTICOL = ''0'' and coalesce(NAO.Blocat,0) in (0,3) ';
        PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
        else
          sInsert:=
          'INSERT INTO '||tmpName||'(
            CodObiect,Articol, UM, TotVanz, MedieVanz, MedieVanzZ,
            Necesar,
            StocReal,
            CodExtern, CodIntern, Producator, StocMIN, StocMED, StocMAX,
            CantC_CF, CantA_CF, RestA_CF,
            CantC_CC, CantA_CC, RestA_CC,
            CantC_CSERV, CantA_CSERV, RestA_CSERV,
            CantC_CSIn, CantA_CSIn, RestA_CSIn,
            CantC_CSIes, CantA_CSIes, RestA_CSIes,
            CantC_CG, CantA_CG, RestA_CG,
            CantC_CIIn, CantA_CIIn, RestA_CIIn,
            CantC_CIIes, CantA_CIIes, RestA_CIIes,
            Rezervat, UltFurn, UltPrAchiz, NrComFurn, NrZile, NrZileNec, CodSubunit, Subunitatea, VanzPrec'||gUserFields||')
          SELECT
            NAO.CODOBIECT, NAO.DENUMIRE, NUM.DEN_UM, COALESCE(IP.CANT,0) TOTVANZ, CEIL(COALESCE(IP.CANT,0) / '||vNrLuni||') MEDIEVANZ,
            COALESCE(IP.CANT,0) / '||vNrZilePer||' MEDIEVANZZ,
            --GREATEST(CEIL(COALESCE(IP.CANT,0) / '||vNrLuni||') - NVL(SR.Cant, 0) - NVL(SI.Cant, 0) - NVL(CG.RESTA,0) + NVL(CF.RESTA,0) - NVL(CC.RESTA,0) - NVL(CSERV.RESTA,0) + NVL(CSIN.RESTA,0) - NVL(CSIES.RESTA,0) + NVL(CIIN.RESTA,0) - NVL(CIIES.RESTA,0),0) Necesar,
            GREATEST(CEIL(COALESCE(IP.CANT,0) / '||vNrZilePer||' * '||current_setting('PKG_LIST_BASE_NAPROVIZ2.vNrZile', true)||') - NVL(SR.Cant, 0)'||sAfectare||' + NVL(CG.RESTA,0) - NVL(CF.RESTA,0) + NVL(CC.RESTA,0) + NVL(CSERV.RESTA,0) - NVL(CSIN.RESTA,0) + NVL(CSIES.RESTA,0) - NVL(CIIN.RESTA,0) + NVL(CIIES.RESTA,0),0) Necesar, '||chr(13);
          sInsert := sInsert||'
            NVL(SR.CANT,0) STOCREAL,
            NAO.CODEXTERN, NAO.CODINTERN, PROD.DEN_PART'||sColMinMax||',
            NVL(CF.CANTC,0), NVL(CF.CANTA,0), NVL(CF.RESTA,0),
            NVL(CC.CANTC,0), NVL(CC.CANTA,0), NVL(CC.RESTA,0),
            NVL(CSERV.CANTC,0), NVL(CSERV.CANTA,0), NVL(CSERV.RESTA,0),
            NVL(CSIN.CANTC,0), NVL(CSIN.CANTA,0), NVL(CSIN.RESTA,0),
            NVL(CSIES.CANTC,0), NVL(CSIES.CANTA,0), NVL(CSIES.RESTA,0),
            NVL(CG.CANTC,0), NVL(CG.CANTA,0), NVL(CG.RESTA,0),
            NVL(CIIN.CANTC,0), NVL(CIIN.CANTA,0), NVL(CIIN.RESTA,0),
            NVL(CIIES.CANTC,0), NVL(CIIES.CANTA,0), NVL(CIIES.RESTA,0),
            SREZ.REZERVAT, UF.DEN_PART, NVL(UNS.PRET,0) - Nvl(UNS.ADAOS,0), CF.AuxField,'||vNrZilePer||','||current_setting('PKG_LIST_BASE_NAPROVIZ2.vNrZile', true)||
            ','||to_char(v_sub.codsubunit)||','''||v_sub.den_subunit||''', IPP.CANT'||gUserAlias||'
          FROM NARTOBJ NAO
            INNER JOIN NART NA ON NA.CODARTICOL = NAO.CODARTICOL
            INNER JOIN NUM ON NUM.CODUM = NA.UM
            LEFT JOIN ('||sUltNirstoc||') X ON X.CODOBIECT = NAO.CODOBIECT
            LEFT JOIN NIRSTOC UNS ON UNS.CODNIRSTOC = X.CODNIRSTOC
            LEFt JOIN NPART UF ON UF.CODPART = UNS.FURN
            LEFT JOIN NIR UNIR ON UNIR.CODNIR = UNS.CODNIR
            LEFT JOIN INTRARI UINTR ON UINTR.CODINTR = UNIR.CODINTR AND UINTR.TIPDOC = 6
            LEFT JOIN NSUBUNIT USUB ON USUB.CODSUBUNIT = UINTR.CODSUBUNIT
            LEFT JOIN NARTOBJSUBUNIT NAOS ON NAO.CODOBIECT = NAOS.CODOBIECT
                                          and (NAOS.codgest is null or NAOS.codgest = 0)
                                          AND NAOS.SUBUNITATE = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_STOCREAL SR ON SR.CODOBIECT = NAO.CODOBIECT AND SR.TIP = ''REAL'' AND SR.CODGEST = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_STOCREZ SREZ ON SREZ.CODOBIECT = NAO.CODOBIECT AND SREZ.CODGEST = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_STOCREAL SI ON SI.CODOBIECT = NAO.CODOBIECT AND SI.TIP = ''INIT'' AND SI.CODGEST = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_CMD_TMP CF ON CF.CODOBIECT = NAO.CODOBIECT AND CF.TIP = ''CF'' AND CF.CODSUBUNIT = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_CMD_TMP CC ON CC.CODOBIECT = NAO.CODOBIECT AND CC.TIP = ''CC'' AND CC.CODSUBUNIT = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_CMD_TMP CSERV ON CSERV.CODOBIECT = NAO.CODOBIECT AND CSERV.TIP = ''CSERV'' AND CSERV.CODSUBUNIT = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_CMD_TMP CSIN ON CSIN.CODOBIECT = NAO.CODOBIECT AND CSIN.TIP = ''CSIN'' AND CSIN.CODSUBUNIT = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_CMD_TMP CSIES ON CSIES.CODOBIECT = NAO.CODOBIECT AND CSIES.TIP = ''CSIES'' AND CSIES.CODSUBUNIT = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_CMD_TMP CG ON CG.CODOBIECT = NAO.CODOBIECT AND CG.TIP = ''CG'' AND CG.CODSUBUNIT = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_CMD_TMP CIIN ON CIIN.CODOBIECT = NAO.CODOBIECT AND CIIN.TIP = ''CIIN'' AND CIIN.CODSUBUNIT = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN TMP_CMD_TMP CIIES ON CIIES.CODOBIECT = NAO.CODOBIECT AND CIIES.TIP = ''CIIES'' AND CIIES.CODSUBUNIT = '||to_char(v_sub.codsubunit)||'
            LEFT JOIN NPART PROD ON PROD.CODPART = NAO.CODPRODUCATOR
            LEFT JOIN (select codobiect, sum(cant) cant, tip from TMP_STOCREAL where tip = ''IES'' AND CODGEST = '||to_char(v_sub.codsubunit)||' group by codobiect, tip) IP ON IP.CODOBIECT = NAO.CODOBIECT AND IP.TIP = ''IES''
            LEFT JOIN (select codobiect, sum(cant) cant, tip from TMP_STOCREAL where tip = ''IESPREC'' group by codobiect, tip) IPP ON IPP.CODOBIECT = NAO.CODOBIECT AND IPP.TIP = ''IESPREC''
            LEFT JOIN NCLASEA CLSA ON CLSA.CODCLASEA = NA.CLASA
            LEFT JOIN NCLASEAS CLSAS ON CLSAS.CODCLASEAS = NA.CLASASTATIST'||
            gSuplJoins||'
          WHERE NA.TIPARTICOL = ''0'' and coalesce(NAO.Blocat,0) in (0,3) ';
        end if;
        if current_setting('pkg_list_base_naproviz2.vProd', TRUE)::NUMERIC &gt; 0 then
          sInsert := sInsert||' and NAO.CodProducator = '|| current_setting('pkg_list_base_naproviz2.vProd', TRUE);
        end if;
        if NOT current_setting('pkg_list_base_naproviz2.vAllCls', TRUE)::boolean then
            sInsert := sInsert||' and exists (select tmp.valoare from tmp_manevra_liste tmp, nclasea clsx
                                            where tmp.filtru = ''CODCLASEA'' and tmp.valoare = clsx.codclasea::varchar
                                                  and INSTRB(CLSA.CODIDENT, clsx.codident) = 1) ';
        END IF;
        PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
      end loop;
    ELSE
      sAfectare := '';
      --if pkg_list_base_naproviz2.GETPEZILE = 1 then
        if current_setting('PKG_LIST_BASE_NAPROVIZ2.vAfectare', true)::NUMERIC = 1 then
          sAfectare := ' - NVL(NAOS.STOCMIN,0) ';
        end if;
        if current_setting('PKG_LIST_BASE_NAPROVIZ2.vAfectare', true)::NUMERIC = 2 then
          sAfectare := ' - NVL(NAOS.STOCMED,0) ';
        end if;
        if current_setting('PKG_LIST_BASE_NAPROVIZ2.vAfectare', true)::NUMERIC = 3 then
          sAfectare := ' - NVL(NAOS.STOCMAX,0) ';
        end if;
      --end if;
      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vDim', true)::boolean then
        INSERT INTO TMP_CMD_TMP(CODOBIECT, TIP, D1, D2, D3)
        SELECT DISTINCT CODOBIECT, 'OBJ', D1, D2, D3
        FROM
        (SELECT CODOBIECT, D1, D2, D3
         FROM TMP_CMD_TMP
         UNION ALL
         SELECT CODOBIECT, D1, D2, D3
         FROM TMP_STOCREAL
        )b_pg;
        sInsert:=
        'INSERT INTO '||tmpName||'(
          CodObiect,Articol, UM, TotVanz, MedieVanz, MedieVanzZ,
          Necesar,
          StocReal,
          CodExtern, CodIntern, Producator, StocMIN, StocMED, StocMAX,
          CantC_CF, CantA_CF, RestA_CF,
          CantC_CC, CantA_CC, RestA_CC,
          CantC_CSERV, CantA_CSERV, RestA_CSERV,
          CantC_CSIn, CantA_CSIn, RestA_CSIn,
          CantC_CSIes, CantA_CSIes, RestA_CSIes,
          CantC_CG, CantA_CG, RestA_CG,
          CantC_CIIn, CantA_CIIn, RestA_CIIn,
          CantC_CIIes, CantA_CIIes, RestA_CIIes,
          Rezervat, UltFurn, UltPrAchiz, NrComFurn, NrZile, NrZileNec, D1, D2, D3, VanzPrec'||gUserFields||')
        SELECT
          NAO.CODOBIECT, NAO.DENUMIRE, NUM.DEN_UM, COALESCE(IP.CANT,0) TOTVANZ, CEIL(COALESCE(IP.CANT,0) / '||vNrLuni||') MEDIEVANZ,
          COALESCE(IP.CANT,0) / '||vNrZilePer||' MEDIEVANZZ,
          --GREATEST(CEIL(COALESCE(IP.CANT,0) / '||vNrLuni||') - NVL(SR.Cant, 0) - NVL(SI.Cant, 0) - NVL(CG.RESTA,0) + NVL(CF.RESTA,0) - NVL(CC.RESTA,0) - NVL(CSERV.RESTA,0) + NVL(CSIN.RESTA,0) - NVL(CSIES.RESTA,0) + NVL(CIIN.RESTA,0) - NVL(CIIES.RESTA,0),0) Necesar,';
        if current_setting('PKG_LIST_BASE_NAPROVIZ2.vPeZile', true)::boolean then
          sInsert := sInsert||'
            GREATEST(CEIL(COALESCE(COALESCE(IP.CANT,0),0) / '||vNrZilePer||' * '||current_setting('PKG_LIST_BASE_NAPROVIZ2.vNrZile', true)||') - NVL(SR.Cant, 0)'||sAfectare||' + NVL(CG.RESTA,0) - NVL(CF.RESTA,0) + NVL(CC.RESTA,0) + NVL(CSERV.RESTA,0) - NVL(CSIN.RESTA,0) + NVL(CSIES.RESTA,0) - NVL(CIIN.RESTA,0) + NVL(CIIES.RESTA,0),0) Necesar, '||chr(13);
        else
          sInsert := sInsert||'
            GREATEST(CEIL(COALESCE(COALESCE(IP.CANT,0),0) / '||vNrLuni||') - NVL(SR.Cant, 0)'||sAfectare||' + NVL(CG.RESTA,0) - NVL(CF.RESTA,0) + NVL(CC.RESTA,0) + NVL(CSERV.RESTA,0) - NVL(CSIN.RESTA,0) + NVL(CSIES.RESTA,0) - NVL(CIIN.RESTA,0) + NVL(CIIES.RESTA,0),0) Necesar,';
        end if;
        sInsert := sInsert||'
          NVL(SR.CANT,0) STOCREAL,
          NAO.CODEXTERN, NAO.CODINTERN, PROD.DEN_PART'||sColMinMax||',
          NVL(CF.CANTC,0), NVL(CF.CANTA,0), NVL(CF.RESTA,0),
          NVL(CC.CANTC,0), NVL(CC.CANTA,0), NVL(CC.RESTA,0),
          NVL(CSERV.CANTC,0), NVL(CSERV.CANTA,0), NVL(CSERV.RESTA,0),
          NVL(CSIN.CANTC,0), NVL(CSIN.CANTA,0), NVL(CSIN.RESTA,0),
          NVL(CSIES.CANTC,0), NVL(CSIES.CANTA,0), NVL(CSIES.RESTA,0),
          NVL(CG.CANTC,0), NVL(CG.CANTA,0), NVL(CG.RESTA,0),
          NVL(CIIN.CANTC,0), NVL(CIIN.CANTA,0), NVL(CIIN.RESTA,0),
          NVL(CIIES.CANTC,0), NVL(CIIES.CANTA,0), NVL(CIIES.RESTA,0),
          SREZ.REZERVAT, UF.DEN_PART, NVL(UNS.PRET,0) - Nvl(UNS.ADAOS,0), CF.AuxField,'||vNrZilePer||','||current_setting('PKG_LIST_BASE_NAPROVIZ2.vNrZile', true)||',TMP.D1, TMP.D2, TMP.D3, IPP.CANT'||gUserAlias||'
        FROM (SELECT CODOBIECT, D1, D2, D3 FROM TMP_CMD_TMP WHERE TIP = ''OBJ'') TMP
          INNER JOIN NARTOBJ NAO ON NAO.CODOBIECT = TMP.CODOBIECT
          INNER JOIN NART NA ON NA.CODARTICOL = NAO.CODARTICOL
          INNER JOIN NUM ON NUM.CODUM = NA.UM
          LEFT JOIN ('||sUltNirstoc||') X ON X.CODOBIECT = NAO.CODOBIECT
          LEFT JOIN NIRSTOC UNS ON UNS.CODNIRSTOC = X.CODNIRSTOC
          LEFt JOIN NPART UF ON UF.CODPART = UNS.FURN
          LEFT JOIN NIR UNIR ON UNIR.CODNIR = UNS.CODNIR
          LEFT JOIN INTRARI UINTR ON UINTR.CODINTR = UNIR.CODINTR AND UINTR.TIPDOC = 6
          LEFT JOIN NSUBUNIT USUB ON USUB.CODSUBUNIT = UINTR.CODSUBUNIT
          LEFT JOIN NARTOBJSUBUNIT NAOS ON NAO.CODOBIECT = NAOS.CODOBIECT
                                        and (NAOS.codgest is null or NAOS.codgest = 0)
                                        AND NAOS.SUBUNITATE = '||GETSUBUNITATE()||'
          LEFT JOIN TMP_STOCREAL SR ON SR.CODOBIECT = NAO.CODOBIECT AND SR.TIP = ''REAL'' AND SR.D1 = TMP.D1 AND SR.D2 = TMP.D2 AND SR.D3 = TMP.D3
          LEFT JOIN TMP_STOCREZ SREZ ON SREZ.CODOBIECT = NAO.CODOBIECT AND SREZ.D1 = TMP.D1 AND SREZ.D2 = TMP.D2 AND SREZ.D3 = TMP.D3
          LEFT JOIN TMP_STOCREAL SI ON SI.CODOBIECT = NAO.CODOBIECT AND SI.TIP = ''INIT'' AND SI.D1 = TMP.D1 AND SI.D2 = TMP.D2 AND SI.D3 = TMP.D3
          LEFT JOIN TMP_CMD_TMP CF ON CF.CODOBIECT = NAO.CODOBIECT AND CF.TIP = ''CF'' AND CF.D1 = TMP.D1 AND CF.D2 = TMP.D2 AND CF.D3 = TMP.D3
          LEFT JOIN TMP_CMD_TMP CC ON CC.CODOBIECT = NAO.CODOBIECT AND CC.TIP = ''CC'' AND CC.D1 = TMP.D1 AND CC.D2 = TMP.D2 AND CC.D3 = TMP.D3
          LEFT JOIN TMP_CMD_TMP CSERV ON CSERV.CODOBIECT = NAO.CODOBIECT AND CSERV.TIP = ''CSERV'' AND CSERV.D1 = TMP.D1 AND CSERV.D2 = TMP.D2 AND CSERV.D3 = TMP.D3
          LEFT JOIN TMP_CMD_TMP CSIN ON CSIN.CODOBIECT = NAO.CODOBIECT AND CSIN.TIP = ''CSIN'' AND CSIN.D1 = TMP.D1 AND CSIN.D2 = TMP.D2 AND CSIN.D3 = TMP.D3
          LEFT JOIN TMP_CMD_TMP CSIES ON CSIES.CODOBIECT = NAO.CODOBIECT AND CSIES.TIP = ''CSIES'' AND CSIES.D1 = TMP.D1 AND CSIES.D2 = TMP.D2 AND CSIES.D3 = TMP.D3
          LEFT JOIN TMP_CMD_TMP CG ON CG.CODOBIECT = NAO.CODOBIECT AND CG.TIP = ''CG'' AND CG.D1 = TMP.D1 AND CG.D2 = TMP.D2 AND CG.D3 = TMP.D3
          LEFT JOIN TMP_CMD_TMP CIIN ON CIIN.CODOBIECT = NAO.CODOBIECT AND CIIN.TIP = ''CIIN'' AND CIIN.D1 = TMP.D1 AND CIIN.D2 = TMP.D2 AND CIIN.D3 = TMP.D3
          LEFT JOIN TMP_CMD_TMP CIIES ON CIIES.CODOBIECT = NAO.CODOBIECT AND CIIES.TIP = ''CIIES'' AND CIIES.D1 = TMP.D1 AND CIIES.D2 = TMP.D2 AND CIIES.D3 = TMP.D3
          LEFT JOIN NPART PROD ON PROD.CODPART = NAO.CODPRODUCATOR
          LEFT JOIN (select codobiect, sum(cant) cant, tip, D1, D2, D3 from TMP_STOCREAL where tip = ''IES'' group by codobiect, tip, D1, D2, D3) IP ON IP.CODOBIECT = NAO.CODOBIECT AND IP.TIP = ''IES''
                    AND IP.D1 = TMP.D1 AND IP.D2 = TMP.D2 AND IP.D3 = TMP.D3
          LEFT JOIN (select codobiect, sum(cant) cant, tip, D1, D2, D3 from TMP_STOCREAL where tip = ''IESPREC'' group by codobiect, tip, D1, D2, D3) IPP ON IPP.CODOBIECT = NAO.CODOBIECT AND IPP.TIP = ''IESPREC''
                    AND IPP.D1 = TMP.D1 AND IPP.D2 = TMP.D2 AND IPP.D3 = TMP.D3
          LEFT JOIN NCLASEA CLSA ON CLSA.CODCLASEA = NA.CLASA
          LEFT JOIN NCLASEAS CLSAS ON CLSAS.CODCLASEAS = NA.CLASASTATIST'||
          gSuplJoins||'
        WHERE NA.TIPARTICOL = ''0'' and coalesce(NAO.Blocat,0) in (0,3) ';
      else
        sInsert:=
        'INSERT INTO '||tmpName||'(
          CodObiect,Articol, UM, TotVanz, MedieVanz, MedieVanzZ,
          Necesar,
          StocReal,
          CodExtern, CodIntern, Producator, StocMIN, StocMED, StocMAX,
          CantC_CF, CantA_CF, RestA_CF,
          CantC_CC, CantA_CC, RestA_CC,
          CantC_CSERV, CantA_CSERV, RestA_CSERV,
          CantC_CSIn, CantA_CSIn, RestA_CSIn,
          CantC_CSIes, CantA_CSIes, RestA_CSIes,
          CantC_CG, CantA_CG, RestA_CG,
          CantC_CIIn, CantA_CIIn, RestA_CIIn,
          CantC_CIIes, CantA_CIIes, RestA_CIIes,
          Rezervat, UltFurn, UltPrAchiz, NrComFurn, NrZile, NrZileNec, VanzPrec'||gUserFields||')
        SELECT
          NAO.CODOBIECT, NAO.DENUMIRE, NUM.DEN_UM, COALESCE(IP.CANT,0) TOTVANZ, CEIL(COALESCE(IP.CANT,0) / '||vNrLuni||') MEDIEVANZ,
          COALESCE(IP.CANT,0) / '||vNrZilePer||' MEDIEVANZZ,
          --GREATEST(CEIL(COALESCE(IP.CANT,0) / '||vNrLuni||') - NVL(SR.Cant, 0) - NVL(SI.Cant, 0) - NVL(CG.RESTA,0) + NVL(CF.RESTA,0) - NVL(CC.RESTA,0) - NVL(CSERV.RESTA,0) + NVL(CSIN.RESTA,0) - NVL(CSIES.RESTA,0) + NVL(CIIN.RESTA,0) - NVL(CIIES.RESTA,0),0) Necesar,';
        if current_setting('PKG_LIST_BASE_NAPROVIZ2.vPeZile', true)::boolean then
          sInsert := sInsert||'
            GREATEST(CEIL(COALESCE(IP.CANT,0) / '||vNrZilePer||' * '||current_setting('PKG_LIST_BASE_NAPROVIZ2.vNrZile', true)||') - NVL(SR.Cant, 0)'||sAfectare||' + NVL(CG.RESTA,0) - NVL(CF.RESTA,0) + NVL(CC.RESTA,0) + NVL(CSERV.RESTA,0) - NVL(CSIN.RESTA,0) + NVL(CSIES.RESTA,0) - NVL(CIIN.RESTA,0) + NVL(CIIES.RESTA,0),0) Necesar, '||chr(13);
        else
          sInsert := sInsert||'
            GREATEST(CEIL(COALESCE(IP.CANT,0) / '||vNrLuni||') - NVL(SR.Cant, 0)'||sAfectare||' + NVL(CG.RESTA,0) - NVL(CF.RESTA,0) + NVL(CC.RESTA,0) + NVL(CSERV.RESTA,0) - NVL(CSIN.RESTA,0) + NVL(CSIES.RESTA,0) - NVL(CIIN.RESTA,0) + NVL(CIIES.RESTA,0),0) Necesar,';
        end if;
        sInsert := sInsert||'
          NVL(SR.CANT,0) STOCREAL,
          NAO.CODEXTERN, NAO.CODINTERN, PROD.DEN_PART'||sColMinMax||',
          NVL(CF.CANTC,0), NVL(CF.CANTA,0), NVL(CF.RESTA,0),
          NVL(CC.CANTC,0), NVL(CC.CANTA,0), NVL(CC.RESTA,0),
          NVL(CSERV.CANTC,0), NVL(CSERV.CANTA,0), NVL(CSERV.RESTA,0),
          NVL(CSIN.CANTC,0), NVL(CSIN.CANTA,0), NVL(CSIN.RESTA,0),
          NVL(CSIES.CANTC,0), NVL(CSIES.CANTA,0), NVL(CSIES.RESTA,0),
          NVL(CG.CANTC,0), NVL(CG.CANTA,0), NVL(CG.RESTA,0),
          NVL(CIIN.CANTC,0), NVL(CIIN.CANTA,0), NVL(CIIN.RESTA,0),
          NVL(CIIES.CANTC,0), NVL(CIIES.CANTA,0), NVL(CIIES.RESTA,0),
          SREZ.REZERVAT, UF.DEN_PART, NVL(UNS.PRET,0) - Nvl(UNS.ADAOS,0), CF.AuxField,'||vNrZilePer||','||current_setting('PKG_LIST_BASE_NAPROVIZ2.vNrZile', true)||', IPP.CANT'||gUserAlias||'
        FROM NARTOBJ NAO
          INNER JOIN NART NA ON NA.CODARTICOL = NAO.CODARTICOL
          INNER JOIN NUM ON NUM.CODUM = NA.UM
          LEFT JOIN ('||sUltNirstoc||') X ON X.CODOBIECT = NAO.CODOBIECT
          LEFT JOIN NIRSTOC UNS ON UNS.CODNIRSTOC = X.CODNIRSTOC
          LEFt JOIN NPART UF ON UF.CODPART = UNS.FURN
          LEFT JOIN NIR UNIR ON UNIR.CODNIR = UNS.CODNIR
          LEFT JOIN INTRARI UINTR ON UINTR.CODINTR = UNIR.CODINTR AND UINTR.TIPDOC = 6
          LEFT JOIN NSUBUNIT USUB ON USUB.CODSUBUNIT = UINTR.CODSUBUNIT
          LEFT JOIN NARTOBJSUBUNIT NAOS ON NAO.CODOBIECT = NAOS.CODOBIECT
                                        and (NAOS.codgest is null or NAOS.codgest = 0)
                                        AND NAOS.SUBUNITATE = '||GETSUBUNITATE()||'
          LEFT JOIN TMP_STOCREAL SR ON SR.CODOBIECT = NAO.CODOBIECT AND SR.TIP = ''REAL''
          LEFT JOIN TMP_STOCREZ SREZ ON SREZ.CODOBIECT = NAO.CODOBIECT
          LEFT JOIN TMP_STOCREAL SI ON SI.CODOBIECT = NAO.CODOBIECT AND SI.TIP = ''INIT''
          LEFT JOIN TMP_CMD_TMP CF ON CF.CODOBIECT = NAO.CODOBIECT AND CF.TIP = ''CF''
          LEFT JOIN TMP_CMD_TMP CC ON CC.CODOBIECT = NAO.CODOBIECT AND CC.TIP = ''CC''
          LEFT JOIN TMP_CMD_TMP CSERV ON CSERV.CODOBIECT = NAO.CODOBIECT AND CSERV.TIP = ''CSERV''
          LEFT JOIN TMP_CMD_TMP CSIN ON CSIN.CODOBIECT = NAO.CODOBIECT AND CSIN.TIP = ''CSIN''
          LEFT JOIN TMP_CMD_TMP CSIES ON CSIES.CODOBIECT = NAO.CODOBIECT AND CSIES.TIP = ''CSIES''
          LEFT JOIN TMP_CMD_TMP CG ON CG.CODOBIECT = NAO.CODOBIECT AND CG.TIP = ''CG''
          LEFT JOIN TMP_CMD_TMP CIIN ON CIIN.CODOBIECT = NAO.CODOBIECT AND CIIN.TIP = ''CIIN''
          LEFT JOIN TMP_CMD_TMP CIIES ON CIIES.CODOBIECT = NAO.CODOBIECT AND CIIES.TIP = ''CIIES''
          LEFT JOIN NPART PROD ON PROD.CODPART = NAO.CODPRODUCATOR
          LEFT JOIN (select codobiect, sum(cant) cant, tip from TMP_STOCREAL where tip = ''IES'' group by codobiect, tip) IP ON IP.CODOBIECT = NAO.CODOBIECT AND IP.TIP = ''IES''
          LEFT JOIN (select codobiect, sum(cant) cant, tip from TMP_STOCREAL where tip = ''IESPREC'' group by codobiect, tip) IPP ON IPP.CODOBIECT = NAO.CODOBIECT AND IPP.TIP = ''IESPREC''
          LEFT JOIN NCLASEA CLSA ON CLSA.CODCLASEA = NA.CLASA
          LEFT JOIN NCLASEAS CLSAS ON CLSAS.CODCLASEAS = NA.CLASASTATIST'||
          gSuplJoins||'
        WHERE NA.TIPARTICOL = ''0'' and coalesce(NAO.Blocat,0) in (0,3) ';
      end if;
      if current_setting('pkg_list_base_naproviz2.vProd', TRUE)::NUMERIC &gt; 0 then
        sInsert := sInsert||' and NAO.CodProducator = '|| current_setting('pkg_list_base_naproviz2.vProd', TRUE);
      end if;
      if NOT current_setting('pkg_list_base_naproviz2.vAllCls', TRUE)::boolean then
          sInsert := sInsert||' and exists (select tmp.valoare from tmp_manevra_liste tmp, nclasea clsx
                                            where tmp.filtru = ''CODCLASEA'' and tmp.valoare = clsx.codclasea::varchar
                                                  and INSTRB(CLSA.CODIDENT, clsx.codident) = 1) ';
     END IF;
     PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
    end if;
  else
    delete FROM tmp_lst_napr2;
    sAfectare := '';
    --if pkg_list_base_naproviz2.GETPEZILE = 1 then
      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vAfectare', true)::NUMERIC = 1 then
        sAfectare := ' NVL(NAOS.STOCMIN,0) ';
      end if;
      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vAfectare', true)::NUMERIC = 2 then
        sAfectare := ' NVL(NAOS.STOCMED,0) ';
      end if;
      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vAfectare', true)::NUMERIC = 3 then
        sAfectare := ' NVL(NAOS.STOCMAX,0) ';
      end if;
    --end if;
    sInsert:=
    'INSERT INTO '||tmpName||'(
      codobiect, codum1, Articol, UM, TotVanz, MedieVanz, MedieVanzZ,
      Necesar,
      StocReal,
      CodExtern, CodIntern, Producator, StocMIN, StocMED, StocMAX,
      CantC_CF, CantA_CF, RestA_CF,
      CantC_CC, CantA_CC, RestA_CC,
      CantC_CSERV, CantA_CSERV, RestA_CSERV,
      CantC_CSIn, CantA_CSIn, RestA_CSIn,
      CantC_CSIes, CantA_CSIes, RestA_CSIes,
      CantC_CG, CantA_CG, RestA_CG,
      CantC_CIIn, CantA_CIIn, RestA_CIIn,
      CantC_CIIes, CantA_CIIes, RestA_CIIes,
      Rezervat, UltFurn, UltPrAchiz, CodUltFurn, IesNed '||gUserFields||')
    SELECT
      nao.codobiect, num1.codum1,NAO.DENUMIRE, NUM.DEN_UM, COALESCE(IP.CANT,0)+NVL(EMUL.CANT,0) TOTVANZ, CEIL((COALESCE(IP.CANT,0)+NVL(EMUL.CANT,0)) / '||vNrLuni||') MEDIEVANZ,
      (COALESCE(IP.CANT,0)+NVL(EMUL.CANT,0)) / '||vNrZilePer||' MEDIEVANZZ,
      --GREATEST(CEIL(COALESCE(IP.CANT,0) / '||vNrLuni||') - NVL(SR.Cant, 0) - NVL(SI.Cant, 0) - NVL(CG.RESTA,0) + NVL(CF.RESTA,0) - NVL(CC.RESTA,0) - NVL(CSERV.RESTA,0) + NVL(CSIN.RESTA,0) - NVL(CSIES.RESTA,0) + NVL(CIIN.RESTA,0) - NVL(CIIES.RESTA,0),0) Necesar,';
    if current_setting('PKG_LIST_BASE_NAPROVIZ2.vAfectare', true)::NUMERIC = 3 then
      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vPeZile', true)::boolean then
        sInsert := sInsert||'
          case when GREATEST(CEIL((COALESCE(IP.CANT,0)+NVL(EMUL.CANT,0)) / '||vNrZilePer||' * '||current_setting('PKG_LIST_BASE_NAPROVIZ2.vNrZile', true)||') - (NVL(SR.Cant, 0)-NVL(EMUL.CANT,0)) + NVL(IESNED.RESTA,0) + NVL(CG.RESTA,0) - NVL(CF.RESTA,0) + NVL(CC.RESTA,0) + NVL(CSERV.RESTA,0) - NVL(CSIN.RESTA,0) + NVL(CSIES.RESTA,0) - NVL(CIIN.RESTA,0) + NVL(CIIES.RESTA,0),0) &gt; '||sAfectare||' then '||sAfectare||'
               else GREATEST(CEIL((COALESCE(IP.CANT,0)+NVL(EMUL.CANT,0)) / '||vNrZilePer||' * '||current_setting('PKG_LIST_BASE_NAPROVIZ2.vNrZile', true)||') - (NVL(SR.Cant, 0)-NVL(EMUL.CANT,0)) + NVL(IESNED.RESTA,0) + NVL(CG.RESTA,0) - NVL(CF.RESTA,0) + NVL(CC.RESTA,0) + NVL(CSERV.RESTA,0) - NVL(CSIN.RESTA,0) + NVL(CSIES.RESTA,0) - NVL(CIIN.RESTA,0) + NVL(CIIES.RESTA,0),0)
          end Necesar, '||chr(13);
      else
        sInsert := sInsert||'
          case when GREATEST(CEIL((COALESCE(IP.CANT,0)+NVL(EMUL.CANT,0)) / '||vNrLuni||') - (NVL(SR.Cant, 0)-NVL(EMUL.CANT,0)) + NVL(IESNED.RESTA,0) + NVL(CG.RESTA,0) - NVL(CF.RESTA,0) + NVL(CC.RESTA,0) + NVL(CSERV.RESTA,0) - NVL(CSIN.RESTA,0) + NVL(CSIES.RESTA,0) - NVL(CIIN.RESTA,0) + NVL(CIIES.RESTA,0),0) &gt; '||sAfectare||' then '||sAfectare||'
               else GREATEST(CEIL((COALESCE(IP.CANT,0)+NVL(EMUL.CANT,0)) / '||vNrLuni||') - (NVL(SR.Cant, 0)-NVL(EMUL.CANT,0)) + NVL(IESNED.RESTA,0) + NVL(CG.RESTA,0) - NVL(CF.RESTA,0) + NVL(CC.RESTA,0) + NVL(CSERV.RESTA,0) - NVL(CSIN.RESTA,0) + NVL(CSIES.RESTA,0) - NVL(CIIN.RESTA,0) + NVL(CIIES.RESTA,0),0)
          end Necesar,';
      end if;
    else
      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vPeZile', true)::boolean then
        sInsert := sInsert||'
          GREATEST(CEIL((COALESCE(IP.CANT,0)+NVL(EMUL.CANT,0)) / '||vNrZilePer||' * '||current_setting('PKG_LIST_BASE_NAPROVIZ2.vNrZile', true)||') - (NVL(SR.Cant, 0)-NVL(EMUL.CANT,0)) + '||sAfectare||' + NVL(IESNED.RESTA,0) + NVL(CG.RESTA,0) - NVL(CF.RESTA,0) + NVL(CC.RESTA,0) + NVL(CSERV.RESTA,0) - NVL(CSIN.RESTA,0) + NVL(CSIES.RESTA,0) - NVL(CIIN.RESTA,0) + NVL(CIIES.RESTA,0),0) Necesar, '||chr(13);
      else
        sInsert := sInsert||'
          GREATEST(CEIL((COALESCE(IP.CANT,0)+NVL(EMUL.CANT,0)) / '||vNrLuni||') - (NVL(SR.Cant, 0)-NVL(EMUL.CANT,0)) + '||sAfectare||' + NVL(IESNED.RESTA,0) + NVL(CG.RESTA,0) - NVL(CF.RESTA,0) + NVL(CC.RESTA,0) + NVL(CSERV.RESTA,0) - NVL(CSIN.RESTA,0) + NVL(CSIES.RESTA,0) - NVL(CIIN.RESTA,0) + NVL(CIIES.RESTA,0),0) Necesar,';
      end if;
    end if;
    sInsert := sInsert||'
      NVL(SR.CANT,0)- NVL(EMUL.CANT,0),
      NAO.CODEXTERN, NAO.CODINTERN, PROD.DEN_PART'||sColMinMax||',
      NVL(CF.CANTC,0), NVL(CF.CANTA,0), NVL(CF.RESTA,0),
      NVL(CC.CANTC,0), NVL(CC.CANTA,0), NVL(CC.RESTA,0),
      NVL(CSERV.CANTC,0), NVL(CSERV.CANTA,0), NVL(CSERV.RESTA,0),
      NVL(CSIN.CANTC,0), NVL(CSIN.CANTA,0), NVL(CSIN.RESTA,0),
      NVL(CSIES.CANTC,0), NVL(CSIES.CANTA,0), NVL(CSIES.RESTA,0),
      NVL(CG.CANTC,0), NVL(CG.CANTA,0), NVL(CG.RESTA,0),
      NVL(CIIN.CANTC,0), NVL(CIIN.CANTA,0), NVL(CIIN.RESTA,0),
      NVL(CIIES.CANTC,0), NVL(CIIES.CANTA,0), NVL(CIIES.RESTA,0),
      SREZ.REZERVAT, UF.DEN_PART, NVL(UNS.PRET,0) - Nvl(UNS.ADAOS,0), nvl(UF.CODPART,0) CodUltFurn, IESNED.RESTA'||gUserAlias||'
    FROM NARTOBJ NAO
      INNER JOIN NART NA ON NA.CODARTICOL = NAO.CODARTICOL
      INNER JOIN NUM ON NUM.CODUM = NA.UM
      LEFT JOIN NUM1 ON NUM.CODUM = NUM1.CODUM AND NVL(NUM1.SECUNDARA,0) = 0
      LEFT JOIN ('||sUltNirstoc||') X ON X.CODOBIECT = NAO.CODOBIECT
      LEFT JOIN NIRSTOC UNS ON UNS.CODNIRSTOC = X.CODNIRSTOC
      LEFt JOIN NPART UF ON UF.CODPART = UNS.FURN
      LEFT JOIN NIR UNIR ON UNIR.CODNIR = UNS.CODNIR
      LEFT JOIN INTRARI UINTR ON UINTR.CODINTR = UNIR.CODINTR AND UINTR.TIPDOC = 6
      LEFT JOIN NSUBUNIT USUB ON USUB.CODSUBUNIT = UINTR.CODSUBUNIT '||chr(13)||
                  sJoinSub||chr(13)||'
      LEFT JOIN TMP_STOCREAL SR ON SR.CODOBIECT = NAO.CODOBIECT AND SR.TIP = ''REAL''
      LEFT JOIN TMP_STOCREZ SREZ ON SREZ.CODOBIECT = NAO.CODOBIECT
      LEFT JOIN TMP_STOCREAL SI ON SI.CODOBIECT = NAO.CODOBIECT AND SI.TIP = ''INIT''
      LEFT JOIN TMP_CMD_TMP CF ON CF.CODOBIECT = NAO.CODOBIECT AND CF.TIP = ''CF''
      LEFT JOIN TMP_CMD_TMP CC ON CC.CODOBIECT = NAO.CODOBIECT AND CC.TIP = ''CC''
      LEFT JOIN TMP_CMD_TMP CSERV ON CSERV.CODOBIECT = NAO.CODOBIECT AND CSERV.TIP = ''CSERV''
      LEFT JOIN TMP_CMD_TMP CSIN ON CSIN.CODOBIECT = NAO.CODOBIECT AND CSIN.TIP = ''CSIN''
      LEFT JOIN TMP_CMD_TMP CSIES ON CSIES.CODOBIECT = NAO.CODOBIECT AND CSIES.TIP = ''CSIES''
      LEFT JOIN TMP_CMD_TMP CG ON CG.CODOBIECT = NAO.CODOBIECT AND CG.TIP = ''CG''
      LEFT JOIN TMP_CMD_TMP CIIN ON CIIN.CODOBIECT = NAO.CODOBIECT AND CIIN.TIP = ''CIIN''
      LEFT JOIN TMP_CMD_TMP CIIES ON CIIES.CODOBIECT = NAO.CODOBIECT AND CIIES.TIP = ''CIIES''
      LEFT JOIN TMP_CMD_TMP IESNED ON IESNED.CODOBIECT = NAO.CODOBIECT AND IESNED.TIP = ''IESNED''
      LEFT JOIN NPART PROD ON PROD.CODPART = NAO.CODPRODUCATOR
      LEFT JOIN (select codobiect, sum(cant) cant from TMP_STOCREAL where tip = ''IES'' group by codobiect) IP ON IP.CODOBIECT = NAO.CODOBIECT
      LEFT JOIN (select codobiect, sum(cant) cant from TMP_STOCREAL where tip = ''EMUL'' group by codobiect) EMUL ON EMUL.CODOBIECT = NAO.CODOBIECT
      LEFT JOIN NCLASEA CLSA ON CLSA.CODCLASEA = NA.CLASA
      LEFT JOIN NCLASEAS CLSAS ON CLSAS.CODCLASEAS = NA.CLASASTATIST
      LEFT JOIN NCLASEAS CLSW ON CLSW.CODCLASEAS = NA.CLASAW '||
      gSuplJoins||'
    WHERE NA.TIPARTICOL = ''0'' and coalesce(NAO.Blocat,0) in (0,3)';
    if current_setting('pkg_list_base_naproviz2.vClasa', TRUE)::NUMERIC &gt; 0 then
      begin
        select codident into vCodIdent
        from nclasea
        where codclasea = current_setting('pkg_list_base_naproviz2.vClasa', TRUE)::NUMERIC;
      exception when others then PERFORM set_config('pkg_list_base_naproviz2.vClasa', '0', FALSE);
      end;
      if current_setting('pkg_list_base_naproviz2.vClasa', TRUE)::NUMERIC &gt; 0 then
        sInsert := sInsert||' and INSTRB(CLSA.CODIDENT, '''||vCodIdent||''') = 1 ';
      end if;
    end if;
    if current_setting('pkg_list_base_naproviz2.vClasaS', TRUE)::NUMERIC &gt; 0 then
      begin
        select codident into vCodIdent
        from nclaseas
        where codclaseas = current_setting('pkg_list_base_naproviz2.vClasaS', TRUE)::NUMERIC;
      exception when others then PERFORM set_config('pkg_list_base_naproviz2.vClasaS', '0', FALSE);
      end;
      if current_setting('pkg_list_base_naproviz2.vClasaS', TRUE)::NUMERIC &gt; 0 then
        sInsert := sInsert||' and INSTRB(CLSAS.CODIDENT, '''||vCodIdent||''') = 1 ';
      end if;
    end if;
    if current_setting('pkg_list_base_naproviz2.vClasaW', TRUE)::NUMERIC &gt; 0 then
      begin
        select codident into vCodIdent
        from nclaseaS
        where codclaseas = current_setting('pkg_list_base_naproviz2.vClasaW', TRUE)::NUMERIC;
      exception when others then PERFORM set_config('pkg_list_base_naproviz2.vClasaW', '0', FALSE);
      end;
      if current_setting('pkg_list_base_naproviz2.vClasaW', TRUE)::NUMERIC &gt; 0 then
        sInsert := sInsert||' and INSTRB(CLSW.CODIDENT, '''||vCodIdent||''') = 1 ';
      end if;
    end if;
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  end if;

  if tmpName = 'TMP_LST_NAPR2' and coalesce(current_setting('pkg_list_base_naproviz2.vCuArtFaraVanz', TRUE)::NUMERIC,0) &lt;&gt; 1 then
    execute 'delete from TMP_LST_NAPR2 where coalesce(totvanz,0) = 0';
  end if;

  --DELETE TMP_CMD WHERE USERID = VUSERID;
  if current_setting('PKG_LIST_BASE_NAPROVIZ2.vZileStoc', true)::NUMERIC &gt; 0 then
    PERFORM pkg_list_base_naproviz2_CalculeazaZileStoc(tmpName);
  end if;

  select
    (extract(year from vZiuaFin)*12+extract(month from vZiuaFin)) - (extract(year from vZiuaIni)*12+extract(month from vZiuaIni)) + 1
  into Luni;

  if current_setting('PKG_LIST_BASE_NAPROVIZ2.vPeLuni', true)::boolean and tmpName &lt;&gt; 'TMP_LST_NAPR2' then
    execute 'update '||tmpName||' set luni = '||Luni;
    if (extract(year from vZiuaIni)*12+extract(month from vZiuaIni))/12 = trunc((extract(year from vZiuaIni)*12+extract(month from vZiuaIni))/12) then
      vLunaV := 12;
      vAnV   := (extract(year from vZiuaIni)*12+extract(month from vZiuaIni))/12 - 1;
    else
      vLunaV := (extract(year from vZiuaIni)*12+extract(month from vZiuaIni)) - trunc((extract(year from vZiuaIni)*12+extract(month from vZiuaIni))/12)*12;
      vAnV   := trunc((extract(year from vZiuaIni)*12+extract(month from vZiuaIni))/12);
    end if;
    Luni := 0;
    Loop
      Luni := Luni + 1;
      if Luni &gt; 12 then Exit; end if;
      if current_setting('PKG_LIST_BASE_NAPROVIZ2.vDim', true)::boolean then
        if vLunaV =  1 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Ian = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Ian'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3 and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Ian = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Ian'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3),0)';
          end if;

        end if;
        if vLunaV =  2 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Feb = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Feb'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3 and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Feb = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Feb'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3),0)';
          end if;

        end if;
        if vLunaV =  3 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Mar = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Mar'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3 and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Mar = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Mar'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3),0)';
          end if;

        end if;
        if vLunaV =  4 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Apr = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Apr'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3 and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Apr = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Apr'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3),0)';
          end if;

        end if;
        if vLunaV =  5 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Mai = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Mai'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3 and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Mai = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Mai'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3),0)';
          end if;

        end if;
        if vLunaV =  6 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Jun = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Jun'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3 and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Jun = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Jun'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3),0)';
          end if;

        end if;
        if vLunaV =  7 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Jul = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Jul'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3 and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Jul = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Jul'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3),0)';
          end if;

        end if;
        if vLunaV =  8 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Aug = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Aug'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3 and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Aug = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Aug'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3),0)';
          end if;

        end if;
        if vLunaV =  9 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Sep = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Sep'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3 and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Sep = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Sep'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3),0)';
          end if;

        end if;
        if vLunaV = 10 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Oct = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Oct'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3 and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Oct = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Oct'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3),0)';
          end if;

        end if;
        if vLunaV = 11 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Nov = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Nov'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3 and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Nov = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Nov'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3),0)';
          end if;

        end if;
        if vLunaV = 12 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Dec = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Dec'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3 and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Dec = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Dec'' and tmp.codobiect = t.codobiect and t.d1 = tmp.d1 and t.d2 = tmp.d2 and t.d3 = tmp.d3),0)';
          end if;

        end if;
      else
        if vLunaV =  1 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Ian = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Ian'' and tmp.codobiect = t.codobiect and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Ian = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Ian'' and tmp.codobiect = t.codobiect),0)';
          end if;

        end if;
        if vLunaV =  2 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Feb = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Feb'' and tmp.codobiect = t.codobiect and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Feb = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Feb'' and tmp.codobiect = t.codobiect),0)';
          end if;

        end if;
        if vLunaV =  3 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Mar = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Mar'' and tmp.codobiect = t.codobiect and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Mar = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Mar'' and tmp.codobiect = t.codobiect),0)';
          end if;

        end if;
        if vLunaV =  4 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Apr = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Apr'' and tmp.codobiect = t.codobiect and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Apr = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Apr'' and tmp.codobiect = t.codobiect),0)';
          end if;

        end if;
        if vLunaV =  5 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Mai = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Mai'' and tmp.codobiect = t.codobiect and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Mai = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Mai'' and tmp.codobiect = t.codobiect),0)';
          end if;

        end if;
        if vLunaV =  6 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Jun = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Jun'' and tmp.codobiect = t.codobiect and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Jun = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Jun'' and tmp.codobiect = t.codobiect),0)';
          end if;

        end if;
        if vLunaV =  7 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Jul = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Jul'' and tmp.codobiect = t.codobiect and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Jul = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Jul'' and tmp.codobiect = t.codobiect),0)';
          end if;

        end if;
        if vLunaV =  8 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Aug = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Aug'' and tmp.codobiect = t.codobiect and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Aug = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Aug'' and tmp.codobiect = t.codobiect),0)';
          end if;

        end if;
        if vLunaV =  9 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Sep = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Sep'' and tmp.codobiect = t.codobiect and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Sep = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Sep'' and tmp.codobiect = t.codobiect),0)';
          end if;

        end if;
        if vLunaV = 10 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Oct = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Oct'' and tmp.codobiect = t.codobiect and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Oct = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Oct'' and tmp.codobiect = t.codobiect),0)';
          end if;

        end if;
        if vLunaV = 11 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Nov = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Nov'' and tmp.codobiect = t.codobiect and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Nov = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Nov'' and tmp.codobiect = t.codobiect),0)';
          end if;

        end if;
        if vLunaV = 12 then
          if vDefalcare then
            execute 'update '||tmpName||' t set Dec = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Dec'' and tmp.codobiect = t.codobiect and tmp.codgest = t.codsubunit),0)';
          else
            execute 'update '||tmpName||' t set Dec = NVL((select sum(nvl(tmp.cant,0)) from tmp_stocreal tmp where tmp.tip = ''Dec'' and tmp.codobiect = t.codobiect),0)';
          end if;

        end if;
      end if;
      vLunaV := vLunaV + 1;
      if vLunaV = 13 then
        vLunaV := 1;
        vAnV   := vAnV + 1;
      end if;
    end loop;
  end if;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz7_processlist</obj_name>
  <obj_hashval>e7701389a51bf17b2dca826fa1f69d68</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz7_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert      VARCHAR(32000);
  sSelect      VARCHAR( 2000);
  sColMinMax   VARCHAR(  100):= ', NAOS.STOCMIN, NAOS.STOCMED, NAOS.STOCMAX';
  vAux         VARCHAR( 1000):= '';
  vSelStocReal VARCHAR( 3000);
  vSelStocInit VARCHAR( 3000);
  vSelIes_Per  VARCHAR( 3000);
  vSelTr_Per   VARCHAR( 3000);
  vSelIes_Emul VARCHAR( 3000);
  vAnPrec      NUMERIC(4);
  vLunaPrec    NUMERIC(2);
  vNrLuni      INTEGER        := extract(year from to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))*12+
                                 extract(month from to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy')) -
                                 extract(year from to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))*12-
                                 extract(month from to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy')) +1;
  vNrZilePer   INTEGER        := to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy') - to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy') + 1;
  vCateGest    INTEGER        := 0;
  vCateLGest   INTEGER        := 0;
  vCondSub_C   VARCHAR(  100);
  vCondSub_CS  VARCHAR(  100);
  vCondSub_G   VARCHAR(  100);
  sUltNirstoc  VARCHAR( 1000);
  sAfectare    VARCHAR(50):= '';
  pUsername        VARCHAR(100);
  pStocExternFirma VARCHAR(3000) := fnc_getvalconstantalucru('StocExternFirma') ;
  pStocExternCamp  VARCHAR( 100) := PKG_LIST_BASE_UTILS_Get_StocExternCamp();
  vFiltruTermen    VARCHAR(1000);
  sJoinRestCmd varchar(1000);
  vUserID NUMERIC(20);
  gSuplCols varchar := 'NARTOBJ NAO, NART NA, NARTOBJSUBUNIT NAOS, NUM NUM, NPART PROD, NCLASEA CLSA, NCLASEAS CLSAS';
  gUserFields       VARCHAR := '';
  gUserAlias        VARCHAR := '';
  gNullAlias        VARCHAR := '';
  gSuplJoins        VARCHAR := '';
BEGIN
  --Florin 14.05.2024 - fixat 61922
  --Florin 26.03.2024 - fixat 61458
  --Florin 22.03.2024 - sinc. Oracle
  --Florin 27.02.2024 - fixat 61085
  --Florin 21.02.2024 - fixat 61066
  --Florin 30.05.2023 - fixat 58457
  --Florin 24.05.2023
  if vNrLuni &lt;= 0 then vNrLuni := 1; end if;
  if vNrZilePer &lt;= 0 then vNrZilePer := 1; end if;
  vCondSub_C  := PKG_LIST_BASE_UTILS_COND_SUBUNIT('C');
  vCondSub_CS := PKG_LIST_BASE_UTILS_COND_SUBUNIT('C', 'SubunitSursa');
  vCondSub_G  := PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT');

  delete FROM tmp_stocreal;

  CALL pkg_list_struct_StartSuplCols();
  CALL pkg_list_struct_AddSuplTabs(gSuplCols, 'NARTOBJEXT',     'OEXT', 'OEXT.CODOBIECT = NAO.CODOBIECT');
  CALL pkg_list_struct_AddSuplTabs(gSuplCols, 'NARTOBJATR',     'OATR', 'OATR.CODOBIECT = NAO.CODOBIECT');
  CALL pkg_list_struct_AddSuplTabs(gSuplCols, 'TMP_STOCEXTERN', 'TSE',  'TSE.CODCOMUN = NAO.'||pStocExternCamp);
  CALL pkg_list_struct_GetSuplCols(aLISTID,alistver,gUserFields,gUserAlias,gNullAlias,gSuplJoins,gSuplCols);
  IF InStr(gSuplJoins, 'TMP_STOCEXTERN') &gt; 0 THEN
    SELECT USERNAME INTO pUSERNAME FROM user_users;
    PERFORM WINMADMIN.PKG_USERFIRME_POPULEAZA_STOCURI_EXTERNE(pUSERNAME,pStocExternFirma,pStocExternCamp);
  END IF;

  IF GETSUBUNITATE() = 1 THEN
    sColMinMax  := ', NAO.STOCMIN, NAO.STOCMED, NAO.STOCMAX';
  END IF;
  SELECT newan, newluna INTO vAnPrec, vLunaPrec FROM pkg_globals_Calculeaza_Luna_Precedenta((Extract(Year from to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))::NUMERIC),
    (Extract(Month from to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))::NUMERIC), vAnPrec, vLunaPrec);
  PERFORM pkg_globals_SetLunaTemp((Extract(Year from to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy')))::NUMERIC,
    (Extract(Month from to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy')))::NUMERIC);
  PERFORM pkg_globals_SetLunaPrecedenta(vAnPrec, vLunaPrec);
  PERFORM PKG_LIST_SELFISAMAG_setAllParams(null, null, current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 0, 0, 0);
  if current_setting('PKG_LIST_BASE_NAPROVIZ2.vDim', TRUE)::boolean THEN
    vSelStocInit := '
    SELECT NS.CODOBIECT, SUM(V.REST) CANT, ''INIT'', NS.D1, NS.D2, NS.D3
    FROM V_STOC_INI_NECESAR2 V
      INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = V.CODNIRSTOC
      INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
      INNER JOIN NGEST G ON G.CODGEST = N.GEST '||vCondSub_G||'
    WHERE V.REST &lt;&gt; 0';
    vSelStocReal := '
    SELECT NS.CODOBIECT, SUM(NS.REST) CANT, ''REAL'', NS.D1, NS.D2, NS.D3
    FROM NIRSTOC NS
      INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
      INNER JOIN NGEST G ON G.CODGEST = N.GEST '||vCondSub_G||'
    WHERE NS.REST &lt;&gt; 0';

    vSelIes_Per  := '
    SELECT NS.CODOBIECT, L1.CANT, ''IES'', NS.D1, NS.D2, NS.D3, I.CODIES, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC
    FROM LIVR L
      INNER JOIN LIVR1 l1 ON L1.CODLIVR = L.CODLIVR
      INNER JOIN IESIRI I ON L.CODIES = I.CODIES
      INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES AND L1.CODIES1 = I1.CODIES1
      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 '||vCondSub_G||'
    WHERE L.DATALIVR BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
      to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||'''
      AND NVL(I.ANULAT,0) = 0 AND I.OPERAT = 1 AND I.TIPDOC IN ('||current_setting('PKG_LIST_BASE_NAPROVIZ2.vTipVanz', TRUE)||')';
    vSelTr_Per := '';
    if Instr(current_setting('PKG_LIST_BASE_NAPROVIZ2.vTipVanz', TRUE),'12') &gt; 0 then
      vSelTr_Per  := '
        SELECT NS.CODOBIECT, L1.CANT, ''IES'', NS.D1, NS.D2, NS.D3, T.CODTRANSF, T.TIPDOC, T.PREFIXDOC, T.SERIADOC, T.NRDOC, T.DATADOC
        FROM LIVR L
          INNER JOIN LIVR1 l1 ON L1.CODLIVR = L.CODLIVR
          INNER JOIN TRANSF T ON T.CODTRANSF = L.CODTRANSF
          INNER JOIN TRANSF1 T1 ON T1.CODTRANSF = T.CODTRANSF AND L1.CODIES1 = T1.CODTRANSF1
          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 '||vCondSub_G||'
        WHERE L.DATALIVR BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
        to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||'''
          AND NVL(T.ANULAT,0) = 0 AND T.OPERAT = 1 AND T.TIPDOC = 12 ';
    end if;

    IF current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', TRUE)::boolean 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';
      vAux := '
      AND';
      IF    vCateLGest = 0 THEN vAux := vAux||' N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
      ELSIF vCateGest  = 0 THEN vAux := vAux||' NS.CODLOCATIE::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'') ';
      ELSE vAux := vAux||' (N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') OR NS.CODLOCATIE IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'')) ';
      END IF;
      vSelStocReal := vSelStocReal ||vAux;
      vSelStocInit := vSelStocInit ||vAux;
      vSelIes_Per := vSelIes_Per   ||vAux;
      if Length(vSelTr_Per) &gt; 0 then
        vSelTr_Per := vSelTr_Per   ||vAux;
      end if;
    END IF;
    IF current_setting('PKG_LIST_BASE_NAPROVIZ2.pToateIoart', TRUE)::boolean THEN
      vAux := '
      AND NS.CODIOART::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
      vSelStocReal := vSelStocReal ||vAux;
      vSelStocInit := vSelStocInit ||vAux;
      vSelIes_Per := vSelIes_Per   ||vAux;
      if Length(vSelTr_Per) &gt; 0 then
        vSelTr_Per := vSelTr_Per   ||vAux;
      end if;
    END IF;

    vSelStocReal := vSelStocReal ||'
    GROUP BY NS.CODOBIECT, NS.D1, NS.D2, NS.D3';
    vSelStocInit := vSelStocInit ||'
    GROUP BY NS.CODOBIECT, NS.D1, NS.D2, NS.D3';

    sJoinRestCmd := '';
    if current_setting('PKG_LIST_BASE_NAPROVIZ2.vRestCmd', TRUE)::boolean then
      sJoinRestCmd := ' INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = C1.GESTACT::varchar AND FILTRU = ''CODGEST'' ';
    end if;

    vFiltruTermen := '';
    if current_setting('PKG_LIST_BASE_NAPROVIZ2.vCuTermen', TRUE)::boolean then
      vFiltruTermen := ' AND C1.TERMEN &lt;= '''||current_setting('PKG_LIST_BASE_NAPROVIZ2.vTermen', TRUE)||''' ';
    end if;
    /************************ Sfarsit Constructie Selecturi Auxiliare ***************************/
    PERFORM PKG_GLOBALS_SetSeparator(',');
    DELETE FROM TMP_CMD_TMP;
    sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,auxfield,D1,D2,D3,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC)
    SELECT C1.CodObiect,
      case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
      to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantComandat else 0 end CantC,
      case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
      to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantAcceptat else 0 end CantA,
      C1.RestAcceptat RestA, ''CF'', to_char(C.nrdoc),C1.D1,C1.D2,C1.D3,C.CODCOMANDA,C.TIPDOC,C.PREFIXDOC,C.SERIADOC,C.NRDOC,C.DATADOC
    FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
    WHERE Nvl(C.INCHISA, 0) = 0
      AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 8 '||vCondSub_C||'
      AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||'''
      '||vFiltruTermen;
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
    sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,D1,D2,D3,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC)
    SELECT C1.CodObiect,
      case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
      to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantComandat else 0 end CantC,
      case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
      to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantAcceptat else 0 end CantA,
      C1.RestAcceptat RestA, ''CC'',C1.D1,C1.D2,C1.D3,C.CODCOMANDA,C.TIPDOC,C.PREFIXDOC,C.SERIADOC,C.NRDOC,C.DATADOC
    FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
    WHERE Nvl(C.INCHISA, 0) = 0
      AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 18 '||vCondSub_C||'
      AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' ';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
    sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,D1,D2,D3,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC)
    SELECT C1.CodObiect,
      case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
      to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantComandat else 0 end CantC,
      case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
      to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantAcceptat else 0 end CantA,
      C1.RestAcceptat RestA, ''CSERV'',C1.D1,C1.D2,C1.D3,C.CODCOMANDA,C.TIPDOC,C.PREFIXDOC,C.SERIADOC,C.NRDOC,C.DATADOC
    FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
    WHERE Nvl(C.INCHISA, 0) = 0
      AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 92 '||vCondSub_C||'
      AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' ';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
    sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,D1,D2,D3,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC)
    SELECT C1.CodObiect,
      case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
      to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantComandat else 0 end CantC,
      case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
      to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantAcceptat else 0 end CantA,
      C1.RestAcceptat RestA, ''CSIN'',C1.D1,C1.D2,C1.D3,C.CODCOMANDA,C.TIPDOC,C.PREFIXDOC,C.SERIADOC,C.NRDOC,C.DATADOC
    FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
    WHERE Nvl(C.INCHISA, 0) = 0
      AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 44 '||vCondSub_C||'
      AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' ';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
    sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,D1,D2,D3,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC)
    SELECT C1.CodObiect,
      case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
      to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantComandat else 0 end CantC,
      case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
      to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantAcceptat else 0 end CantA,
      C1.RestAcceptat RestA, ''CSIES'',C1.D1,C1.D2,C1.D3,C.CODCOMANDA,C.TIPDOC,C.PREFIXDOC,C.SERIADOC,C.NRDOC,C.DATADOC
    FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
    WHERE Nvl(C.INCHISA, 0) = 0
      AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 44 '||vCondSub_CS||'
      AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' ';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
    sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,D1,D2,D3,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC)
    SELECT C1.CodObiect,
      case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
      to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantComandat else 0 end CantC,
      case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
      to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantAcceptat else 0 end CantA,
      C1.RestAcceptat RestA, ''CG'',C1.D1,C1.D2,C1.D3,C.CODCOMANDA,C.TIPDOC,C.PREFIXDOC,C.SERIADOC,C.NRDOC,C.DATADOC
    FROM COMANDA1 C1
      INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
      INNER JOIN NGEST G ON C.CodGest = G.CodGest'||sJoinRestCmd||'
    WHERE Nvl(C.INCHISA, 0) = 0
      AND C.Operat = 1 AND C.Anulat = 0 AND G.Tip = 1 AND C.TipDoc = 43 '||vCondSub_C||'
      AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||'''';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
    sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,D1,D2,D3,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC)
    SELECT CMDMAT.CodObiect,
      case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
      to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then CMDMAT.Cant else 0 end CantC,
      case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
      to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then CMDMAT.Cant else 0 end CantA,
      CMDMAT.Rest RestA, ''CIIN'',CMDMAT.D1,CMDMAT.D2,CMDMAT.D3,C.CODCOMANDA,C.TIPDOC,C.PREFIXDOC,C.SERIADOC,C.NRDOC,C.DATADOC
    FROM CMDPRODMAT CMDMAT
      INNER JOIN COMANDA1 C1 ON CMDMAT.CodComanda1 = C1.CodComanda1
      INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
    WHERE Nvl(C.INCHISA, 0) = 0
      AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 53 '||vCondSub_C||'
      AND CMDMAT.Rest &gt; 0 AND C.DataDoc &lt;= '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||'''
      AND ((C1.Consum = 1 AND CMDMAT.Tip &lt;&gt; 1) OR (C1.Consum = 2 AND CMDMAT.Tip = 2))';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
    sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,D1,D2,D3,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC)
    SELECT CMDMAT.CodObiect,
      case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
      to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then CMDMAT.Cant else 0 end CantC,
      case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
      to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then CMDMAT.Cant else 0 end CantA,
      CMDMAT.Rest RestA, ''CIIES'',CMDMAT.D1,CMDMAT.D2,CMDMAT.D3,C.CODCOMANDA,C.TIPDOC,C.PREFIXDOC,C.SERIADOC,C.NRDOC,C.DATADOC
    FROM CMDPRODMAT CMDMAT
      INNER JOIN COMANDA1 C1 ON CMDMAT.CodComanda1 = C1.CodComanda1
      INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
    WHERE Nvl(C.INCHISA, 0) = 0
      AND C.Operat = 1 AND C.Anulat = 0 '||vCondSub_C||'
      AND CMDMAT.Rest &gt; 0 AND C.DataDoc &lt;= '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||'''
      AND ((C1.Consum = 1 AND CMDMAT.Tip = 1) OR (C1.Consum = 2 AND CMDMAT.Tip &lt;&gt; 2))';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
    DELETE FROM TMP_STOCREAL;
    PERFORM LIST_EXECUTE_IMMEDIATE('INSERT INTO tmp_stocreal(codobiect,cant,tip,D1,D2,D3) '||vSelStocReal, aListID, aListVer);
    PERFORM LIST_EXECUTE_IMMEDIATE('INSERT INTO tmp_stocreal(codobiect,cant,tip,D1,D2,D3) '||vSelStocInit, aListID, aListVer);
    PERFORM LIST_EXECUTE_IMMEDIATE('INSERT INTO tmp_cmd_tmp(codobiect,resta,tip,D1,D2,D3,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC) '||vSelIes_Per, aListID, aListVer);
    if Length(vSelTr_Per) &gt; 0 then
      PERFORM LIST_EXECUTE_IMMEDIATE('INSERT INTO tmp_cmd_tmp(codobiect,resta,tip,D1,D2,D3,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC) '||vSelTr_Per, aListID, aListVer);
    end if;
    DELETE FROM TMP_STOCREZ;
    sSelect := 'INSERT INTO tmp_stocrez(codobiect,rezervat,D1,D2,D3)
    SELECT NS.CODOBIECT, SUM(R.REST) REZERVAT,NS.D1,NS.D2,NS.D3
    FROM REZERVATS R
      INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = R.CODNIRSTOC
      INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
      INNER JOIN NGEST G ON G.CODGEST = N.GEST '||vCondSub_G||'
    WHERE NVL(R.REST,0) &gt; 0';

    if NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', TRUE)::boolean 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
        sSelect := sSelect || ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = N.GEST::varchar)';
      elsif vCateGest = 0 then
        sSelect := sSelect || ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND VALOARE = NS.CODLOCATIE::varchar)';
      else
        sSelect := sSelect || ' 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;
    if NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateIoart', TRUE)::boolean then
      sSelect := sSelect || ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND VALOARE = NS.CODIOART::varchar ) ';
    end if;
    sSelect := sSelect||' GROUP BY NS.CODOBIECT,NS.D1,NS.D2,NS.D3';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);

    IF current_setting('PKG_LIST_BASE_NAPROVIZ2.pUltAchiz', TRUE)::boolean
    THEN sUltNirstoc := 'SELECT 0 CODOBIECT, 0 CODNIRSTOC';--'SELECT CODOBIECT,D1,D2,D3,MAX(CODNIRSTOC) KEEP (DENSE_RANK LAST ORDER BY DATAACHIZ, CODNIRSTOC) CODNIRSTOC FROM NIRSTOC WHERE FURN &gt; 0 AND Nvl(CODNIRSTOCPARINTE,0) = 0 GROUP BY CODOBIECT,D1,D2,D3';
    ELSE sUltNirstoc := 'SELECT 0 CODOBIECT, 0 CODNIRSTOC';
    END IF;
  ELSE
    vSelStocInit := '
    SELECT NS.CODOBIECT, SUM(V.REST) CANT, ''INIT''
    FROM V_STOC_INI_NECESAR2 V
      INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = V.CODNIRSTOC
      INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
      INNER JOIN NGEST G ON G.CODGEST = N.GEST '||vCondSub_G||'
    WHERE V.REST &lt;&gt; 0';

    vSelStocReal := '
    SELECT NS.CODOBIECT, SUM(NS.REST) CANT, ''REAL''
    FROM NIRSTOC NS
      INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
      INNER JOIN NGEST G ON G.CODGEST = N.GEST '||vCondSub_G||'
    WHERE NS.REST &lt;&gt; 0';

    vSelIes_Per  := '
    SELECT NS.CODOBIECT, L1.CANT, ''IES'', I.CODIES, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC
    FROM LIVR L
      INNER JOIN LIVR1 l1 ON L1.CODLIVR = L.CODLIVR
      INNER JOIN IESIRI I ON L.CODIES = I.CODIES
      INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES AND L1.CODIES1 = I1.CODIES1
      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 '||vCondSub_G||'
    WHERE L.DATALIVR BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
    to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||'''
      AND NVL(I.ANULAT,0) = 0 AND I.OPERAT = 1 AND I.TIPDOC IN ('||current_setting('PKG_LIST_BASE_NAPROVIZ2.vTipVanz', TRUE)||')';

    if current_setting('PKG_LIST_BASE_NAPROVIZ2.vVanzEmul', TRUE)::boolean then
      vSelIes_Emul  := '
      SELECT E1.CODOBIECT, SUM(E1.CANT) CANT, ''EMUL'', E.CODEMULARE, 64 TIPDOC, '' PREFIXDOC, '' SERIADOC, E.NRBON NRDOC, E.DATABON DATADOC
      FROM EMULARE1 E1
        INNER JOIN EMULARE E ON E.CODEMULARE = E1.CODEMULARE
        INNER JOIN NGEST G ON G.CODGEST = E1.CODGEST '||vCondSub_G||'
      WHERE E.DATABON BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
      to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||'''
        AND NVL(E.PRELUAT, 0) = 0
        AND NVL(E.FACTURARE, 0) = 0';
    end if;
    vSelTr_Per := '';
    if Instr(current_setting('PKG_LIST_BASE_NAPROVIZ2.vTipVanz', TRUE),'12') &gt; 0 then
      vSelTr_Per  := '
        SELECT NS.CODOBIECT, L1.CANT, ''IES'', T.CODTRANSF, T.TIPDOC, T.PREFIXDOC, T.SERIADOC, T.NRDOC, T.DATADOC
        FROM LIVR L
          INNER JOIN LIVR1 l1 ON L1.CODLIVR = L.CODLIVR
          INNER JOIN TRANSF T ON T.CODTRANSF = L.CODTRANSF
          INNER JOIN TRANSF1 T1 ON T1.CODTRANSF = T.CODTRANSF AND L1.CODIES1 = T1.CODTRANSF1
          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 '||vCondSub_G||'
        WHERE L.DATALIVR BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
        to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||'''
          AND NVL(T.ANULAT,0) = 0 AND T.OPERAT = 1 AND T.TIPDOC = 12';
    end if;
    IF NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', TRUE)::boolean 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';
      vAux := '
      AND';
      IF    vCateLGest = 0 THEN vAux := vAux||' N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
      ELSIF vCateGest  = 0 THEN vAux := vAux||' NS.CODLOCATIE::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'') ';
      ELSE vAux := vAux||' (N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') OR NS.CODLOCATIE IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'')) ';
      END IF;
      vSelStocReal := vSelStocReal ||vAux;
      vSelStocInit := vSelStocInit ||vAux;
      vSelIes_Per := vSelIes_Per   ||vAux;
      if Length(vSelTr_Per) &gt; 0 then
        vSelTr_Per := vSelTr_Per   ||vAux;
      end if;
    END IF;

    IF NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateIoart', TRUE)::boolean THEN
      vAux := '
      AND NS.CODIOART::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
      vSelStocReal := vSelStocReal ||vAux;
      vSelStocInit := vSelStocInit ||vAux;
      vSelIes_Per := vSelIes_Per   ||vAux;
      if Length(vSelTr_Per) &gt; 0 then
        vSelTr_Per := vSelTr_Per   ||vAux;
      end if;
    END IF;

    vSelTr_Per := vSelTr_Per ||
       ' GROUP BY NS.CODOBIECT, T.CODTRANSF, T.TIPDOC, T.PREFIXDOC, T.SERIADOC, T.NRDOC, T.DATADOC, l1.cant';

    vSelStocReal := vSelStocReal ||'
    GROUP BY NS.CODOBIECT';
    vSelStocInit := vSelStocInit ||'
    GROUP BY NS.CODOBIECT';

    sJoinRestCmd := '';
    if current_setting('PKG_LIST_BASE_NAPROVIZ2.vREstCmd', TRUE)::boolean then
      sJoinRestCmd := ' INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = C1.GESTACT::varchar AND FILTRU = ''CODGEST'' ';
    end if;

    vFiltruTermen := '';
    if current_setting('PKG_LIST_BASE_NAPROVIZ2.vCuTermen', TRUE)::boolean then
      vFiltruTermen := ' AND C1.TERMEN &lt;= '''||current_setting('PKG_LIST_BASE_NAPROVIZ2.vtermen', TRUE)||''' ';
    end if;

    /************************ Sfarsit Constructie Selecturi Auxiliare ***************************/

    PERFORM PKG_GLOBALS_SetSeparator(',');
    DELETE FROM TMP_CMD_TMP;
    if current_setting('PKG_LIST_BASE_NAPROVIZ2.vCuComenzi', TRUE)::NUMERIC &gt; 0 then
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,auxfield,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC)
      SELECT C1.CodObiect,
        case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
        to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantComandat else 0 end CantC,
        case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
        to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantAcceptat else 0 end CantA,
        C1.RestAcceptat RestA, ''CF'', to_char(C.nrdoc), C.CODCOMANDA, C.TIPDOC, C.PREFIXDOC, C.SERIADOC, C.NRDOC, C.DATADOC
      FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 8 '||vCondSub_C||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= to_date('''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''',''dd.mm.yyyy'')
        '||vFiltruTermen;
      PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC)
      SELECT C1.CodObiect,
        case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
        to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantComandat else 0 end CantC,
        case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
        to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantAcceptat else 0 end CantA,
        C1.RestAcceptat RestA, ''CC'', C.CODCOMANDA, C.TIPDOC, C.PREFIXDOC, C.SERIADOC, C.NRDOC, C.DATADOC
      FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 18 '||vCondSub_C||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= to_date('''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''',''dd.mm.yyyy'')';
      PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC)
      SELECT C1.CodObiect,
        case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
        to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantComandat else 0 end CantC,
        case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
        to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantAcceptat else 0 end CantA,
        C1.RestAcceptat RestA, ''CSERV'', C.CODCOMANDA, C.TIPDOC, C.PREFIXDOC, C.SERIADOC, C.NRDOC, C.DATADOC
      FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 92 '||vCondSub_C||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= to_date('''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''',''dd.mm.yyyy'')';
      PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC)
      SELECT C1.CodObiect,
        case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
        to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantComandat else 0 end CantC,
        case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
        to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantAcceptat else 0 end CantA,
        C1.RestAcceptat RestA, ''CSIN'', C.CODCOMANDA, C.TIPDOC, C.PREFIXDOC, C.SERIADOC, C.NRDOC, C.DATADOC
      FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 44 '||vCondSub_C||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= to_date('''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''',''dd.mm.yyyy'')';
      PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC)
      SELECT C1.CodObiect,
        case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
        to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantComandat else 0 end CantC,
        case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
        to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantAcceptat else 0 end CantA,
        C1.RestAcceptat RestA, ''CSIES'', C.CODCOMANDA, C.TIPDOC, C.PREFIXDOC, C.SERIADOC, C.NRDOC, C.DATADOC
      FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 44 '||vCondSub_CS||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= to_date('''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''',''dd.mm.yyyy'')';
      PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC)
      SELECT C1.CodObiect,
        case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
        to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantComandat else 0 end CantC,
        case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
        to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then C1.CantAcceptat else 0 end CantA,
        C1.RestAcceptat RestA, ''CG'', C.CODCOMANDA, C.TIPDOC, C.PREFIXDOC, C.SERIADOC, C.NRDOC, C.DATADOC
      FROM COMANDA1 C1
        INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
        INNER JOIN NGEST G ON C.CodGest = G.CodGest'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND G.Tip = 1 AND C.TipDoc = 43 '||vCondSub_C||'
        AND C1.RestAcceptat &gt; 0 AND C.DataDoc &lt;= to_date('''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''',''dd.mm.yyyy'')';
      PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
    sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC)
      SELECT CMDMAT.CodObiect,
        case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
        to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then CMDMAT.Cant else 0 end CantC,
        case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
        to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then CMDMAT.Cant else 0 end CantA,
        CMDMAT.Rest RestA, ''CIIN'', C.CODCOMANDA, C.TIPDOC, C.PREFIXDOC, C.SERIADOC, C.NRDOC, C.DATADOC
      FROM CMDPRODMAT CMDMAT
        INNER JOIN COMANDA1 C1 ON CMDMAT.CodComanda1 = C1.CodComanda1
        INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 53 '||vCondSub_C||'
        AND CMDMAT.Rest &gt; 0 AND C.DataDoc &lt;= to_date('''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''',''dd.mm.yyyy'')
        AND ((C1.Consum = 1 AND CMDMAT.Tip &lt;&gt; 1) OR (C1.Consum = 2 AND CMDMAT.Tip = 2))';
      PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
      sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,cantc,canta,resta,tip,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC)
      SELECT CMDMAT.CodObiect,
        case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
        to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then CMDMAT.Cant else 0 end CantC,
        case when C.DataDoc BETWEEN '''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni', TRUE), 'dd.mm.yyyy'))||''' AND '''||
        to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''' then CMDMAT.Cant else 0 end CantA,
        CMDMAT.Rest RestA, ''CIIES'', C.CODCOMANDA, C.TIPDOC, C.PREFIXDOC, C.SERIADOC, C.NRDOC, C.DATADOC
      FROM CMDPRODMAT CMDMAT
        INNER JOIN COMANDA1 C1 ON CMDMAT.CodComanda1 = C1.CodComanda1
        INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||sJoinRestCmd||'
      WHERE Nvl(C.INCHISA, 0) = 0
        AND C.Operat = 1 AND C.Anulat = 0 '||vCondSub_C||'
        AND CMDMAT.Rest &gt; 0 AND C.DataDoc &lt;= to_date('''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''',''dd.mm.yyyy'')
        AND ((C1.Consum = 1 AND CMDMAT.Tip = 1) OR (C1.Consum = 2 AND CMDMAT.Tip &lt;&gt; 2))';
      PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
    end if;
    sSelect := 'INSERT INTO TMP_CMD_TMP(codobiect,resta,tip,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC)
    SELECT I1.CodObiect,
      L1.RestIESVAL RestA, ''IESNED'', I.CODIES, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC
    FROM LIVR1 L1
      INNER JOIN LIVR L ON L.CODLIVR = L1.CODLIVR
      INNER JOIN IESIRI I ON I.CODIES = L.CODIES
      INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES AND L1.CODIES1 = I1.CODIES1
      INNER JOIN LIVRVAL LV ON LV.CODLIVR1 = L1.CODLIVR1'||chr(13);
    if NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', TRUE)::boolean THEN
      sSelect := sSelect||'INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = LV.GEST::varchar AND FILTRU = ''CODGEST'''||chr(13);
    end if;
  sSelect := sSelect||'
    WHERE I.Operat = 1 AND I.Anulat = 0 '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('I')||'
      AND L1.RestIESVAL &lt;&gt; 0 AND I.DataDoc &lt;= to_date('''||to_char(to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin', TRUE), 'dd.mm.yyyy'))||''',''dd.mm.yyyy'')';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
    DELETE FROM TMP_STOCREAL;
    PERFORM LIST_EXECUTE_IMMEDIATE('INSERT INTO tmp_stocreal(codobiect,cant,tip) '||vSelStocReal, aListID, aListVer);
    PERFORM LIST_EXECUTE_IMMEDIATE('INSERT INTO tmp_stocreal(codobiect,cant,tip) '||vSelStocInit, aListID, aListVer);
    PERFORM LIST_EXECUTE_IMMEDIATE('INSERT INTO tmp_cmd_tmp(codobiect,resta,tip,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC) '||vSelIes_Per, aListID, aListVer);
    if Length(vSelTr_Per) &gt; 0 THEN
      PERFORM LIST_EXECUTE_IMMEDIATE('INSERT INTO tmp_cmd_tmp(codobiect,resta,tip,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC) '||vSelTr_Per, aListID, aListVer);
    end if;
    if current_setting('PKG_LIST_BASE_NAPROVIZ2.vVanzEmul', TRUE)::boolean then
      PERFORM LIST_EXECUTE_IMMEDIATE('INSERT INTO tmp_cmd_tmp(codobiect,resta,tip,CODDOC,TIPDOC,PREFIXDOC,SERIADOC,NRDOC,DATADOC) '||vSelIes_Emul, aListID, aListVer);
    end if;
    DELETE FROM TMP_STOCREZ;
    sSelect := 'INSERT INTO tmp_stocrez(codobiect,rezervat)
    SELECT NS.CODOBIECT, SUM(R.REST) REZERVAT
    FROM REZERVATS R
      INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = R.CODNIRSTOC
      INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
      INNER JOIN NGEST G ON G.CODGEST = N.GEST '||vCondSub_G||'
    WHERE NVL(R.REST,0) &gt; 0';
    if NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', TRUE)::boolean 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
        sSelect := sSelect || ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = N.GEST::varchar)';
      elsif vCateGest = 0 then
        sSelect := sSelect || ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND VALOARE = NS.CODLOCATIE::varchar)';
      else
        sSelect := sSelect || ' 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;
    if NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateIoart', TRUE)::boolean then
      sSelect := sSelect || ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND VALOARE = NS.CODIOART::varchar ) ';
    end if;
    sSelect := sSelect||' GROUP BY NS.CODOBIECT,NS.D1,NS.D2,NS.D3';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);

    IF current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateIoart', TRUE)::boolean
    THEN sUltNirstoc := 'SELECT 0 CODOBIECT, 0 CODNIRSTOC';--'SELECT CODOBIECT, MAX(CODNIRSTOC) KEEP (DENSE_RANK LAST ORDER BY DATAACHIZ, CODNIRSTOC) CODNIRSTOC FROM NIRSTOC WHERE FURN &gt; 0 AND Nvl(CODNIRSTOCPARINTE,0) = 0 GROUP BY CODOBIECT';
    ELSE sUltNirstoc := 'SELECT 0 CODOBIECT, 0 CODNIRSTOC';
    END IF;
  end if;
  sAfectare := '';
  --if pkg_list_base_naproviz2.GETPEZILE = 1 then
    if current_setting('PKG_LIST_BASE_NAPROVIZ2.vAfectare', TRUE)::NUMERIC = 1 then
      sAfectare := ' - NVL(NAOS.STOCMIN,0) ';
    end if;
    if current_setting('PKG_LIST_BASE_NAPROVIZ2.vAfectare', TRUE)::NUMERIC = 2 then
      sAfectare := ' - NVL(NAOS.STOCMED,0) ';
    end if;
    if current_setting('PKG_LIST_BASE_NAPROVIZ2.vAfectare', TRUE)::NUMERIC = 3 then
      sAfectare := ' - NVL(NAOS.STOCMAX,0) ';
    end if;
  --end if;
  vUserid := GETUSERID();
  delete FROM tmp_cmd where userid = vUSERID;
  if current_setting('PKG_LIST_BASE_NAPROVIZ2.vDim', TRUE)::boolean then
    INSERT INTO TMP_CMD_TMP(CODOBIECT, TIP, D1, D2, D3)
    SELECT DISTINCT CODOBIECT, 'OBJ', D1, D2, D3
    FROM
    (SELECT CODOBIECT, D1, D2, D3
     FROM TMP_CMD_TMP
     UNION ALL
     SELECT CODOBIECT, D1, D2, D3
     FROM TMP_STOCREAL
    ) a_pg;
    insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid,d1,d2,d3)
    select codobiect, sum(coalesce(cantc,0)), sum(coalesce(canta,0)), sum(coalesce(resta,0)), tip, vuserid, d1, d2, d3
    from tmp_cmd_tmp
    group by codobiect, tip, vuserid, d1, d2, d3;
    sInsert:=
    'INSERT INTO '||tmpName||'(
      CodObiect,Articol, UM, TotVanz, MedieVanz, MedieVanzZ,
      Necesar,
      StocReal,
      CodExtern, CodIntern, Producator, StocMIN, StocMED, StocMAX,
      CantC_CF, CantA_CF, RestA_CF,
      CantC_CC, CantA_CC, RestA_CC,
      CantC_CSERV, CantA_CSERV, RestA_CSERV,
      CantC_CSIn, CantA_CSIn, RestA_CSIn,
      CantC_CSIes, CantA_CSIes, RestA_CSIes,
      CantC_CG, CantA_CG, RestA_CG,
      CantC_CIIn, CantA_CIIn, RestA_CIIn,
      CantC_CIIes, CantA_CIIes, RestA_CIIes,
      Rezervat, UltFurn, UltPrAchiz, NrComFurn, NrZile, NrZileNec, D1, D2, D3'||gUserFields||')
    SELECT
      NAO.CODOBIECT, NAO.DENUMIRE, NUM.DEN_UM, COALESCE(IP.CANT,0) TOTVANZ, CEIL(COALESCE(IP.CANT,0) / '||vNrLuni||') MEDIEVANZ,
      COALESCE(IP.CANT,0) / '||vNrZilePer||' MEDIEVANZZ,
      --GREATEST(CEIL(COALESCE(IP.CANT,0) / '||vNrLuni||') - NVL(SR.Cant, 0) - NVL(SI.Cant, 0) - NVL(CG.RESTA,0) + NVL(CF.RESTA,0) - NVL(CC.RESTA,0) - NVL(CSERV.RESTA,0) + NVL(CSIN.RESTA,0) - NVL(CSIES.RESTA,0) + NVL(CIIN.RESTA,0) - NVL(CIIES.RESTA,0),0) Necesar,';
    if current_setting('PKG_LIST_BASE_NAPROVIZ2.vPeZile', TRUE)::boolean then
      sInsert := sInsert||'
        GREATEST(CEIL(COALESCE(COALESCE(IP.CANT,0),0) / '||vNrZilePer||' * '||current_setting('PKG_LIST_BASE_NAPROVIZ2.vNrZile', TRUE)||') - NVL(SR.Cant, 0)'||sAfectare||' + NVL(CG.RESTA,0) - NVL(CF.RESTA,0) + NVL(CC.RESTA,0) + NVL(CSERV.RESTA,0) - NVL(CSIN.RESTA,0) + NVL(CSIES.RESTA,0) - NVL(CIIN.RESTA,0) + NVL(CIIES.RESTA,0),0) Necesar, '||chr(13);
    else
      sInsert := sInsert||'
        GREATEST(CEIL(COALESCE(COALESCE(IP.CANT,0),0) / '||vNrLuni||') - NVL(SR.Cant, 0)'||sAfectare||' + NVL(CG.RESTA,0) - NVL(CF.RESTA,0) + NVL(CC.RESTA,0) + NVL(CSERV.RESTA,0) - NVL(CSIN.RESTA,0) + NVL(CSIES.RESTA,0) - NVL(CIIN.RESTA,0) + NVL(CIIES.RESTA,0),0) Necesar,';
    end if;
    sInsert := sInsert||'
      NVL(SR.CANT,0) STOCREAL,
      NAO.CODEXTERN, NAO.CODINTERN, PROD.DEN_PART'||sColMinMax||',
      NVL(CF.CANTC,0), NVL(CF.CANTA,0), NVL(CF.RESTA,0),
      NVL(CC.CANTC,0), NVL(CC.CANTA,0), NVL(CC.RESTA,0),
      NVL(CSERV.CANTC,0), NVL(CSERV.CANTA,0), NVL(CSERV.RESTA,0),
      NVL(CSIN.CANTC,0), NVL(CSIN.CANTA,0), NVL(CSIN.RESTA,0),
      NVL(CSIES.CANTC,0), NVL(CSIES.CANTA,0), NVL(CSIES.RESTA,0),
      NVL(CG.CANTC,0), NVL(CG.CANTA,0), NVL(CG.RESTA,0),
      NVL(CIIN.CANTC,0), NVL(CIIN.CANTA,0), NVL(CIIN.RESTA,0),
      NVL(CIIES.CANTC,0), NVL(CIIES.CANTA,0), NVL(CIIES.RESTA,0),
      SREZ.REZERVAT, UF.DEN_PART, NVL(UNS.PRET,0) - Nvl(UNS.ADAOS,0), CF.AuxField,'||vNrZilePer||','||to_char(current_setting('PKG_LIST_BASE_NAPROVIZ2.vNrZile', TRUE))||',TMP.D1, TMP.D2, TMP.D3'||gUserAlias||'
    FROM (SELECT CODOBIECT, D1, D2, D3 FROM TMP_CMD_TMP WHERE TIP = ''OBJ'') TMP
      INNER JOIN NARTOBJ NAO ON NAO.CODOBIECT = TMP.CODOBIECT
      INNER JOIN NART NA ON NA.CODARTICOL = NAO.CODARTICOL
      INNER JOIN NUM ON NUM.CODUM = NA.UM
      LEFT JOIN ('||sUltNirstoc||') X ON X.CODOBIECT = NAO.CODOBIECT
      LEFT JOIN NIRSTOC UNS ON UNS.CODNIRSTOC = X.CODNIRSTOC
      LEFt JOIN NPART UF ON UF.CODPART = UNS.FURN
      LEFT JOIN NIR UNIR ON UNIR.CODNIR = UNS.CODNIR
      LEFT JOIN INTRARI UINTR ON UINTR.CODINTR = UNIR.CODINTR AND UINTR.TIPDOC = 6
      LEFT JOIN NSUBUNIT USUB ON USUB.CODSUBUNIT = UINTR.CODSUBUNIT
      LEFT JOIN NARTOBJSUBUNIT NAOS ON NAO.CODOBIECT = NAOS.CODOBIECT
                                    and (NAOS.codgest is null or NAOS.codgest = 0)
                                    AND NAOS.SUBUNITATE = '||GETSUBUNITATE()||'
      LEFT JOIN TMP_STOCREAL SR ON SR.CODOBIECT = NAO.CODOBIECT AND SR.TIP = ''REAL'' AND SR.D1 = TMP.D1 AND SR.D2 = TMP.D2 AND SR.D3 = TMP.D3
      LEFT JOIN TMP_STOCREZ SREZ ON SREZ.CODOBIECT = NAO.CODOBIECT AND SREZ.D1 = TMP.D1 AND SREZ.D2 = TMP.D2 AND SREZ.D3 = TMP.D3
      LEFT JOIN TMP_STOCREAL SI ON SI.CODOBIECT = NAO.CODOBIECT AND SI.TIP = ''INIT'' AND SI.D1 = TMP.D1 AND SI.D2 = TMP.D2 AND SI.D3 = TMP.D3
      LEFT JOIN TMP_CMD CF ON CF.CODOBIECT = NAO.CODOBIECT AND CF.TIP = ''CF'' AND CF.D1 = TMP.D1 AND CF.D2 = TMP.D2 AND CF.D3 = TMP.D3 AND CF.USERID = '||TO_CHAR(VUSERID)||'
      LEFT JOIN TMP_CMD CC ON CC.CODOBIECT = NAO.CODOBIECT AND CC.TIP = ''CC'' AND CC.D1 = TMP.D1 AND CC.D2 = TMP.D2 AND CC.D3 = TMP.D3 AND CC.USERID = '||TO_CHAR(VUSERID)||'
      LEFT JOIN TMP_CMD CSERV ON CSERV.CODOBIECT = NAO.CODOBIECT AND CSERV.TIP = ''CSERV'' AND CSERV.D1 = TMP.D1 AND CSERV.D2 = TMP.D2 AND CSERV.D3 = TMP.D3 AND CSERV.USERID = '||TO_CHAR(VUSERID)||'
      LEFT JOIN TMP_CMD CSIN ON CSIN.CODOBIECT = NAO.CODOBIECT AND CSIN.TIP = ''CSIN'' AND CSIN.D1 = TMP.D1 AND CSIN.D2 = TMP.D2 AND CSIN.D3 = TMP.D3 AND CSIN.USERID = '||TO_CHAR(VUSERID)||'
      LEFT JOIN TMP_CMD CSIES ON CSIES.CODOBIECT = NAO.CODOBIECT AND CSIES.TIP = ''CSIES'' AND CSIES.D1 = TMP.D1 AND CSIES.D2 = TMP.D2 AND CSIES.D3 = TMP.D3 AND CSIES.USERID = '||TO_CHAR(VUSERID)||'
      LEFT JOIN TMP_CMD CG ON CG.CODOBIECT = NAO.CODOBIECT AND CG.TIP = ''CG'' AND CG.D1 = TMP.D1 AND CG.D2 = TMP.D2 AND CG.D3 = TMP.D3 AND CG.USERID = '||TO_CHAR(VUSERID)||'
      LEFT JOIN TMP_CMD CIIN ON CIIN.CODOBIECT = NAO.CODOBIECT AND CIIN.TIP = ''CIIN'' AND CIIN.D1 = TMP.D1 AND CIIN.D2 = TMP.D2 AND CIIN.D3 = TMP.D3 AND CIIN.USERID = '||TO_CHAR(VUSERID)||'
      LEFT JOIN TMP_CMD CIIES ON CIIES.CODOBIECT = NAO.CODOBIECT AND CIIES.TIP = ''CIIES'' AND CIIES.D1 = TMP.D1 AND CIIES.D2 = TMP.D2 AND CIIES.D3 = TMP.D3 AND CIIES.USERID = '||TO_CHAR(VUSERID)||'
      LEFT JOIN NPART PROD ON PROD.CODPART = NAO.CODPRODUCATOR
      LEFT JOIN (select codobiect, sum(resta) cant, tip, D1, D2, D3 from TMP_CMD_TMP where tip = ''IES'' group by codobiect, tip, D1, D2, D3) IP ON IP.CODOBIECT = NAO.CODOBIECT AND IP.TIP = ''IES''
                AND IP.D1 = TMP.D1 AND IP.D2 = TMP.D2 AND IP.D3 = TMP.D3
      LEFT JOIN NCLASEA CLSA ON CLSA.CODCLASEA = NA.CLASA
      LEFT JOIN NCLASEAS CLSAS ON CLSAS.CODCLASEAS = NA.CLASASTATIST'||
      gSuplJoins||'
    WHERE NA.TIPARTICOL = ''0'' and coalesce(NAO.Blocat,0) in (0,3) ';
    if NOT current_setting('pkg_list_base_naproviz2.vAllCls', TRUE)::boolean THEN
      sInsert := sInsert||' and exists (select tmp.valoare from tmp_manevra_liste tmp, nclasea clsx
                                        where tmp.filtru = ''CODCLASEA'' and tmp.valoare = clsx.codclasea::varchar
                                              and INSTRB(CLSA.CODIDENT, clsx.codident) = 1) ';
    END IF;
  ELSE
    insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid)
    select codobiect, sum(coalesce(cantc,0)), sum(coalesce(canta,0)), sum(coalesce(resta,0)), tip, vuserid
    from tmp_cmd_tmp
    group by codobiect, tip, vuserid;
    sInsert:=
    'INSERT INTO '||tmpName||'(
      CodObiect,Articol, UM, TotVanz, MedieVanz, MedieVanzZ,
      Necesar,
      StocReal,
      CodExtern, CodIntern, Producator, StocMIN, StocMED, StocMAX,
      CantC_CF, CantA_CF, RestA_CF,
      CantC_CC, CantA_CC, RestA_CC,
      CantC_CSERV, CantA_CSERV, RestA_CSERV,
      CantC_CSIn, CantA_CSIn, RestA_CSIn,
      CantC_CSIes, CantA_CSIes, RestA_CSIes,
      CantC_CG, CantA_CG, RestA_CG,
      CantC_CIIn, CantA_CIIn, RestA_CIIn,
      CantC_CIIes, CantA_CIIes, RestA_CIIes,
      Rezervat, UltFurn, UltPrAchiz, NrComFurn, NrZile, NrZileNec'||gUserFields||')
    SELECT
      NAO.CODOBIECT, NAO.DENUMIRE, NUM.DEN_UM, COALESCE(IP.CANT,0) TOTVANZ, CEIL(COALESCE(IP.CANT,0) / '||vNrLuni||') MEDIEVANZ,
      COALESCE(IP.CANT,0) / '||vNrZilePer||' MEDIEVANZZ,
      --GREATEST(CEIL(COALESCE(IP.CANT,0) / '||vNrLuni||') - NVL(SR.Cant, 0) - NVL(SI.Cant, 0) - NVL(CG.RESTA,0) + NVL(CF.RESTA,0) - NVL(CC.RESTA,0) - NVL(CSERV.RESTA,0) + NVL(CSIN.RESTA,0) - NVL(CSIES.RESTA,0) + NVL(CIIN.RESTA,0) - NVL(CIIES.RESTA,0),0) Necesar,';
    if current_setting('pkg_list_base_naproviz2.vPeZile', true)::boolean then
      sInsert := sInsert||'
        GREATEST(CEIL(COALESCE(IP.CANT,0) / '||vNrZilePer||' * '||current_setting('PKG_LIST_BASE_NAPROVIZ2.vNrZile', TRUE)||') - NVL(SR.Cant, 0)'||sAfectare||' + NVL(CG.RESTA,0) - NVL(CF.RESTA,0) + NVL(CC.RESTA,0) + NVL(CSERV.RESTA,0) - NVL(CSIN.RESTA,0) + NVL(CSIES.RESTA,0) - NVL(CIIN.RESTA,0) + NVL(CIIES.RESTA,0),0) Necesar, '||chr(13);
    else
      sInsert := sInsert||'
        GREATEST(CEIL(COALESCE(IP.CANT,0) / '||vNrLuni||') - NVL(SR.Cant, 0)'||sAfectare||' + NVL(CG.RESTA,0) - NVL(CF.RESTA,0) + NVL(CC.RESTA,0) + NVL(CSERV.RESTA,0) - NVL(CSIN.RESTA,0) + NVL(CSIES.RESTA,0) - NVL(CIIN.RESTA,0) + NVL(CIIES.RESTA,0),0) Necesar,';
    end if;
    sInsert := sInsert||'
      NVL(SR.CANT,0) STOCREAL,
      NAO.CODEXTERN, NAO.CODINTERN, PROD.DEN_PART'||sColMinMax||',
      NVL(CF.CANTC,0), NVL(CF.CANTA,0), NVL(CF.RESTA,0),
      NVL(CC.CANTC,0), NVL(CC.CANTA,0), NVL(CC.RESTA,0),
      NVL(CSERV.CANTC,0), NVL(CSERV.CANTA,0), NVL(CSERV.RESTA,0),
      NVL(CSIN.CANTC,0), NVL(CSIN.CANTA,0), NVL(CSIN.RESTA,0),
      NVL(CSIES.CANTC,0), NVL(CSIES.CANTA,0), NVL(CSIES.RESTA,0),
      NVL(CG.CANTC,0), NVL(CG.CANTA,0), NVL(CG.RESTA,0),
      NVL(CIIN.CANTC,0), NVL(CIIN.CANTA,0), NVL(CIIN.RESTA,0),
      NVL(CIIES.CANTC,0), NVL(CIIES.CANTA,0), NVL(CIIES.RESTA,0),
      SREZ.REZERVAT, UF.DEN_PART, NVL(UNS.PRET,0) - Nvl(UNS.ADAOS,0), CF.AuxField,'||vNrZilePer||','||to_char(current_setting('PKG_LIST_BASE_NAPROVIZ2.vNrZile', TRUE))||gUserAlias||'
    FROM NARTOBJ NAO
      INNER JOIN NART NA ON NA.CODARTICOL = NAO.CODARTICOL
      INNER JOIN NUM ON NUM.CODUM = NA.UM
      LEFT JOIN ('||sUltNirstoc||') X ON X.CODOBIECT = NAO.CODOBIECT
      LEFT JOIN NIRSTOC UNS ON UNS.CODNIRSTOC = X.CODNIRSTOC
      LEFt JOIN NPART UF ON UF.CODPART = UNS.FURN
      LEFT JOIN NIR UNIR ON UNIR.CODNIR = UNS.CODNIR
      LEFT JOIN INTRARI UINTR ON UINTR.CODINTR = UNIR.CODINTR AND UINTR.TIPDOC = 6
      LEFT JOIN NSUBUNIT USUB ON USUB.CODSUBUNIT = UINTR.CODSUBUNIT
      LEFT JOIN NARTOBJSUBUNIT NAOS ON NAO.CODOBIECT = NAOS.CODOBIECT
                                    and (NAOS.codgest is null or NAOS.codgest = 0)
                                    AND NAOS.SUBUNITATE = '||GETSUBUNITATE()||'
      LEFT JOIN TMP_STOCREAL SR ON SR.CODOBIECT = NAO.CODOBIECT AND SR.TIP = ''REAL''
      LEFT JOIN TMP_STOCREZ SREZ ON SREZ.CODOBIECT = NAO.CODOBIECT
      LEFT JOIN TMP_STOCREAL SI ON SI.CODOBIECT = NAO.CODOBIECT AND SI.TIP = ''INIT''
      LEFT JOIN TMP_CMD CF ON CF.CODOBIECT = NAO.CODOBIECT AND CF.TIP = ''CF'' AND CF.USERID = '||TO_CHAR(VUSERID)||'
      LEFT JOIN TMP_CMD CC ON CC.CODOBIECT = NAO.CODOBIECT AND CC.TIP = ''CC'' AND CC.USERID = '||TO_CHAR(VUSERID)||'
      LEFT JOIN TMP_CMD CSERV ON CSERV.CODOBIECT = NAO.CODOBIECT AND CSERV.TIP = ''CSERV'' AND CSERV.USERID = '||TO_CHAR(VUSERID)||'
      LEFT JOIN TMP_CMD CSIN ON CSIN.CODOBIECT = NAO.CODOBIECT AND CSIN.TIP = ''CSIN'' AND CSIN.USERID = '||TO_CHAR(VUSERID)||'
      LEFT JOIN TMP_CMD CSIES ON CSIES.CODOBIECT = NAO.CODOBIECT AND CSIES.TIP = ''CSIES'' AND CSIES.USERID = '||TO_CHAR(VUSERID)||'
      LEFT JOIN TMP_CMD CG ON CG.CODOBIECT = NAO.CODOBIECT AND CG.TIP = ''CG'' AND CG.USERID = '||TO_CHAR(VUSERID)||'
      LEFT JOIN TMP_CMD CIIN ON CIIN.CODOBIECT = NAO.CODOBIECT AND CIIN.TIP = ''CIIN'' AND CIIN.USERID = '||TO_CHAR(VUSERID)||'
      LEFT JOIN TMP_CMD CIIES ON CIIES.CODOBIECT = NAO.CODOBIECT AND CIIES.TIP = ''CIIES'' AND CIIES.USERID = '||TO_CHAR(VUSERID)||'
      LEFT JOIN NPART PROD ON PROD.CODPART = NAO.CODPRODUCATOR
      LEFT JOIN (select codobiect, sum(resta) cant, tip from TMP_CMD_TMP where tip = ''IES'' group by codobiect, tip) IP ON IP.CODOBIECT = NAO.CODOBIECT AND IP.TIP = ''IES''
      LEFT JOIN NCLASEA CLSA ON CLSA.CODCLASEA = NA.CLASA
      LEFT JOIN NCLASEAS CLSAS ON CLSAS.CODCLASEAS = NA.CLASASTATIST'||
      gSuplJoins||'
    WHERE NA.TIPARTICOL = ''0'' and coalesce(NAO.Blocat,0) in (0,3) ';
    if NOT current_setting('PKG_LIST_BASE_NAPROVIZ2.vAllCls', TRUE)::boolean THEN
      sInsert := sInsert||' and exists (select tmp.valoare from tmp_manevra_liste tmp, nclasea clsx
                                        where tmp.filtru = ''CODCLASEA'' and tmp.valoare = clsx.codclasea::varchar
                                              and INSTRB(CLSA.CODIDENT, clsx.codident) = 1) ';
    END IF;
  end if;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  --DELETE TMP_CMD WHERE USERID = VUSERID;
  if current_setting('PKG_LIST_BASE_NAPROVIZ2.vNrZile', TRUE)::numeric &gt; 0 then
    PERFORM PKG_LIST_BASE_NAPROVIZ7_CalculeazaZileStoc(tmpName);
  end if;
  if current_setting('PKG_LIST_BASE_NAPROVIZ2.vDim', TRUE)::boolean then
  sInsert :=
  'DO LANGUAGE PLPGSQL $$
     DECLARE v_rec record;
   begin
     for v_rec in (
     select
       NAV_CodDoc,NAV_TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       Articol,UM,TotVanz,MedieVanz,Necesar,StocReal,CodExtern,CodIntern,Producator,StocMIN,StocMED,StocMAX,
       CantC_CF,CantA_CF,RestA_CF,
       CantC_CC,CantA_CC,RestA_CC,
       CantC_CSERV,CantA_CSERV,RestA_CSERV,
       CantC_CSIn,CantA_CSIn,RestA_CSIn,
       CantC_CSIes,CantA_CSIes,RestA_CSIes,
       CantC_CG,CantA_CG,RestA_CG,
       CantC_CIIn,CantA_CIIn,RestA_CIIn,
       CantC_CIIes,CantA_CIIes,RestA_CIIes,
       REZERVAT,UltFurn,UltPrAchiz,NrComFurn,NrZile,MedieVanzZ,NrZileNec,D1,D2,D3
     from '||tmpName||') loop
       INSERT INTO '||TMPNAME||'
       (
       NAV_CodDoc,NAV_TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       Articol,UM,CodExtern,CodIntern,
       D1,D2,D3
       )
       SELECT
       CodDoc,TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       v_rec.Articol,v_rec.UM,v_rec.CodExtern,v_rec.CodIntern,v_rec.D1,v_rec.D2,v_rec.D3
       FROM TMP_CMD_TMP
       WHERE TIP = ''IES'' AND CODOBIECT = V_REC.CODOBIECT AND D1 = V_REC.D1 AND D2 = V_REC.D2 AND D3 = V_REC.D3;
       INSERT INTO '||TMPNAME||'
       (
       NAV_CodDoc,NAV_TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       Articol,UM,CodExtern,CodIntern,
       D1,D2,D3
       )
       SELECT
       CodDoc,TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       v_rec.Articol,v_rec.UM,
       CantC,CantA,RestA,
       v_rec.D1,v_rec.D2,v_rec.D3
       FROM TMP_CMD_TMP
       WHERE TIP = ''CF'' AND CODOBIECT = V_REC.CODOBIECT AND D1 = V_REC.D1 AND D2 = V_REC.D2 AND D3 = V_REC.D3;
       INSERT INTO '||TMPNAME||'
       (
       NAV_CodDoc,NAV_TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       Articol,UM,CodExtern,CodIntern,
       CantC_CC,CantA_CC,RestA_CC,
       D1,D2,D3
       )
       SELECT
       CodDoc,TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       v_rec.Articol,v_rec.UM,v_rec.CodExtern,v_rec.CodIntern,
       CantC,CantA,RestA,
       v_rec.D1,v_rec.D2,v_rec.D3
       FROM TMP_CMD_TMP
       WHERE TIP = ''CC'' AND CODOBIECT = V_REC.CODOBIECT AND D1 = V_REC.D1 AND D2 = V_REC.D2 AND D3 = V_REC.D3;
       INSERT INTO '||TMPNAME||'
       (
       NAV_CodDoc,NAV_TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       Articol,UM,CodExtern,CodIntern,
       CantC_CSERV,CantA_CSERV,RestA_CSERV,
       D1,D2,D3
       )
       SELECT
       CodDoc,TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       v_rec.Articol,v_rec.UM,v_rec.CodExtern,v_rec.CodIntern,
       CantC,CantA,RestA,
       v_rec.D1,v_rec.D2,v_rec.D3
       FROM TMP_CMD_TMP
       WHERE TIP = ''CSERV'' AND CODOBIECT = V_REC.CODOBIECT AND D1 = V_REC.D1 AND D2 = V_REC.D2 AND D3 = V_REC.D3;
       INSERT INTO '||TMPNAME||'
       (
       NAV_CodDoc,NAV_TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       Articol,UM,CodExtern,CodIntern,
       CantC_CSIn,CantA_CSIn,RestA_CSIn,
       D1,D2,D3
       )
       SELECT
       CodDoc,TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       v_rec.Articol,v_rec.UM,v_rec.CodExtern,v_rec.CodIntern,
       CantC,CantA,RestA,
       v_rec.D1,v_rec.D2,v_rec.D3
       FROM TMP_CMD_TMP
       WHERE TIP = ''CSIN'' AND CODOBIECT = V_REC.CODOBIECT AND D1 = V_REC.D1 AND D2 = V_REC.D2 AND D3 = V_REC.D3;
       INSERT INTO '||TMPNAME||'
       (
       NAV_CodDoc,NAV_TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       Articol,UM,CodExtern,CodIntern,
       CantC_CSIes,CantA_CSIes,RestA_CSIes,
       D1,D2,D3
       )
       SELECT
       CodDoc,TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       v_rec.Articol,v_rec.UM,v_rec.CodExtern,v_rec.CodIntern,
       CantC,CantA,RestA,
       v_rec.D1,v_rec.D2,v_rec.D3
       FROM TMP_CMD_TMP
       WHERE TIP = ''CSIES'' AND CODOBIECT = V_REC.CODOBIECT AND D1 = V_REC.D1 AND D2 = V_REC.D2 AND D3 = V_REC.D3;
       INSERT INTO '||TMPNAME||'
       (
       NAV_CodDoc,NAV_TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       Articol,UM,CodExtern,CodIntern,
       CantC_CG,CantA_CG,RestA_CG,
       D1,D2,D3
       )
       SELECT
       CodDoc,TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       v_rec.Articol,v_rec.UM,v_rec.CodExtern,v_rec.CodIntern,
       CantC,CantA,RestA,
       v_rec.D1,v_rec.D2,v_rec.D3
       FROM TMP_CMD_TMP
       WHERE TIP = ''CG'' AND CODOBIECT = V_REC.CODOBIECT AND D1 = V_REC.D1 AND D2 = V_REC.D2 AND D3 = V_REC.D3;
       INSERT INTO '||TMPNAME||'
       (
       NAV_CodDoc,NAV_TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       Articol,UM,CodExtern,CodIntern,
       CantC_CIIn,CantA_CIIn,RestA_CIIn,
       D1,D2,D3
       )
       SELECT
       CodDoc,TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       v_rec.Articol,v_rec.UM,v_rec.CodExtern,v_rec.CodIntern,
       CantC,CantA,RestA,
       v_rec.D1,v_rec.D2,v_rec.D3
       FROM TMP_CMD_TMP
       WHERE TIP = ''CIIN'' AND CODOBIECT = V_REC.CODOBIECT AND D1 = V_REC.D1 AND D2 = V_REC.D2 AND D3 = V_REC.D3;
       INSERT INTO '||TMPNAME||'
       (
       NAV_CodDoc,NAV_TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       Articol,UM,CodExtern,CodIntern,
       CantC_CIIes,CantA_CIIes,RestA_CIIes,
       D1,D2,D3
       )
       SELECT
       CodDoc,TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       v_rec.Articol,v_rec.UM,v_rec.CodExtern,v_rec.CodIntern,
       CantC,CantA,RestA,
       v_rec.D1,v_rec.D2,v_rec.D3
       FROM TMP_CMD_TMP
       WHERE TIP = ''CIIES'' AND CODOBIECT = V_REC.CODOBIECT AND D1 = V_REC.D1 AND D2 = V_REC.D2 AND D3 = V_REC.D3;
      UPDATE '||TMPNAME||' SET
       TotVanz = NULL,
       CantC_CF = NULL,CantA_CF = NULL,RestA_CF = NULL,
       CantC_CC = NULL,CantA_CC = NULL,RestA_CC = NULL,
       CantC_CSERV = NULL,CantA_CSERV = NULL,RestA_CSERV = NULL,
       CantC_CSIn = NULL,CantA_CSIn = NULL,RestA_CSIn = NULL,
       CantC_CSIes = NULL,CantA_CSIes = NULL,RestA_CSIes = NULL,
       CantC_CG = NULL,CantA_CG = NULL,RestA_CG = NULL,
       CantC_CIIn = NULL,CantA_CIIn = NULL,RestA_CIIn = NULL,
       CantC_CIIes = NULL,CantA_CIIes = NULL,RestA_CIIes = NULL
       WHERE NAV_CODDOC IS NULL AND NAV_TIPDOC IS NULL;
     end loop;
   END $$;';
  else
    sInsert :=
  'DO LANGUAGE PLPGSQL $$
     DECLARE v_rec record;
   begin
     for v_rec in (
     select
       NAV_CodDoc,NAV_TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       Articol,UM,TotVanz,MedieVanz,Necesar,StocReal,CodExtern,CodIntern,Producator,StocMIN,StocMED,StocMAX,
       CantC_CF,CantA_CF,RestA_CF,
       CantC_CC,CantA_CC,RestA_CC,
       CantC_CSERV,CantA_CSERV,RestA_CSERV,
       CantC_CSIn,CantA_CSIn,RestA_CSIn,
       CantC_CSIes,CantA_CSIes,RestA_CSIes,
       CantC_CG,CantA_CG,RestA_CG,
       CantC_CIIn,CantA_CIIn,RestA_CIIn,
       CantC_CIIes,CantA_CIIes,RestA_CIIes,
       REZERVAT,UltFurn,UltPrAchiz,NrComFurn,NrZile,MedieVanzZ,NrZileNec
     from '||tmpName||') loop
        INSERT INTO '||TMPNAME||'
       (
       NAV_CodDoc,NAV_TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       Articol,UM,TotVanz,CodExtern,CodIntern
       )
       SELECT
       CodDoc,TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       v_rec.Articol,v_rec.UM,RESTA,v_rec.CodExtern,v_rec.CodIntern
       FROM TMP_CMD_TMP
       WHERE TIP = ''IES'' AND CODOBIECT = V_REC.CODOBIECT;
       INSERT INTO '||TMPNAME||'
       (
       NAV_CodDoc,NAV_TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       Articol,UM,CodExtern,CodIntern,
       CantC_CF,CantA_CF,RestA_CF
       )
       SELECT
       CodDoc,TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       v_rec.Articol,v_rec.UM,v_rec.CodExtern,v_rec.CodIntern,
       CantC,CantA,RestA
       FROM TMP_CMD_TMP
       WHERE TIP = ''CF'' AND CODOBIECT = V_REC.CODOBIECT;
       INSERT INTO '||TMPNAME||'
       (
       NAV_CodDoc,NAV_TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       Articol,UM,CodExtern,CodIntern,
       CantC_CC,CantA_CC,RestA_CC
       )
       SELECT
       CodDoc,TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       v_rec.Articol,v_rec.UM,v_rec.CodExtern,v_rec.CodIntern,
       CantC,CantA,RestA
       FROM TMP_CMD_TMP
       WHERE TIP = ''CC'' AND CODOBIECT = V_REC.CODOBIECT;
       INSERT INTO '||TMPNAME||'
       (
       NAV_CodDoc,NAV_TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       Articol,UM,CodExtern,CodIntern,
       CantC_CSERV,CantA_CSERV,RestA_CSERV
       )
       SELECT
       CodDoc,TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       v_rec.Articol,v_rec.UM,v_rec.CodExtern,v_rec.CodIntern,
       CantC,CantA,RestA
       FROM TMP_CMD_TMP
       WHERE TIP = ''CSERV'' AND CODOBIECT = V_REC.CODOBIECT;
       INSERT INTO '||TMPNAME||'
       (
       NAV_CodDoc,NAV_TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       Articol,UM,CodExtern,CodIntern,
       CantC_CSIn,CantA_CSIn,RestA_CSIn
       )
       SELECT
       CodDoc,TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       v_rec.Articol,v_rec.UM,v_rec.CodExtern,v_rec.CodIntern,
       CantC,CantA,RestA
       FROM TMP_CMD_TMP
       WHERE TIP = ''CSIN'' AND CODOBIECT = V_REC.CODOBIECT;
       INSERT INTO '||TMPNAME||'
       (
       NAV_CodDoc,NAV_TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       Articol,UM,CodExtern,CodIntern,
       CantC_CSIes,CantA_CSIes,RestA_CSIes
       )
       SELECT
       CodDoc,TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       v_rec.Articol,v_rec.UM,v_rec.CodExtern,v_rec.CodIntern,
       CantC,CantA,RestA
       FROM TMP_CMD_TMP
       WHERE TIP = ''CSIES'' AND CODOBIECT = V_REC.CODOBIECT;
       INSERT INTO '||TMPNAME||'
       (
       NAV_CodDoc,NAV_TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       Articol,UM,CodExtern,CodIntern,
       CantC_CG,CantA_CG,RestA_CG
       )
       SELECT
       CodDoc,TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       v_rec.Articol,v_rec.UM,v_rec.CodExtern,v_rec.CodIntern,
       CantC,CantA,RestA
       FROM TMP_CMD_TMP
       WHERE TIP = ''CG'' AND CODOBIECT = V_REC.CODOBIECT;
       INSERT INTO '||TMPNAME||'
       (
       NAV_CodDoc,NAV_TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       Articol,UM,CodExtern,CodIntern,
       CantC_CIIn,CantA_CIIn,RestA_CIIn
       )
       SELECT
       CodDoc,TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       v_rec.Articol,v_rec.UM,v_rec.CodExtern,v_rec.CodIntern,
       CantC,CantA,RestA
       FROM TMP_CMD_TMP
       WHERE TIP = ''CIIN'' AND CODOBIECT = V_REC.CODOBIECT;
       INSERT INTO '||TMPNAME||'
       (
       NAV_CodDoc,NAV_TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       Articol,UM,CodExtern,CodIntern,
       CantC_CIIes,CantA_CIIes,RestA_CIIes
       )
       SELECT
       CodDoc,TipDoc,PrefixDoc,NrDoc,SeriaDoc,DataDoc,CodObiect,
       v_rec.Articol,v_rec.UM,v_rec.CodExtern,v_rec.CodIntern,
       CantC,CantA,RestA
       FROM TMP_CMD_TMP
       WHERE TIP = ''CIIES'' AND CODOBIECT = V_REC.CODOBIECT;
       UPDATE '||TMPNAME||' SET
       TotVanz = NULL,
       CantC_CF = NULL,CantA_CF = NULL,RestA_CF = NULL,
       CantC_CC = NULL,CantA_CC = NULL,RestA_CC = NULL,
       CantC_CSERV = NULL,CantA_CSERV = NULL,RestA_CSERV = NULL,
       CantC_CSIn = NULL,CantA_CSIn = NULL,RestA_CSIn = NULL,
       CantC_CSIes = NULL,CantA_CSIes = NULL,RestA_CSIes = NULL,
       CantC_CG = NULL,CantA_CG = NULL,RestA_CG = NULL,
       CantC_CIIn = NULL,CantA_CIIn = NULL,RestA_CIIn = NULL,
       CantC_CIIes = NULL,CantA_CIIes = NULL,RestA_CIIes = NULL
       WHERE NAV_CODDOC IS NULL AND NAV_TIPDOC IS NULL;
     end loop;
   END $$;';
  end if;
  execute sInsert;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nart_processlist</obj_name>
  <obj_hashval>cabeb65701d082c92d651389f9bbae76</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nart_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sAnLunaLucru   varchar;
  aCodSubunitate integer;
  sCodSubunitate varchar;
  sInsert        text;
  Toate          integer := 1;
  gUserFields    VARCHAR := '';
  gUserAlias     VARCHAR := '';
  gNullAlias     VARCHAR := '';
  gSuplCols      VARCHAR := '';
  gSuplJoins     VARCHAR := '';
  sColMinMax     varchar := ', os.stocmin, os.stocmed, os.stocmax';
begin
  --Florin - 18.08.2025 - sinc. Oracle
  --Bogdan 10.11.2022 - NTVA1
  --Adina 20.04.2021 - sinc.Oracle
  --Adina 09.03.2021 - prc_al_check
  --Adina 04.03.2021 - add col. X_...
  perform PKG_GLOBALS_SetSeparator(';');
  gSuplCols := 'nartobj o, nart a, nart1 a1, num u, num u1, num u2, num1 uamb, ngest ng, nclasea c, npart p, ncont nc, nclaseas cs, ncarsupart s, ioart ioa, ntari t, nartobj1 o1, pretm pm,'
            || 'nlocatii locimp, NAGENDA NAG, NLOCALIT LOC, NJUDET JUD';
  sAnLunaLucru := getAnLunaLucru()::varchar;
  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, 'NTVA1'     , 'T1'  , 'T1.CODTVA = A1.CODTVA AND ' || sAnLunaLucru || ' BETWEEN T1.ALSTART AND T1.ALSTOP',NULL);
  CALL pkg_list_struct_getsuplcols( aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_NART.gSuplCols', gSuplCols, False);


  SELECT Coalesce(PKG_GLOBALS_GETSUBUNITATE.WME_RESULT, 1) into aCodSubunitate FROM PKG_GLOBALS_GETSUBUNITATE(NULL,NULL);

  sCodSubunitate := aCodSubunitate:: varchar;
  IF  aCodSubunitate = 1 THEN  sColMinMax := ', o.stocmin, o.stocmed, o.stocmax'; END IF;
  sInsert:=
  'INSERT INTO '||tmpName||
    '(DenArt, TipSer, DenUM, DenClasaA, SimbolClasaA, Masa, Volum,
      StocMinim, StocMediu, StocMaxim, TipArticol, TipContabil, ContImplicit,
      CodIntern, CodExtern, Producator, GestImpl,
      Promotie, UMAmb, ParAmb, CNAS, AreTG, TipPretMax, Accize, TaxeSupl1, TaxeSupl2,
      NRCOLETE
      , x_Judet, X_CodSubunit,X_CodGest,X_CodClasaP'|| gUserFields ||')
  WITH
    NAI AS (
      SELECT CODARTICOL, CODSUBUNIT, CONTIMPLICIT, GESTIMPLICITA, LOCATIEIMPLICITA
      FROM nartimplicite
      WHERE codsubunit = '||sCodSUBUNITATE||')
  SELECT
    o.denumire, (case when a.tipserie = 0 then ''fara serie''   when a.tipserie = 1 then ''serie pe bucata''  when a.tipserie =  2 then ''serie pe lot'' end) tipser,
    u.den_um , c.Den_Clasea, c.simbol, o.Masa, o.Volum'||sColMinMax||', (case when a.tiparticol = ''0'' then ''Stoc'' when a.tiparticol = ''2'' then  ''Mijloc fix'' else ''Serviciu'' end) TipArt,
    ioa.den_ioart TipContabil, nc.simbol, o.codintern, o.codextern, p.den_part,
    ng.den_gest, (case when o.promotie = 0 then ''Nu'' else ''Da'' end), uamb.den_um1, uamb.paritate, o.codcnas, (case when a.aretg = 0 then ''Nu'' else ''Da'' end) aretg,
    (case when o1.tippretmax = 1 then ''din stoc * Impus'' when o1.tippretmax = 2 then ''din stoc * Recomandat'' when o1.tippretmax = 3 then ''din stoc * Netransmisibil''
                         when o1.tippretmax = 4 then ''lunar * Impus'' when o1.tippretmax = 5 then ''lunar * Recomandat'' when o1.tippretmax = 6 then ''lunar * Netransmisibil''
                         else ''nu se foloseste'' end), ntacc.den_taxa, ntax1.den_taxa, ntax2.den_taxa,
    (SELECT COUNT(1) FROM nartobjcolet oc WHERE oc.codobiect = o.codobiect)
    , coalesce(JUD.SIMBAUTO,''XX''), '||sCodSUBUNITATE||', ng.codgest, p.codclasa'|| gUserAlias||'
  FROM NARTOBJ o
    INNER JOIN nart             a      ON a.codarticol       = o.codarticol
    LEFT  JOIN nai                     ON nai.codarticol     = a.codarticol
    LEFT  JOIN nart1            a1     ON a1.codarticol     = o.codarticol AND '||sAnLunaLucru||' BETWEEN a1.alstart AND a1.alstop
    LEFT  JOIN nartobjsubunit   os     ON os.codobiect       = o.codobiect
                                       and (os.codgest is null or os.codgest = 0)
                                       AND os.subunitate   = '||sCodSUBUNITATE||'
    LEFT  JOIN nartimplicite    aimp   ON aimp.codarticol   = a.codarticol AND aimp.codsubunit = '||sCodSUBUNITATE||'
    LEFT  JOIN nlocatii         locimp on locimp.codlocatie = aimp.locatieimplicita
    LEFT  JOIN num              u      ON a.um               = u.codum
    LEFT  JOIN num              u1     ON u1.codum           = a.um1
    LEFT  JOIN num              u2     ON u2.codum           = a.um2
    LEFT  JOIN num1             uamb   ON uamb.codum1       = o.umambalare
    LEFT  JOIN ngest            ng     ON ng.codgest         = nai.gestimplicita
    LEFT  JOIN nclasea          c      ON c.codclasea       = Coalesce(a.clasa,0)
    LEFT  JOIN npart            p      ON p.codpart          = o.codproducator
    LEFT  JOIN NAGENDA          NAG    ON p.codpart         = NAG.CODPART AND NAG.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(NAG.INACTIV, 0) = 0
    LEFT  JOIN NLOCALIT         LOC    ON NAG.CODLOCALIT    = LOC.CODLOCALIT
    LEFT  JOIN NJUDET           JUD    ON JUD.CODJUDET      = LOC.CODJUDET
    LEFT  JOIN ioart            ioa    ON ioa.codioart       = nai.contimplicit
    LEFT  JOIN ioart1           ioa1   ON ioa1.codioart     = nai.contimplicit AND '||sAnLunaLucru||' BETWEEN ioa1.alstart AND ioa1.alstop
    LEFT  JOIN ncont            nc     ON nc.codcont         = (case when a.tiparticol=''0'' then ioa1.cont when a.tiparticol=''2'' then ioa1.cont else a.contserviciu end)
    LEFT  JOIN nclaseas         cs     ON cs.codclaseas     = a.clasastatist
    LEFT  JOIN ncarsupart       s      ON s.codcarsupart     = o.codcaract
    LEFT  JOIN ntari            t      ON t.codtara         = o.taraorigine
    LEFT  JOIN nartobj1         o1     ON o1.codobiect       = o.codobiect AND '||sAnLunaLucru||' BETWEEN o1.alstart AND o1.alstop
    LEFT  JOIN pretm            pm     ON pm.codobiect       = o.codobiect AND pm.implicit = 1 AND pm.subunitatea = '||sCodSUBUNITATE||'
    LEFT  JOIN ntaxe            ntacc  ON ntacc.codtaxa     = a1.codaccize
    LEFT  JOIN ntaxe            ntax1  ON ntax1.codtaxa     = a1.codtaxa1
    LEFT  JOIN ntaxe            ntax2  ON ntax2.codtaxa     = a1.codtaxa2'||
    gSuplJoins||'
  WHERE  a.codarticol &gt; 0 ';

  Toate := current_setting('PKG_LIST_BASE_NART.vToateArt', true)::integer;
  IF  Toate &lt;&gt; 1 THEN
    sInsert := sInsert || ' AND O.CODOBIECT IN ( SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' )';
  END IF;

  CALL PRC_AL_CHECK('NARTOBJ1');
  CALL PRC_AL_CHECK('NART1');
  CALL PRC_AL_CHECK('IOART1');
  CALL PRC_AL_CHECK('NTVA1');

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ncdoc_processlist</obj_name>
  <obj_hashval>ff6429595dc64ef42353be0ce00a4231</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ncdoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'intrari i, intrari1 i1, nartobj o, cantar c';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodNC          varchar := current_setting('PKG_LIST_BASE_NCDOC.vCodNC', true);
  sAnLunaLucru    varchar := coalesce(to_char(getAnLunaLucru(), 'fm99999'),'0');
BEGIN
    --Bogdan 10.07.2025 - 66145 PG - Note contabile diverse - extensie eroare coloane suplimentare
  --Adina 10.05.2021 - alstart,alstop, sAnLunaLucru
  --Adina 25 septembrie 2020
  CALL PRC_AL_CHECK('ncont1',0);

gSuplCols :=
    'NC N, NC1 N1, NMONEDE M, NGEST G, NPARCAUT PAUT, NPART NPD, NPART NPC, NCONT NCD, NCONT NCC, NCONT1 NC1D, NCONTS CSD, NCONT1 NC1C, NCONTS CSC, CENTRECOST CC, '||
    'ANALIZANOD ANOD, ANALIZA ANALIZ, DESCRIPTORI1 ADESC1, DESCRIPTORI ADESC, NPERS AGENT, FORMATII FORM';

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

  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || tmpName || '(
     Observatii, Moneda, Curs, NrLinie, TipLTva, SimbContDebit, SimbContCredit,
     Valoare, Gestiune, ObservatiiLinie, DenContDebit, DenContCredit, CentruCost' || gUserFields || ')
   SELECT
     N.OBS, M.SIMBOL, N.CURS, N1.INDEXLOCAL,
     (case N1.TIPLINIETVA when 2 then ''Baza TVA stocuri'' when 3 then ''Val. TVA stocuri'' when 4 then ''Baza TVA servicii'' when 5 then ''Val. TVA servicii'' else ''-'' end),
     NCD.SIMBOL, NCC.SIMBOL, N1.VALOARE, G.DEN_GEST, N1.Obs, NCD.DEN_CONT, NCC.DEN_CONT, CC.DENUMIRE ' || gUserAlias || '
   FROM NC N
     LEFT JOIN NC1          N1     ON N1.CODNC              = N.CODNC
     LEFT JOIN NMONEDE      M      ON M.CODMONEDA           = N.MONEDA
     LEFT JOIN NGEST        G      ON G.CODGEST             = N1.CODGEST
     LEFT JOIN NPARCAUT     PAUT   ON PAUT.CODNPARCAUT      = N1.CODAUTO
     LEFT JOIN NPART        NPD    ON NPD.CODPART           = CASE WHEN COALESCE(N1.PARTD,0) = 0 THEN 0 WHEN COALESCE(N1.CODPART,0) &lt;&gt; 0 THEN N1.CODPART ELSE N.PART END
     LEFT JOIN NPART        NPC    ON NPC.CODPART           = CASE WHEN COALESCE(N1.PARTC,0) = 0 THEN 0 WHEN COALESCE(N1.CODPART,0) &lt;&gt; 0 THEN N1.CODPART ELSE N.PART END
     LEFT JOIN NCONT        NCD    ON NCD.CODCONT           = CASE
                                                                WHEN N1.PARTD = 1 THEN PKG_LIST_BASE_UTILS_iCont_CodCont(N1.ICONTD, NPD.CODPART, N.AN*12+N.LUNA, 1200)
                                                                WHEN N1.PERSD = 1 THEN PKG_LIST_BASE_UTILS_iCont_CodCont(N1.ICONTD, N1.AGENT,    N.AN*12+N.LUNA, 1100)
                                                                ELSE N1.CONTD
                                                              END
     LEFT JOIN NCONT        NCC    ON NCC.CODCONT           = CASE
                                                                WHEN N1.PARTC = 1 THEN PKG_LIST_BASE_UTILS_iCont_CodCont(N1.ICONTC, NPC.CODPART, N.AN*12+N.LUNA, 1201)
                                                                WHEN N1.PERSC = 1 THEN PKG_LIST_BASE_UTILS_iCont_CodCont(N1.ICONTC, N1.AGENT,    N.AN*12+N.LUNA, 1101)
                                                                ELSE N1.CONTC
                                                              END
     LEFT JOIN NCONT1       NC1D   ON NC1D.CODCONT          = N1.CONTD AND ' || sAnLunaLucru || ' BETWEEN NC1D.ALSTART and NC1D.ALSTOP
     LEFT JOIN NCONTS       CSD    ON CSD.CODCONTS          = NC1D.CONTSECUNDAR
     LEFT JOIN NCONT1       NC1C   ON NC1C.CODCONT1         = N1.CONTC AND ' || sAnLunaLucru || ' BETWEEN NC1C.ALSTART and NC1C.ALSTOP
     LEFT JOIN NCONTS       CSC    ON CSC.CODCONTS          = NC1C.CONTSECUNDAR
     LEFT JOIN CENTRECOST   CC     ON CC.CODCENTRU          = CASE WHEN coalesce(N1.CODCENTRU,0) &gt; 0 THEN N1.CODCENTRU WHEN coalesce(NC1D.CODCENTRU,0) &gt; 0 THEN NC1D.CODCENTRU ELSE coalesce(NC1C.CODCENTRU,0) END
     LEFT JOIN ANALIZANOD   ANOD   ON anod.codanalizanod    = n1.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
     LEFT JOIN NPERS        AGENT  ON AGENT.CODPERS         = N1.AGENT
     LEFT JOIN FORMATII     FORM   ON FORM.CODFORMATIE      = N1.CODFORMATIE' || coalesce(current_setting('PKG_LIST_BASE_NCDOC.gSuplJoins', true),'') || '
   WHERE N.CodNC = ' || coalesce(vCodNC,'');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN (SELECT   P.DEN_PART, NC.OBS, NC.NRDOC, NC.DATADOC,
                        COALESCE(U.Nume, '...nedefinit...') UNUME, COALESCE(U.Prenume, '...nedefinit...') UPRENUME,
                        COALESCE(U.CNP, '...nedefinit...') UCNP, coalesce(U.BISERIA,'') || ' ' || coalesce(U.BINR::varchar ,'') UBI
                FROM   NC
                      LEFT JOIN NPART P ON  COALESCE(NC.PART, 0) = P.CODPART
                      LEFT JOIN NPERS U ON  U.LOGONNAME          = NC.USERID
                WHERE NC.CodNC = vCodNC::numeric
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Partener',           v_rec.Den_Part);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Observatii',         v_rec.Obs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Nr NC',             v_rec.NrDoc::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Data NC',           To_Char(v_rec.DataDoc, 'dd.mm.yyyy'));
    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_ncdoc_setjoinuri</obj_name>
  <obj_hashval>0fe738f9baa203c94b05e147d6c4c82c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ncdoc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 25 septembrie 2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_NCDOC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nir_setvverso</obj_name>
  <obj_hashval>a27c50e54a234a92b4865c29a518618c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_setvverso(avverso boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_NIR.vVerso',avVerso,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nom_utilaje_processlist</obj_name>
  <obj_hashval>73356ce0f8cd34d183264f8432cc8dc9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nom_utilaje_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'NARTOBJ NOBJ,NUM NUM,NPART CLI,NPART FURN,NLOCALIT LOC,MIFIX MF,UTILAJE U';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Florin 14.09.2023 - sinc. Oracle
  --Florin 12.09.2023 - sinc. Oracle
  --Adina 07.06.2021 - sinc.Oracle din 03.06.2021
  --Adina 16 septembrie 2020
  --Florin 01.04.2021 - fixat 46507
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_NOM_UTILAJE.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || tmpName || ' (
     NAV_CODDOC,
     NAV_TIPDOC,
     DENUMIRE,
     NRINVENTAR,
     ETICHETA,
     TIPUTILAJ,
     FLOTA,
     MODEL,
     ANF,
     SERIEF,
     INCARCARE,
     DATAGARANTIE,
     INGARANTIE,
     LUNGIME,
     LATIME,
     INALTIME,
     OBS,
     INACTIV,
     UM,
     PLAFONCANTF,
     GESTIUNE,
     CLIENT,
     DATAGARANTIEI,
     APROBAT,
     DATASTART,
     NRCONTR,
     DATACONTR,
     FURNIZOR,
     DOC,
     TIP,
     LOCALIT,
     ADRESA ' || gUserFields || ')
   SELECT
     U.CODUTILAJ,
     508,
     NOBJ.DENUMIRE,
     U.NRINVENTAR,
     U.ETICHETA,
     U.TIPUTILAJ,
     U.FLOTA,
     U.MODEL,
     U.ANF,
     U.SERIEF,
     U.INCARCARE,
     U.DATAGARANTIE,
     CASE WHEN U.INGARANTIE = 1 THEN ''DA'' ELSE ''NU'' END,
     U.LUNGIME,
     U.LATIME,
     U.INALTIME,
     U.OBS,
     CASE WHEN U.INACTIV = 1 THEN ''DA'' ELSE ''NU'' END,
     NUM.DEN_UM,
     U.PLAFONCANTF,
     GU.DEN_GEST,
     CLI.DEN_PART,
     U.DATAGARANTIEI,
     CASE WHEN U.APROBAT = 1 THEN ''DA'' ELSE ''NU'' END,
     U.DATASTART,
     U.NRCONTR,
     U.DATACONTR,
     FURN.DEN_PART,
     case when U.DOC is null and U.CODIES1 &gt; 0 then I.NRDoc||''/''||to_char(I.DataDoc,''DD.MM.YYYY'') else U.DOC end,
     CASE
       CASE
         WHEN U.TIP IS NULL AND U.CODPART &gt; 0 THEN 2
         ELSE
           CASE
             WHEN (SELECT COUNT(*) FROM UTILAJE1 WHERE CODUTILAJ = U.CODUTILAJ) &gt; 0 AND U.TIP IS NULL THEN 1
             ELSE coalesce(U.TIP,0)
           END
       END
       WHEN 0 THEN ''Utilaj propriu''
       WHEN 1 THEN ''Utilaj in custodie la client''
       WHEN 2 THEN ''Utilaj client''
       WHEN 3 THEN ''Utilaj client cu alt furnizor''
       WHEN 4 THEN ''Utilaj inchiriat clientului''
     END,
     LOC.DEN_LOCALIT,
     U.ADRESA
     ' || gUserAlias || '
   FROM UTILAJE U
        INNER JOIN NARTOBJ   NOBJ ON U.CODOBIECT     = NOBJ.CODOBIECT
        LEFT  JOIN NUM       NUM  ON NUM.CODUM       = U.UM
        LEFT  JOIN IESIRI1   I1   ON I1.CODIES1      = U.CODIES1
        LEFT  JOIN IESIRI    I    ON I1.CODIES       = I.CODIES
        LEFT  JOIN LIVR      L    ON L.CODIES        = I.CODIES
        LEFT  JOIN LIVR1     L1   ON I1.CODIES1      = L1.CODIES1 AND L1.CODLIVR = L.CODLIVR
        LEFT  JOIN NIRSTOC   NS   ON NS.CODNIRSTOC   = L1.CODNIRSTOC
        LEFT  JOIN NPART     P    ON NS.FURN         = P.CODPART
        LEFT  JOIN CONTRACT1 C1   ON C1.CODCONTRACT1 = I1.CODCONTRACT1
        LEFT  JOIN CONTRACT  C    ON C.CODCONTRACT   = I.CODCONTRACT
        LEFT  JOIN NGEST     GU   ON GU.CODGEST      = U.CODGEST
        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 MIFIX     MF   ON MF.NRINVENTAR   = U.NRINVENTAR AND MF.TIP = ''MF''
        ' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nompart_processlist</obj_name>
  <obj_hashval>9f5c3ef6a5ff1bdabeca673adee6ff07</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nompart_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  AnC         numeric;
  LunaC       numeric;
  AnT         numeric;
  LunaT       numeric;
  AnP         numeric;
  LunaP       numeric;
  sSoldPart   varchar := '';
  sCondPart   varchar := '';
  gSuplCols   varchar := 'NPART N, NPART1 N1, NPARTCODFISC FISC, NAGENDA NAG, NLOCALIT LOC, NJUDET JUD, NTARI TARA, NPARTB PARTB, NBANK NBANK, NLOCALIT LOCBANK, NCATPRET NPRET, NCLASEP NCL, IOPART IO, NPERS AGENT, NTIPSEDII TS';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 13.07.2022 - sinc. Oracle
  --Adina 09.03.2021 - prc_al_check
  --Adina 01.03.2021 - add col X_...
  --Adina 23.12.2020 - CIF_VALID cu un singur parametru
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET', 'PD', 'PD.CODPART = N.CODPART', NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_NOMPART.gSuplCols', gSuplCols, false);

  PERFORM PKG_LIST_STRUCT_SPLIT_COLUMN('NCLASEP', 'SIMBOL', '.', 'TMP_LEVEL1');

  AnT   := getanlucru();
  LunaT := getlunalucru();
  select  NEWAN, newLuna from PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA(AnT, LunaT, AnP, LunaP) into ANP, lunap;

  PERFORM PKG_GLOBALS_SetLunaPRECEDENTA(AnP, LunaP);
  PERFORM PKG_GLOBALS_SetLunaTEMP(AnT, LunaT);

  SELECT AnCurent, LunaCurenta INTO AnC, LunaC FROM FirmaLuni;


  IF AnC * 12 + LunaC &gt; AnT * 12 + LunaT   THEN
    sSoldPart := 'npartsoldluna
    WHERE AN = GetAnLUCRU() AND LUNA = GetLunaLUCRU()';
  ELSE
    PERFORM PKG_INCHIDERI_MAKE_REST_OBLIGPIF_LUNA();
    sSoldPart := 'v_soldpart_ext';
  END IF;

  sCondPart := '';
  IF current_setting('PKG_LIST_BASE_NOMPART.vAllPart', true):: numeric = 0 THEN
    sCondPart := ' and exists (select valoare from tmp_manevra_liste where valoare = N.CodPart::varchar and filtru = ''CODPART'') ';
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(
      DENUMIRE,CODFISCAL,REGCOM,LOCALITATE,JUDET,
      ADRESA
      ,TELEFON,EMAIL,CREDITF,CREDITC,
      SIMBOLBANCA,CONTBANCA,DISCOUNT,PERSFIZICA,
      CATEGPRET,CLASAPART,VOLUMTRANZC,VOLUMTRANZF,
      TIPCONT,SOLDREAL,SCADENTAC,SCADENTAV,DISTANTA,
      CUIVALID, POPRIREANAF, TVALAINC,InstP,
      NIVEL_1,NIVEL_2,NIVEL_3,NIVEL_4,NIVEL_5,NIVEL_6,NIVEL_7,NIVEL_8
      ,X_CodClasaP,x_Judet ' || gUserFields ||
  ')
    WITH NPS AS (
      SELECT codpart, SUM(soldlei) soldlei
      FROM ' || sSoldPart || '
      GROUP BY codpart
    ),
    VT AS (
      SELECT CODPART, SUM(VOLTRANZC) VOLTRANZC, SUM(VOLTRANZF) VOLTRANZF
      FROM (
            SELECT P1.CODPART, (Coalesce(VOLUMTRANZC, 0)) VOLTRANZC, (Coalesce(VOLUMTRANZF, 0)) VOLTRANZF
            FROM FIRMALUNI FL INNER JOIN NPART1 P1 ON P1.ANSTART = FL.ANINITIAL AND P1.LUNASTART = FL.LUNAINITIALA
            WHERE P1.CODPART &lt;&gt; 0
           UNION ALL
            SELECT O.CODPART, (Coalesce(VALTRANZC,0)) VOLTRANZC, (Coalesce(VALTRANZF,0)) VOLTRANZF
            FROM OBLIGPIF O INNER JOIN STINGERE S ON S.CODSTINSPIF = O.CODOBLIGPIF
            WHERE O.CODPART &lt;&gt; 0
           UNION ALL
            SELECT CODPART, (CASE WHEN SEMNIFICATIE = 410 THEN Coalesce(REST,0) ELSE 0 END) VOLTRANZC, (CASE WHEN SEMNIFICATIE = 310 THEN Coalesce(REST,0) ELSE 0 END) VOLTRANZF
            FROM OBLIGPIF obl
            WHERE SEMNIFICATIE IN (310, 410) AND CODPART &lt;&gt; 0
           UNION ALL
            SELECT CODPART, (Coalesce(VALOARE,0)) VOLTRANZC, 0 VOLTRANZF
            FROM EMULARE em
            WHERE CODPART &lt;&gt; 0
           ) sQuery
      GROUP BY CODPART
    )
    SELECT
      N.DEN_PART
      , coalesce(FISC.CODFISCAL,''nedef.''), coalesce(N.REGCOM,''nedef.''), coalesce(LOC.DEN_LOCALIT,''nedef.''), coalesce(JUD.DEN_JUDET,''nedef.''),
      coalesce((select getadresa.wme_result from getadresa('''',NAG.SECTOR,NAG.STRADA,NAG.NR1,NAG.NR2,NAG.BLOC,NAG.SCARA,NAG.ETAJ,NAG.APART,NAG.CODPOSTAL)),''nedef.'')
      ,NAG.TELEFON,NAG.EMAIL, coalesce(N1.CREDITFURN,0), coalesce(N1.CREDITCLIENT,0),
      coalesce(NBANK.SIMBOL,''nedef.''), coalesce(partb.contbanca,''nedef.''),coalesce(N.DISCOUNT,0), N.TIPPART::VARCHAR,
      coalesce(NPRET.DEN_CATPRET,''nedef.''), coalesce(NCL.DEN_CLASEP,''nedef.''), coalesce(VT.VOLTRANZC,0), coalesce(VT.VOLTRANZF,0),
      coalesce(IO.DEN_IOPART,''nedef.''),coalesce(NPS.SOLDLEI,0), coalesce(N.SCADENTAC,0), coalesce(N.SCADENTAV,0), coalesce(NAG.KM,0),
      (case when cif_valid(FISC.CodFiscal::varchar) = 1 then ''DA'' else ''NU'' end) CUIValid,
      (case when n.poprire_anaf = 1 then ''DA'' else ''NU'' end) POPRIREANAF,
      (case when n.tvalaincasare = 1 then ''DA'' else ''NU'' end) TVALAINC,
      case when bitand(n.tippartener,64) = 64 then ''DA'' else ''NU'' end,
      LVL1.NIVEL_1,LVL1.NIVEL_2,LVL1.NIVEL_3,LVL1.NIVEL_4,LVL1.NIVEL_5,LVL1.NIVEL_6,LVL1.NIVEL_7,LVL1.NIVEL_8
      , N.CODCLASA, coalesce(JUD.SIMBAUTO,''XX'')
  ' || gUserAlias || '
    FROM NPART N
      LEFT JOIN NPART1         N1      ON N.CODPART      = N1.CODPART AND ' || getanlunalucru() || ' BETWEEN N1.ALSTART AND N1.ALSTOP
      LEFT JOIN NPARTCODFISC   FISC    ON N.CODPART      =  FISC.CODPART AND FISC.PRINCIPAL = 1
      LEFT JOIN NAGENDA        NAG     ON N.CODPART      = NAG.CODPART AND NAG.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(NAG.INACTIV, 0) = 0
      LEFT JOIN NTIPSEDII      TS      ON TS.CODTIPSEDIU = NAG.CODTIPSEDIU
      LEFT JOIN NPERS          AGENT   ON NAG.CODAGENT   = AGENT.CODPERS
      LEFT JOIN NLOCALIT       LOC     ON NAG.CODLOCALIT = LOC.CODLOCALIT
      LEFT JOIN NJUDET         JUD     ON JUD.CODJUDET   = LOC.CODJUDET
      LEFT JOIN NTARI          TARA    ON TARA.CODTARA   = LOC.CODTARA
      LEFT JOIN NPARTB         PARTB   ON N.CODPART      = PARTB.CODPART AND PARTB.IMPLICIT = 1
      LEFT JOIN NBANK                  ON PARTB.CODBANK  = NBANK.CODBANK
      LEFT JOIN NLOCALIT       LOCBANK ON LOCBANK.CODLOCALIT = PARTB.CODLOCALIT
      LEFT JOIN NCATPRET       NPRET   ON N.CODCATEGPRET = NPRET.CODCATPRET
      LEFT JOIN NCLASEP        NCL     ON N.CODCLASA     = NCL.CODCLASEP
      LEFT JOIN IOPART         IO      ON N1.CODIOPART   = IO.CODIOPART
      LEFT JOIN TMP_LEVEL1     LVL1    ON LVL1.SIMBOL    = NCL.SIMBOL
      LEFT JOIN NPS                    ON N.CODPART      = NPS.CODPART
      LEFT JOIN VT                     ON VT.CODPART     = N.CODPART' || gSuplJoins || '
    WHERE N.CODPART &gt; 0 ' || sCondPart;

  CALL PRC_AL_CHECK('npart1');

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_notacont_guserfields</obj_name>
  <obj_hashval>9beef20df9bb0496bc272d88ec1d3802</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacont_guserfields(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NOTACONT.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_notacont_setgnullalias</obj_name>
  <obj_hashval>d90c89b7a7544fddced13a3e3873bed9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacont_setgnullalias(agnullalias character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_NOTACONT.gNullAlias',agNullAlias,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_parcautochelt_processlist</obj_name>
  <obj_hashval>e6569b1c1aa54f927ed39dd19314eace</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_parcautochelt_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC RECORD;
  sInsert     varchar;
  sSelect     varchar;
  sInsDC      varchar;
  sSelDC      varchar;
  sColDc      varchar;
  sKMZi       varchar;
  pStocComb   varchar;
  pServComb   varchar;
  sFiltruCC0  varchar;
  gSuplCols   varchar := 'nparcaut pa, npers s, nartobj o, nart a, nclasea ca';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Adina 10.05.2021 - prc_al_check
  --Adina 12.01.2021 tichet 42143 - inlocuit "= NULL" cu "IS NULL"
  --Florin 16.09.2020
  CALL PRC_AL_CHECK('ncont1', 0);

  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_PARCAUTOCHELT.gSuplCols', gSuplCols, FALSE);

  PERFORM pkg_globals_SetSeparator(',');
  pStocComb := COALESCE(fnc_getvalconstantalucru('ArtStocCombustibil'), '');
  pServComb := COALESCE(fnc_getvalconstantalucru('ArtServCombustibil'), '');
  sInsDC := ', CC0';
  sSelDC := ', AG.CC0';
  sColDC := ', SUM(valoare) CC0';

  FOR vRec IN (SELECT FIELDNAME, COD FROM tmp_dinamic_cols WHERE COD &lt;&gt; 0 AND  COD2 = 0 ORDER BY COD)
  LOOP
    sInsDC := coalesce(sInsDC,'') || ', '    || coalesce(vRec.FIELDNAME,'');
    sSelDC := coalesce(sSelDC,'') || ', AG.' || coalesce(vRec.FIELDNAME,'');
    sColDC := coalesce(sColDC,'') || ',
            SUM((CASE WHEN codcentru = ' || coalesce(vRec.COD::varchar ,'') || ' THEN valoare ELSE 0 END)) ' || coalesce(vRec.FIELDNAME,'');
  END LOOP;

  IF NOT current_setting('PKG_LIST_BASE_PARCAUTOCHELT.vCC0', true)::NUMERIC = 1 THEN
    sFiltruCC0 := '
        WHERE COALESCE(codcentru,0) &lt;&gt; 0';
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(NRAUTO, SOFER, ART, CLASA, AN, LUNA' || coalesce(sInsDC,'') || gUserFields || ')';

  sSelect := '
      WITH COSTURI AS (
        SELECT
          CASE WHEN COALESCE(i1.codauto,0) = 0 THEN i.codauto ELSE i1.codauto END codauto,
          (SELECT PKG_LIST_BASE_PARCAUTOCHELT_ContCodCentru.wme_result FROM PKG_LIST_BASE_PARCAUTOCHELT_ContCodCentru(NULL, i1.codcentru,i.an*12+i.luna,i1.contserv))::numeric codcentru,
          i.an, i.luna, (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
        FROM intrari i
          INNER JOIN intrari1 i1 ON i1.codintr = i.codintr
        WHERE (COALESCE(i1.codauto,0) &lt;&gt; 0 OR COALESCE(i.codauto,0) &lt;&gt; 0)
          AND i.an*12+i.luna BETWEEN ' || coalesce(current_setting('PKG_LIST_BASE_PARCAUTOCHELT.vAnLunaIni', true)::numeric,0) || ' AND ' || coalesce(current_setting('PKG_LIST_BASE_PARCAUTOCHELT.vAnLunaFin', true)::numeric,0) || '
          AND I.ANULAT = 0 AND I.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
        UNION ALL
        SELECT
          i.codauto, COALESCE(j.codcentru,0) codcentru, j.an, j.luna, j.valoare
        FROM iesiri i
          INNER JOIN jurnal j ON j.coddoc = i.codies AND j.tipdoc = i.tipdoc
        WHERE COALESCE(i.codauto,0) &lt;&gt; 0
          AND i.an*12+i.luna BETWEEN ' || coalesce(current_setting('PKG_LIST_BASE_PARCAUTOCHELT.vAnLunaIni', true)::numeric,0) || ' AND ' || coalesce(current_setting('PKG_LIST_BASE_PARCAUTOCHELT.vAnLunaFin', true)::numeric,0) || '
          AND I.ANULAT = 0 AND I.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
        UNION ALL
        SELECT
          o.codnparcaut codauto,
          (SELECT PKG_LIST_BASE_PARCAUTOCHELT_IContCodCentru.wme_result FROM PKG_LIST_BASE_PARCAUTOCHELT_IContCodCentru (NULL, o.codcentru,t.an*12+t.luna,o.icont,o.codpart,o.semnificatie))::numeric codcentru,
          t.an, t.luna, o.valoare
        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
        WHERE COALESCE(o.codnparcaut,0) &lt;&gt; 0
          AND t.an*12+t.luna BETWEEN ' || coalesce(current_setting('PKG_LIST_BASE_PARCAUTOCHELT.vAnLunaIni', true)::numeric,0) || ' AND ' || coalesce(current_setting('PKG_LIST_BASE_PARCAUTOCHELT.vAnLunaFin', true)::numeric,0) || '
          AND T1.ANULAT = 0 AND T.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL),'') || '
        UNION ALL
        SELECT
          nc1.codauto,
          (SELECT PKG_LIST_BASE_PARCAUTOCHELT_ContCodCentru.wme_result FROM PKG_LIST_BASE_PARCAUTOCHELT_ContCodCentru(NULL, nc1.codcentru,nc1.an*12+nc1.luna,nc1.contd,nc1.contc))::numeric codcentru,
          nc1.an, nc1.luna, nc1.valoare * (CASE WHEN nc.curs IS NULL THEN 1 WHEN nc.curs = 0 THEN 1 ELSE nc.curs END)
        FROM nc1
          INNER JOIN nc ON nc.codnc = nc1.codnc
        WHERE COALESCE(nc1.codauto,0) &lt;&gt; 0
          AND nc1.an*12+nc1.luna BETWEEN ' || coalesce(current_setting('PKG_LIST_BASE_PARCAUTOCHELT.vAnLunaIni', true)::numeric,0) || ' AND ' || coalesce(current_setting('PKG_LIST_BASE_PARCAUTOCHELT.vAnLunaFin', true)::numeric,0) || ' '
          || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('NC',NULL,NULL,NULL),'') || '
        UNION ALL
        SELECT
          pa.codnparcaut codauto, COALESCE(j.codcentru,0) codcentru, j.an, j.luna, j.valoare
        FROM jurnal j
          INNER JOIN mifix    mf ON mf.codmifix = j.coddoc
          INNER JOIN nparcaut pa ON pa.nrinv    = mf.nrinventar
        WHERE j.tipdoc = 36
          AND j.an*12+j.luna BETWEEN ' || coalesce(current_setting('PKG_LIST_BASE_PARCAUTOCHELT.vAnLunaIni', true)::numeric,0) || ' AND ' || coalesce(current_setting('PKG_LIST_BASE_PARCAUTOCHELT.vAnLunaFin', true)::numeric,0) || ' '
          || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('J',NULL,NULL,NULL),'') || '
      ),
      AG AS (
        SELECT codauto, an, luna' || coalesce(sColDC,'') || '
        FROM Costuri' || coalesce(sFiltruCC0,'') || '
        GROUP BY codauto, an, luna
      ),
      KMLUN AS (
        SELECT codnparcaut, an, luna, Sum(km) kmluna ' || coalesce(sKMZi,'') || '
        FROM (
          SELECT
            p.codnparcaut, p0.luna, p0.an, EXTRACT (DAY FROM p0.databord) zi,
            p0.kmbord - COALESCE(Lag(p0.kmbord) OVER (PARTITION BY p.codnparcaut ORDER BY p0.databord),p.kmpornire,0) km
          FROM nparc0 p0 INNER JOIN nparcaut p ON p.codnparcaut = p0.codnparcaut) b_pg
        WHERE an*12+luna BETWEEN ' || coalesce(current_setting('PKG_LIST_BASE_PARCAUTOCHELT.vAnLunaIni', true)::numeric,0) || ' AND ' || coalesce(current_setting('PKG_LIST_BASE_PARCAUTOCHELT.vAnLunaFin', true)::numeric,0) || '
        GROUP BY codnparcaut, an, luna
      )
      SELECT
        PA.NRINREG, S.NUME||'' ''||S.PRENUME, O.DENUMIRE, CA.DEN_CLASEA, AG.AN, AG.LUNA ' || coalesce(sSelDC,'') || gUserAlias || '
      FROM AG
        INNER JOIN nparcaut pa  ON pa.codnparcaut  = ag.codauto
        LEFT  JOIN npers    s   ON s.codpers       = COALESCE(pa.sofer,0)
        LEFT  JOIN nartobj  o   ON o.codobiect     = pa.codart
        LEFT  JOIN nart     a   ON a.codarticol    = o.codarticol
        LEFT  JOIN nclasea  ca  ON ca.codclasea    = COALESCE(a.clasa,0)
        LEFT  JOIN kmlun    kml ON kml.codnparcaut = ag.codauto AND kml.an = ag.an AND kml.luna = ag.luna' || 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_parcautochelt_setjoinuri</obj_name>
  <obj_hashval>91917ad4814320f7fe2571ff82912d78</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_parcautochelt_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 15.06.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_PARCAUTOCHELT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_parcautointerv_processlist</obj_name>
  <obj_hashval>72eaf8f5a7c564a1fa669d9aef8d6ef1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_parcautointerv_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  gSuplCols   varchar:= 'nparcaut pa, nparc3 p3, ninterventiiauto interv, npers s, mifix mf, nirstoc ns, ngest g, nartobj o ';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 16.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_PARCAUTOINTERV.gSuplCols', gSuplCols, FALSE);

  sInsert := 'INSERT INTO ' || tmpName || '(
      NAV_CodDoc, NAV_TipDoc,
      Den, NrInv, Sofer, Gest, Tip,
      NrInreg, DataInreg, Marca, Model, AnFab, SerieC, Culoare, Lung, Lat, Inalt,
      TipMotor, SerieMotor, Combustibil, Cilindree, Putere, Rezervor, CMM, CMU, CME,
      TipIncarc, Greutate, MasaMax, MasaUtil, MasaURDF, MasaURFDF,
      VolumUtil, LocTot, LocFata, LocSpate, LocPic,
      interv, datau, kmu, datav, kmv, dataa, kma, kmbord, databord ' || gUserFields || ')
    WITH mf1 AS (SELECT codmifix, Max(codnirstoc) codnirstoc FROM mifix1 GROUP BY codmifix)
    SELECT
      pa.codnparcaut, 505,
      o.denumire, pa.nrinv, (s.nume||'' ''||s.prenume) sofer, g.den_gest, (CASE WHEN pa.tip = 0 THEN ''TRACTAT'' ELSE ''MOTORIZAT'' END) tip,
      pa.nrinreg, pa.datainreg, ma.marca, mo.model, pa.anf, pa.seriec, pa.culoare, pa.lung, pa.lat, pa.inalt,
      pa.tipmotor, pa.seriem, pa.sursae, pa.cilindree, pa.putere, pa.rezervor, pa.cmm, pa.cmu, pa.cme,
      (CASE WHEN tipincarc = 1 THEN ''Marfa''WHEN tipincarc = 2 THEN ''Persoane'' WHEN tipincarc = 3 THEN ''Mixta'' END) tipincarc, pa.greutate, pa.masam, pa.masau, pa.masaurdf, pa.masaurfdf,
      pa.volumu, pa.loct, pa.locf, pa.locs, pa.locp,
      interv.denumire, p3.datau, p3.kmu, p3.datav, p3.kmv, p3.dataa, p3.kma, p0.kmbord, p0.databord' || gUserAlias || '
    FROM nparcaut pa
      INNER JOIN nparc3           p3     ON p3.cod        = pa.codnparcaut
      LEFT  JOIN ninterventiiauto interv ON interv.codinterventiiauto = p3.interventie
      LEFT  JOIN npers            s      on s.codpers     = pa.sofer
      LEFT  JOIN mifix            mf     ON mf.nrinventar = pa.nrinv
      LEFT  JOIN (select m1.codnirstoc, m1.codmifix
                  from mifix1 m1 where m1.anstart*12+m1.lunastart = (select max(m11.anstart*12+m11.lunastart) from mifix1 m11 where m11.codmifix = m1.codmifix)
                 )                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
      LEFT  JOIN (SELECT codnparcaut, Max(databord) databord, Max(kmbord) kmbord
                  FROM (SELECT codnparcaut, databord, kmbord, dense_rank() over(Partition by codnparcaut Order by kmbord desc) nr
                        FROM nparc0
                        WHERE COALESCE(kmbord,0) &lt;&gt; 0
                       ) xx
                  WHERE xx.nr=1
                  GROUP BY codnparcaut
                 ) p0 ON p0.codnparcaut = pa.codnparcaut
      ' || gSuplJoins ||
      ' where ((to_date(''' || current_setting('PKG_LIST_ALEGPERIOADA.gDataS', TRUE) || ''',''dd.mm.yyyy'') between P3.DataV and P3.DataU)
                or
                to_date(''' || current_setting('PKG_LIST_ALEGPERIOADA.gDataF', TRUE) || ''',''dd.mm.yyyy'') between P3.DataV and P3.DataU
              )
              or
              (P3.DataV 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'')
               or
               P3.DataU 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'')
              )';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_pf_locm_processlist</obj_name>
  <obj_hashval>632469f39b8bb78337ac1a44921b4696</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pf_locm_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sSelect     varchar;
  gSuplCols   varchar := 'prodcomp pc';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  v_rec RECORD;
BEGIN
  --Florin 14.09.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_PF_LOCM.gSuplCols',gSuplCols,false);

  sInsert := 'INSERT INTO ' || TMPNAME || '(
           CodLoc,
           LOCM,
           CI,
           Client,
           Produs,
           Cant,
           Disponibil,
           Necesar,
           CodIntern,
           CodExtern,
           DataProgramare,
           NrCmdCli,
           TermenLivrare,
           TermenExecutie
           ' || gUserFields || ')';
  sSelect := '
    with
    CRS_NECESAR AS
      (
        SELECT
          SUM( CASE
                WHEN PC.CANT &lt;&gt; 1 THEN PF1.CANTPROGRAMAT / PMAN.CANT * COALESCE(PMAN.TPI, 0)  + PF1.CANTPROGRAMAT / PMAN.BPS*PMAN.TU
                ELSE COALESCE(PMAN.TPI, 0) + PF1.CANTPROGRAMAT / PMAN.BPS*PMAN.TU
               END
             ) NECESAR,
          COALESCE(PMAN.CODLOC,0) CODLOC,
          C1.CODCOMANDA1,
          COALESCE(PMAN.CODOP,0) CODOP,
          pflmc.dataprogramare
        FROM programflmc pflmc
             inner join programf   pf   on pflmc.codprogramf = pf.codprogramf
             inner join comanda1   c1   on c1.codcomanda1    = pflmc.codcomanda1
             inner join programf1  pf1  on pf1.codprogramf   = pflmc.codprogramf and pf1.codcomanda1 = pflmc.codcomanda1
             INNER JOIN PRODCOMP   PC   ON C1.CODRETETA      = PC.CODPRODCOMP
             inner join comanda    c    on c.codcomanda      = c1.codcomanda
             inner join ngest      g    on c.codgest         = g.codgest
             inner join locmunca   lm   on lm.codloc         = pflmc.codloc
             left  join cmdprodman pman on pman.codcomanda1  = c1.codcomanda1 and pflmc.codloc = pman.codloc and pflmc.codop = pman.codop
        WHERE PFLMC.DATAPROGRAMARE 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'')
        GROUP BY c1.codcomanda1, pman.codloc, pflmc.dataprogramare, pman.codop
      )
      select
        pflmc.codloc,
        lm.denumire,
        c.prefixdoc||'' ''||c.nrdoc||''/''||to_char(c.datadoc,''dd.mm.yyyy''),
        p.den_part,
        obj.denumire,
        pf1.cantprogramat,
        (SELECT pkg_locmunca_GetDisponibilPeZi.wme_result FROM pkg_locmunca_GetDisponibilPeZi(NULL, pflmc.codloc))::numeric * 60,
        crs_Necesar.necesar,
        obj.CodIntern,
        obj.CodExtern,
        pflmc.dataprogramare,
        cc.prefixdoc||'' ''||cc.nrdoc||''/''||to_char(cc.datadoc,''dd.mm.yyyy''),
        cc1.termen,
        c1.termen' || gUserAlias || '
      from programflmc pflmc
           inner join programf   pf   on pflmc.codprogramf  = pf.codprogramf
           inner join comanda1   c1   on c1.codcomanda1     = pflmc.codcomanda1
           inner join programf1  pf1  on pf1.codprogramf    = pflmc.codprogramf and pf1.codcomanda1 = pflmc.codcomanda1
           inner join comanda    c    on c.codcomanda       = c1.codcomanda
           inner join ngest      g    on c.codgest          = g.codgest
           inner join locmunca   lm   on lm.codloc          = pflmc.codloc
           inner join nartobj    obj  on c1.codobiect       = obj.codobiect
           left  join prodcomp   pc   on c1.codreteta       = pc.codprodcomp
           left  join cmdprodman pman on pman.codcomanda1   = c1.codcomanda1 and pflmc.codloc = pman.codloc and pflmc.codop = pman.codop
           left  join comanda1   cc1  on cc1.codcomanda1    = (SELECT pkg_comanda_DinCmdCli.wme_result FROM pkg_comanda_DinCmdCli(NULL, c1.CodComanda1))::numeric
           left  join comanda    cc   on cc1.codcomanda     = cc.codcomanda
           left  join npart      p    on p.codpart          = COALESCE(cc.partener,0)
           left  join crs_necesar     on crs_necesar.codloc = pflmc.codloc and crs_necesar.codcomanda1 = pflmc.codcomanda1 and crs_necesar.dataprogramare = pflmc.dataprogramare
                                         and crs_necesar.codop = pflmc.codop' || gSuplJoins || '
      where pflmc.dataprogramare 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'')
      order by pflmc.dataprogramare';
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
  sSelect := 'DO $$'                                                                                            || Chr(10)||
            'declare'                                                                                           || Chr(10)||
            '  V_REC record; '                                                                                  || Chr(10)||
            'BEGIN'                                                                                             || Chr(10)||
            '  for v_rec in (select sum(tmp.necesar) tot, tmpp.dataprogramare, tmp.codloc'                      || Chr(10)||
            '                from (select distinct dataprogramare from ' || TMPNAME || ') tmpp'                 || Chr(10)||
            '                     inner join ' || TMPNAME || ' tmp on tmpp.dataprogramare = tmp.dataprogramare' || Chr(10)||
            '                group by tmpp.dataprogramare, tmp.codloc'                                          || Chr(10)||
            '               ) loop'                                                                             || Chr(10)||
            '    update ' || TMPNAME || ' set dif = COALESCE(disponibil,0) - COALESCE(v_rec.tot,0) where dataprogramare = v_rec.dataprogramare and codloc = v_rec.codloc;' || Chr(10)||
            '  end loop;'                                                                                       || Chr(10)||
            'END$$;';
  PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_pf_luna_processlist</obj_name>
  <obj_hashval>d67a1c799cf81cfd166ff384ff6d071b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pf_luna_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert      varchar;
  sSelect      varchar;
  sSubunitatea varchar;
  sDataS       varchar;
  sDataF       varchar;
  gSuplCols    varchar := 'PROGRAMF PF, COMANDA1 C1, COMANDA C, PRODCOMP PC, NARTOBJ NOBJ, PROGRAMF1 PF1, COMANDA1 C1CLIENT, COMANDA CCLIENT';
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplJoins   VARCHAR := '';
BEGIN
  --Adina 19.01.2021 tichet 42284 - add interval
  --Adina 18.01.2021 tichet 42272 - cast la date in fct. add_days
  --Florin 14.09.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_PF_LUNA.gSuplCols',gSuplCols,false);

  sSubunitatea := getsubunitate()::varchar;
  sDataS := current_setting('PKG_LIST_ALEGPERIOADA.gDataS', TRUE);
  sDataF := current_setting('PKG_LIST_ALEGPERIOADA.gDataF', TRUE);
  sInsert := 'INSERT INTO ' || TMPNAME || '(
         NAV_CODDOC,
         NAV_TIPDOC,
         PRIORITATE,
         CANTPROGRAMAT,
         DEN_GEST,
         NRCMD,
         DEN_OBIECT,
         CODEXTERN,
         UM,
         TERMENEXEC,
         DEN_CLIENT,
         TERMENLIVR,
         DURATA,
         DataOraStart,
         DataOraStop,
         Formatie,
         Schimb,
         Stoc,
         Rest ' || gUserFields || ')';
  sSelect := '
    SELECT
      PF.CODPROGRAMF,
      68,
      PF1.PRIORITATE,
      PF1.CANTPROGRAMAT,
      NG.DEN_GEST,
      C.NRDOC,
      NOBJ.DENUMIRE,
      NOBJ.CODEXTERN,
      NUM1.DEN_UM1,
      COALESCE(PF1.TERMEN,C1.TERMEN),
      NP.DEN_PART,
      c1client.termen,
      PF1.CANTPROGRAMAT * NUM1.Paritate / PC.CANT * PC.DURATA,
--      ADD_DAYS(PF.VDELA::date,(-(PF1.CANTPROGRAMAT * NUM1.Paritate / PC.CANT * (COALESCE(PC.DURATA,0)/60) / 24)
--      + SUM(PF1.CANTPROGRAMAT * NUM1.Paritate / PC.CANT * (COALESCE(PC.DURATA,0)/60) / 24)
--      over (PARTITION BY PF1.CODGEST ORDER BY PF1.PRIORITATE ROWS BETWEEN unbounded preceding AND CURRENT ROW))::INTEGER),
--      ADD_DAYS(PF.VDELA::date, (SUM(PF1.CANTPROGRAMAT * NUM1.Paritate / PC.CANT * (COALESCE(PC.DURATA,0)/60) / 24)
--      over (PARTITION BY PF1.CODGEST ORDER BY PF1.PRIORITATE ROWS BETWEEN unbounded preceding AND CURRENT ROW))::INTEGER),
      PF.VDELA + (-(PF1.CANTPROGRAMAT * NUM1.Paritate / PC.CANT * (COALESCE(PC.DURATA,0)/60) / 24)
                  + SUM(PF1.CANTPROGRAMAT * NUM1.Paritate / PC.CANT * (COALESCE(PC.DURATA,0)/60) / 24)
                  over (PARTITION BY PF1.CODGEST ORDER BY PF1.PRIORITATE ROWS BETWEEN unbounded preceding AND CURRENT ROW)
                 ) *INTERVAL ''1 day''  DataOraStart,
      PF.VDELA + (SUM(PF1.CANTPROGRAMAT * NUM1.Paritate / PC.CANT * (COALESCE(PC.DURATA,0)/60) / 24)
                  over (PARTITION BY PF1.CODGEST ORDER BY PF1.PRIORITATE ROWS BETWEEN unbounded preceding AND CURRENT ROW)
                 ) *INTERVAL ''1 day'' DataOraStop,
      FR.Den_Formatie,
      PF1.Schimb,
      COALESCE(Stoc.Cant,0),
      PF1.CANTPROGRAMAT - COALESCE((select sum(l.cant) from intrprodlink l where l.codprogramf1 = pf1.CODPROGRAMF1),0) ' || gUserAlias || '
    FROM PROGRAMF1 PF1
      INNER JOIN PROGRAMF PF   ON PF1.CODPROGRAMF = PF.CODPROGRAMF
      INNER JOIN NGEST    NG   ON NG.CODGEST      = PF1.CODGEST
      INNER JOIN COMANDA1 C1   ON C1.CODCOMANDA1  = PF1.CODCOMANDA1
      INNER JOIN COMANDA  C    ON C.CODCOMANDA    = C1.CODCOMANDA
      INNER JOIN PRODCOMP PC   ON C1.CODRETETA    = PC.CODPRODCOMP
      INNER JOIN NARTOBJ  NOBJ ON NOBJ.CODOBIECT  = C1.CODOBIECT
      INNER JOIN NUM1          ON  NUM1.CODUM1    = C1.UMSEC
      LEFT  JOIN (SELECT SUM(NS.REST) CANT, NS.CODOBIECT
                  FROM NIRSTOC NS
                       INNER JOIN NIR     ON NIR.CODNIR = NS.CODNIR
                       INNER JOIN NGEST G ON G.CODGEST  = NIR.GEST
                  WHERE (' || coalesce(sSubunitatea,'') || ' = 1 OR G.CODSUBUNIT = ' || coalesce(sSubunitatea,'') || ')
                        and NS.REST &lt;&gt; 0
                        AND NS.CODOBIECT IN (
                                              SELECT DISTINCT C1.CODOBIECT
                                              FROM PROGRAMF1 PF1
                                                   INNER JOIN PROGRAMF PF ON PF1.CODPROGRAMF = PF.CODPROGRAMF
                                                   INNER JOIN COMANDA1 C1 ON C1.CODCOMANDA1  = PF1.CODCOMANDA1
                                              WHERE (' || coalesce(sSubunitatea,'') || ' = 1 OR PF.SUBUNITATEA = ' || coalesce(sSubunitatea,'') || ')
                                                    AND PF1.TERMEN between to_date(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'')
                                                                       AND to_date(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'')
                                            )
                  GROUP BY NS.CODOBIECT
                 ) STOC ON STOC.CODOBIECT = C1.CODOBIECT
      LEFT  JOIN FORMATII FR       ON PF1.CodFormatie      = FR.CodFormatie
      LEFT  JOIN CMDLINK  CLINK    ON CLINK.CODCOMANDA1    = C1.CODCOMANDA1
      LEFT  JOIN COMANDA1 C1CLIENT ON C1CLIENT.CODCOMANDA1 = CLINK.CODLINIECOMANDA
      LEFT  JOIN COMANDA  CCLIENT  ON CCLIENT.CODCOMANDA   = C1CLIENT.CODCOMANDA
      LEFT  JOIN NPART    NP       ON NP.CODPART           = CCLIENT.PARTENER' || gSuplJoins || '
    WHERE (' || coalesce(sSubunitatea,'') || ' = 1 OR PF.SUBUNITATEA = ' || coalesce(sSubunitatea,'') || ')
          AND PF1.TERMEN between to_date(''' || coalesce(sDataS,'') || ''',''dd.mm.yyyy'')
                             AND to_date(''' || coalesce(sDataF,'') || ''',''dd.mm.yyyy'') ';
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_pfgantt_setjoinuri</obj_name>
  <obj_hashval>f4e6841d9faf1cd1f0285b7caf5f1b65</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pfgantt_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 21.07.2021 - sinc Oracle
  PERFORM pkg_list_struct_SetTableSpec((current_setting('PKG_LIST_BASE_PFGANTT.gSuplCols', true)));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_pfgantt_setparams</obj_name>
  <obj_hashval>effd8ce2c133647ecccbcecae15b8682</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pfgantt_setparams(pcodprogramf numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 21.07.2021 - sinc Oracle
  perform set_config('PKG_LIST_BASE_PFGANTT.vCodProgramF', pCodProgramF::varchar, FALSE);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_pontajesa_processlist</obj_name>
  <obj_hashval>f5687a6963e9fa57ab94bd955b7ada81</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pontajesa_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 := 'comanda4 c4, comanda2 c2, comanda3 c3, comanda c, iesiri i, iesiri bc';
   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 12.12.2024 - sinc. Oracle
  --Adina 14.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_PONTAJESA.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF  to_date(gDataS,'dd.mm.yyyy') = to_date(gDataF,'dd.mm.yyyy') THEN
    sPer := '= TO_DATE(''' || coalesce(gDataS,'') || ''',''dd.mm.yyyy'')';
  ELSE
    sPer := 'BETWEEN TO_DATE(''' || coalesce(gDataS,'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(gDataF,'') || ''',''dd.mm.yyyy'')';
  END IF;

  sInsert :=
  'INSERT INTO ' || tmpName || '(
      NAV_CodDoc,
      NAV_TipDoc,
      SERIADOC,
      NRDOC,
      DATADOC,
      OPERATIE,
      NumeAngajat,
      Formatie,
      LocMunca,
      OreLucrate,
      DataStart,
      DataStop,
      NumePartener,
      TIPComanda,
      SerieCaroserie,
      SerieMotor,
      StareComanda,
      Facturat,
      NrFact,
      DataFact,
      AnFact,
      LunaFact,
      Consumat,
      NrBC,
      DataBC,
      AnBC,
      LunaBC  ' || gUserFields || ')';

  sSelect := '
      with CA as (
        select sum(Coalesce(c1.cantacceptat,0)) cant, c1.codcomanda
        from comanda c
             inner join comanda1 c1 on c1.codcomanda = c.codcomanda
        WHERE C.TipDoc = 92 and coalesce(c1.modinchidere,0) in (0,1)
              AND C.DataDoc ' || coalesce(sPer,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || '
        group by c1.codcomanda
      ),
      RA as (
        select sum(Coalesce(c1.restacceptat,0)) cant, c1.codcomanda
        from comanda c
             inner join comanda1 c1 on c1.codcomanda = c.codcomanda
        WHERE C.TipDoc = 92 and coalesce(c1.modinchidere,0) in (0,1)
              AND C.DataDoc ' || coalesce(sPer,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || '
        group by c1.codcomanda
      ),
      CU_REST as (
        SELECT coalesce(COUNT(*),0) cant, c1.codcomanda
        FROM COMANDA1 c1
             inner join comanda c on c.codcomanda = c1.codcomanda
        WHERE coalesce(CANTACCEPTAT, 0) &gt; 0 AND coalesce(RESTACCEPTAT, 0) &gt; 0
              and C.TipDoc = 92 and coalesce(c1.modinchidere,0) in (0,1)
              AND C.DataDoc ' || coalesce(sPer,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || '
        group by c1.codcomanda
      ),
      BC_CA as (
        select sum(Coalesce(c1.cantacceptat,0)) cant, c1.codcomanda
        from comanda1 c1
             inner join comanda c on c.codcomanda = c1.codcomanda
             inner join nartobj o on o.codobiect  = c1.codobiect
             inner join nart a    on a.codarticol = o.codarticol
        WHERE C.TipDoc = 92 and coalesce(c1.modinchidere,0) = 2
              and a.tiparticol = ''0'' AND C.DataDoc ' || coalesce(sPer,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || '
        group by c1.codcomanda
      ),
      BC_RA as (
        select sum(Coalesce(c1.restacceptat,0)) cant, c1.codcomanda
        from comanda1 c1
             inner join comanda c on c.codcomanda = c1.codcomanda
             inner join nartobj o on o.codobiect  = c1.codobiect
             inner join nart a    on a.codarticol = o.codarticol
        WHERE C.TipDoc = 92 and coalesce(c1.modinchidere,0) = 2
              and a.tiparticol = ''0'' AND C.DataDoc ' || coalesce(sPer,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || '
        group by c1.codcomanda
      ),
      BC_CU_REST as (
        SELECT coalesce(COUNT(*),0) cant, c1.codcomanda
        FROM COMANDA1 c1
             inner join comanda c on c.codcomanda = c1.codcomanda
             inner join nartobj o on o.codobiect  = c1.codobiect
             inner join nart a    on a.codarticol = o.codarticol
        WHERE coalesce(c1.CANTACCEPTAT, 0) &gt; 0 AND coalesce(c1.RESTACCEPTAT, 0) &gt; 0
              and C.TipDoc = 92 and coalesce(c1.modinchidere,0) = 2
              and a.tiparticol = ''0'' AND C.DataDoc ' || coalesce(sPer,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || '
        group by c1.codcomanda
      ),
      Last_Fact as (
        select max(i.codies) codies, cc1.codcomanda
        from iesiri i
             inner join iesiri1 i1   on i.codies        = i1.codies
             inner join ieslink l    on l.codies1       = i1.codies1
             inner join comanda1 cc1 on cc1.codcomanda1 = l.codliniecomanda
             inner join (SELECT max(ii.datadoc) datadoc, c1.codcomanda
                         FROM comanda1 c1
                              inner join comanda c   on c.codcomanda       = c1.codcomanda
                              inner join ieslink li  on li.codliniecomanda = c1.codcomanda1
                              inner join iesiri1 ii1 on ii1.codies1        = li.codies1
                              inner join iesiri ii   on ii.codies          = ii1.codies
                         WHERE C.TipDoc = 92 and coalesce(c1.modinchidere,0) in (0,1)
                               AND C.DataDoc ' || coalesce(sPer,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || '
                               and ii.anulat = 0 and ii.operat = 1
                         group by c1.codcomanda) maxd on maxd.datadoc = i.datadoc and cc1.codcomanda = maxd.codcomanda
        where i.anulat = 0 and i.operat = 1
        group by cc1.codcomanda
      ),
      Last_BC as (
        select max(i.codies) codies, cc1.codcomanda
        from iesiri i
             inner join iesiri1 i1   on i.codies        = i1.codies
             inner join comanda1 cc1 on cc1.codcomanda1 = i1.codcmdint1
             inner join (SELECT max(ii.datadoc) datadoc, c1.codcomanda
                         FROM comanda1 c1
                              inner join comanda c   on c.codcomanda   = c1.codcomanda
                              inner join iesiri1 ii1 on ii1.codcmdint1 = c1.codcomanda1
                              inner join iesiri ii on ii.codies = ii1.codies
                         WHERE C.TipDoc = 92 and nvl(c1.modinchidere,0) = 2 and ii.tipdoc = 24
                               AND C.DataDoc '|| coalesce(sPer, '') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'')||'
                               and ii.anulat = 0 and ii.operat = 1
                               and not exists (select l.codies1 from ieslink l where l.codies1 = ii1.codies1)
                         group by c1.codcomanda) maxd on maxd.datadoc = i.datadoc and cc1.codcomanda = maxd.codcomanda
        where i.anulat = 0 and i.operat = 1 and i.tipdoc = 24
        and not exists (select l.codies1 from ieslink l where l.codies1 = i1.codies1)
        group by cc1.codcomanda
        union all
        select max(i.codies) codies, cc1.codcomanda
        from iesiri i
             inner join iesiri1 i1 on i.codies = i1.codies
             inner join ieslink l on l.codies1 = i1.codies1
             inner join comanda1 cc1 on cc1.codcomanda1 = l.codliniecomanda
             inner join (SELECT max(ii.datadoc) datadoc, c1.codcomanda
                         FROM comanda1 c1
                              inner join comanda c on c.codcomanda = c1.codcomanda
                              inner join ieslink l on l.codliniecomanda = c1.codcomanda1
                              inner join iesiri1 ii1 on ii1.codies1 = l.codies1
                              inner join iesiri ii   on ii.codies      = ii1.codies
                         WHERE C.TipDoc = 92 and coalesce(c1.modinchidere,0) = 2 and ii.tipdoc = 24
                               AND C.DataDoc ' || coalesce(sPer,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || '
                               and ii.anulat = 0 and ii.operat = 1
                         group by c1.codcomanda) maxd on maxd.datadoc = i.datadoc and cc1.codcomanda = maxd.codcomanda
        where i.anulat = 0 and i.operat = 1 and i.tipdoc = 24
        group by cc1.codcomanda
      )
      SELECT
        C.CodComanda,
        C.TipDoc,
        C.SeriaDoc,
        C.NrDoc,
        C.DataDOC,
        NO.Denumire Operatie,
        P.NUME||'' ''||P.PRENUME NumeAngajat,
        F.Den_Formatie Formatie,
        L.DENUMIRE LocMunca,
        C4.Ore OreLucrate,
        C4.datastart,
        C4.datastop,
        Pa.Den_Part NumePartener,
        Npc.TipComanda,
        NPA.SERIEC SerieCaroserie,
        NPA.Seriem SerieMotor,
        --Decode(C.Verificat ,0,''Initiala'',1,''Spre devizare'',2,''Finalizata'') StareComanda,
        CASE WHEN C.Anulat = 1 THEN ''ANULATA''
                               WHEN C.OPERAT = 0 THEN ''NEPRELUATA''
                               ELSE CASE WHEN C.Verificat &lt;&gt; 0 and coalesce(CU_REST.CANT,0) &lt;&gt; 0 THEN ''FINALIZATA''
                                         WHEN C.Verificat &lt;&gt; 0 and coalesce(CU_REST.CANT,0) = 0  THEN ''INCHISA''
                                         ELSE ''PRELUATA'' END
        END StareComanda,
        CASE
          WHEN C.FARAFACTURA = 1                                  THEN ''FARA FACTURARE''
          WHEN CA.Cant = 0                                        THEN ''NECONFIRMATA''
          WHEN CA.Cant = RA.Cant                                  THEN ''NEFACTURATA''
          WHEN CA.CANT &gt; RA.CANT AND coalesce(CU_REST.CANT,0) &gt; 0 THEN ''FACTURATA PARTIAL''
          WHEN CA.CANT &lt;&gt; 0 AND coalesce(CU_REST.CANT,0) = 0      THEN ''FACTURATA INTEGRAL''
          ELSE NULL
        END,
        i.nrdoc,
        i.datadoc,
        i.an,
        i.luna,
        CASE
          WHEN BC_CA.Cant = 0                                              THEN ''NECONFIRMATA''
          WHEN BC_CA.Cant = BC_RA.Cant                                     THEN ''NECONSUMATA''
          WHEN BC_CA.CANT &gt; BC_RA.CANT AND coalesce(BC_CU_REST.CANT,0) &gt; 0 THEN ''CONSUMATA PARTIAL''
          WHEN BC_CA.CANT &lt;&gt; 0 AND coalesce(BC_CU_REST.CANT,0) = 0         THEN ''CONSUMATA INTEGRAL''
          ELSE NULL
        END,
        bc.nrdoc,
        bc.datadoc,
        bc.an,
        bc.luna ' || gUserAlias || '
      FROM comanda4 c4
        Left join Comanda C    on C.CodComanda          = C4.CodComanda
        Left join Comanda3 C3  on C3.CodComanda3        = C4.CodComanda3
        Left join Comanda2 C2  on C2.CodComanda2        = C3.CodComanda2
        Left join NOper NO     on NO.CODOP              = C3.CodOperatie
        left join Nparccom NPC on NPC.CodComanda        = C.CodComanda
        Left join NparcAut NPA on NPA.CodNparcaut       = NPC.CodNparcaut
        LEFT JOIN FORMATII F   on F.CodFormatie         = C.CodFormatie
        LEFT JOIN FORMATII1 F1 on F1.CodFormatie        = F.CodFormatie
        LEFT JOIN LocMunca L   on L.CodLoc              = F1.LocMunca
        LEFT JOIN NPers P      on P.CodPers             = C4.CodPers
        LEFT JOIN NPart Pa     on Pa.CodPart            = C2.CodPart
        LEFT JOIN CA           ON CA.CODCOMANDA         = C.CODCOMANDA
        LEFT JOIN RA           ON RA.CODCOMANDA         = C.CODCOMANDA
        LEFT JOIN CU_REST      ON CU_REST.CODCOMANDA    = C.CODCOMANDA
        LEFT JOIN BC_CA        ON BC_CA.CODCOMANDA      = C.CODCOMANDA
        LEFT JOIN BC_RA        ON BC_RA.CODCOMANDA      = C.CODCOMANDA
        LEFT JOIN BC_CU_REST   ON BC_CU_REST.CODCOMANDA = C.CODCOMANDA
        left join last_fact    on last_fact.codcomanda  = c.codcomanda
        left join last_bc      on last_bc.codcomanda    = c.codcomanda
        left join iesiri i     on i.codies              = last_fact.codies
        left join iesiri bc    on bc.codies             = last_bc.codies ' || gSuplJoins || '
      WHERE C.TipDoc = 92
      AND C.DataDoc ' || coalesce(sPer,'') || 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_profit_processlist</obj_name>
  <obj_hashval>d267d13b0ec7c313789b2614cc077f9b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_profit_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sWith       varchar;
  sWithIni     varchar;
  sLG1         varchar;
  sLG2         varchar;
  sLG2Ini     varchar;
  sLG3         varchar;
  sLG4         varchar;
  sLGMon       varchar;
  sSelect     varchar;
  vToateGest  BOOLEAN := current_setting('PKG_LIST_SELECTIEPROFIT.vAllGest'  , TRUE)::boolean;
  vDupaData   BOOLEAN := current_setting('PKG_LIST_SELECTIEPROFIT.vDupaData' , TRUE)::boolean;
  vDataIni    varchar := current_setting('PKG_LIST_SELECTIEPROFIT.vDataIni'  , TRUE);
  vDataFin    varchar := current_setting('PKG_LIST_SELECTIEPROFIT.vDataFin'  , TRUE);
  vLunaAnIni  NUMERIC := current_setting('PKG_LIST_SELECTIEPROFIT.vLunaAnIni', TRUE)::NUMERIC;
  vLunaAnFin  NUMERIC := current_setting('PKG_LIST_SELECTIEPROFIT.vLunaAnFin', TRUE)::NUMERIC;
  vFactInt    BOOLEAN := current_setting('PKG_LIST_SELECTIEPROFIT.vIntern'   , TRUE)::boolean;
  vFactExt    BOOLEAN := current_setting('PKG_LIST_SELECTIEPROFIT.vExtern'   , TRUE)::boolean;
  vTransf     BOOLEAN := current_setting('PKG_LIST_SELECTIEPROFIT.vTransf'   , TRUE)::boolean;
  vSubunit    BOOLEAN := current_setting('PKG_LIST_SELECTIEPROFIT.vSubunit'  , TRUE)::boolean;
  vFactAviz   BOOLEAN := current_setting('PKG_LIST_SELECTIEPROFIT.vFactAviz' , TRUE)::boolean;
  vMon        BOOLEAN := current_setting('PKG_LIST_SELECTIEPROFIT.vMon'      , TRUE)::boolean;
  sCondI       varchar := '';
  sCondT       varchar := '';
  vCondGest   varchar := '';
  vMax         NUMERIC;
  i           NUMERIC;
  sDiscContr0 varchar := '';
  sDiscNC0     varchar := '';
  sDiscContr  varchar := '';
  sDiscNC     varchar := '';
  sJoinCadou   varchar := '';
  gSuplCols   varchar :=  'TMP_LST_PROFIT LG, NARTOBJ OBJ, NUM1 UM1, PACHETE C, TRANSPORT T, NMONEDE MONREF, NPART PROD, NGEST GPROD, NART ART, NCLASEA CLASAA, NAGENDA SED, NLOCALIT LOC, NJUDET J, CENTRECOST CC, NCONT CIO' || ',NIRSTOC NS,LIVR1 L1';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 19.04.2024 - sinc. Oracle
  --Florin 24.06.2022 - fixat 54708
  --Florin 05.05.2022 - sinc. Oracle
  --Adina 09.03.2021 - prc_al_check + 3 for-uri care lipseau
  --Adina 08.12.2020 tichet 41478
  --Florin 01.09.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_addsupltabs(gSuplCols, 'NPERS'     , 'AG_SED', 'AG_SED.CODPERS = SED.CODAGENT' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NZONE'     , 'Z'     , 'Z.CODZONA = LOC.CODZONA'       ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONT'     , 'CVENIT', 'CVENIT.CODCONT = COALESCE(IO1.VENITURI,0)'  , 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONT'     , 'CCHELT', 'CCHELT.CODCONT = COALESCE(IO1.CHELTUIELI,0)', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NGEST'     , 'GLIVR' , 'LG.CODGEST = GLIVR.CODGEST', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPART'     , 'FURN'  , 'FURN.CODPART = LG.FURN', 1);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_PROFIT.gSuplCols', gSuplCols, FALSE);

  vMax := (SELECT PKG_LIST_BASE_UTILS_NIVELE_NCLASEA.WME_RESULT FROM PKG_LIST_BASE_UTILS_NIVELE_NCLASEA(NULL,NULL));
  sDiscContr0 := ',
          0 cdisct,  0 cdiscc,  0 cdiscv,  0 cCodArtCad,  0 cCantArtCad,
            0 cdisctF, 0 cdisccF, 0 cdiscvF, 0 cCodArtCadF, 0 cCantArtCadF';

  IF current_setting('PKG_LIST_SELECTIEPROFIT.vExtra1', TRUE)::boolean THEN
    PERFORM PKG_CONTRACT_SIMULEAZA_DISCV(to_date(vDataIni, 'dd.mm.yyyy'), to_date(vDataFin, 'dd.mm.yyyy'), 0);
    PERFORM PKG_CONTRACT_SIMULEAZA_DISCC(to_date(vDataIni, 'dd.mm.yyyy'), to_date(vDataFin, 'dd.mm.yyyy'), 0);
    PERFORM PKG_CONTRACT_SIMULEAZA_CADOU(to_date(vDataIni, 'dd.mm.yyyy'), to_date(vDataFin, 'dd.mm.yyyy'), 0);
    sDiscContr := ',
            CASE
              WHEN I1.Cant = 0 THEN 0
              WHEN I.TipDoc IN (19,26) THEN COALESCE(pkg_contract_CALCULEAZA_DISCT_LINIE(I.TipDoc, I1.CodIes1, I.DataDoc::date),0) * L1.Cant /I1.Cant
              ELSE 0
            END cdisct,
            CASE
              WHEN I1.Cant = 0 THEN 0
              WHEN I.TipDoc IN (19,26) THEN (
                SELECT COALESCE(MAX(CASE WHEN T.DISCUNITAR &lt;&gt; 0 THEN l1.cant * t.discunitar ELSE l1.cant * (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)) * t.pjdisc / 100 END),0)
                FROM TMP_IESDISCC T
                WHERE T.PARTENER = I.PARTENER AND (T.LOCATIE = 0 OR T.LOCATIE = I.CODLOCATIE) AND T.SUBUNITATEA = I.SUBUNITATEA AND T.CODOBIECT = I1.CODOBIECT AND T.DATASTART &lt;= I.DATADOC AND T.DATASTOP &gt;= I.DATADOC )
              ELSE 0
            END cdiscc,
            CASE
              WHEN I1.Cant = 0 THEN 0
              WHEN I.TipDoc IN (19,26) THEN (
                SELECT COALESCE(MAX(l1.cant * (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)) *t.disc/t.baza),0)
                FROM TMP_IESDISCV T
                WHERE T.PARTENER = I.PARTENER AND (T.LOCATIE = 0 OR T.LOCATIE = I.CODLOCATIE) AND T.SUBUNITATEA = I.SUBUNITATEA AND (T.CODOBIECT = 0 OR T.CODOBIECT = I1.CODOBIECT) AND T.DATASTART &lt;= I.DATADOC AND T.DATASTOP &gt;= I.DATADOC )
              ELSE 0
            END cdiscv,
            CASE
              WHEN I1.Cant = 0 THEN 0
              WHEN I.TipDoc IN (19,26) THEN (SELECT pkg_contract_SIMCADOU_COD.wme_result FROM pkg_contract_SIMCADOU_COD(NULL, 2, I1.CodObiect, I.Partener, I.CodLocatie, I.Subunitatea, I.DataDoc::date))
              ELSE 0
            END cCodArtCad,
            CASE
              WHEN I1.Cant = 0 THEN 0
              WHEN I.TipDoc IN (19,26) THEN (SELECT pkg_contract_SIMCADOU_CANT.wme_result FROM pkg_contract_SIMCADOU_CANT(NULL, 2, I1.CodObiect, I.Partener, I.CodLocatie, I.Subunitatea, I.DataDoc::date, L1.Cant))
              ELSE 0
            END cCantArtCad,
            CASE
              WHEN In1.Cant = 0 THEN 0
              WHEN Intr.operat = 1 AND Intr.TipDoc IN (1,2,9) THEN COALESCE(pkg_contract_CALCULEAZA_DISCT_LINIE(Intr.TipDoc, In1.CodIntr1, Intr.DataDoc::date),0) * L1.Cant/In1.Cant
              ELSE 0
            END cdisctF,
            CASE
              WHEN In1.Cant = 0 THEN 0
              WHEN Intr.TipDoc IN (1,9) THEN (
                SELECT COALESCE(MAX( CASE WHEN T.DISCUNITAR &lt;&gt; 0 THEN l1.cant * t.discunitar ELSE l1.cant * in1.pu * t.pjdisc / 100 END),0)
                FROM TMP_INTRDISCC T
                WHERE T.PARTENER = Intr.PARTENER AND (T.LOCATIE = 0 OR T.LOCATIE = Intr.CODLOCATIE) AND T.SUBUNITATEA = Intr.SUBUNITATEA AND T.CODOBIECT = In1.CODOBIECT AND T.DATASTART &lt;= Intr.DATADOC AND T.DATASTOP &gt;= Intr.DATADOC )
              WHEN Intr.TipDoc = 2 THEN (
                SELECT
                  SUM(
                    l1.cant / in1.cant * (
                    SELECT COALESCE(MAX(CASE WHEN T.DISCUNITAR &lt;&gt; 0 THEN f1.cant * t.discunitar ELSE f1.cant * f1.pu * t.pjdisc / 100 END),0)
                    FROM TMP_INTRDISCC T
                    WHERE T.PARTENER = F.PARTENER AND (T.LOCATIE = 0 OR T.LOCATIE = F.CODLOCATIE) AND T.SUBUNITATEA = F.SUBUNITATEA AND T.CODOBIECT = F1.CODOBIECT AND T.DATASTART &lt;= F.DATADOC AND T.DATASTOP &gt;= F.DATADOC )
                  )
                FROM INTRLINK IL
                  INNER JOIN INTRARI1 F1 ON F1.Codintr1 = IL.CodIntr1
                  INNER JOIN INTRARI  F  ON F.Codintr   = F1.CodIntr
                WHERE IL.CODLINIEAVIZ = In1.CodIntr1)
              ELSE 0
            END cdisccF,
            CASE
              WHEN In1.Cant = 0 THEN 0
              WHEN Intr.TipDoc IN (1,9) THEN (
                SELECT COALESCE(MAX(l1.cant*in1.pu*t.disc/t.baza),0)
                FROM TMP_INTRDISCV T
                WHERE T.PARTENER = Intr.PARTENER AND (T.LOCATIE = 0 OR T.LOCATIE = Intr.CODLOCATIE) AND T.SUBUNITATEA = Intr.SUBUNITATEA AND (T.CODOBIECT = 0 OR T.CODOBIECT = In1.CODOBIECT) AND T.DATASTART &lt;= Intr.DATADOC AND T.DATASTOP &gt;= Intr.DATADOC )
              WHEN Intr.TipDoc = 2 THEN (
                SELECT
                  SUM(
                    l1.cant / in1.cant * (
                    SELECT COALESCE(MAX(f1.cant*f1.pu*t.disc/t.baza),0)
                    FROM TMP_INTRDISCV T
                    WHERE T.PARTENER = F.PARTENER AND (T.LOCATIE = 0 OR T.LOCATIE = F.CODLOCATIE) AND T.SUBUNITATEA = F.SUBUNITATEA AND (T.CODOBIECT = 0 OR T.CODOBIECT = F1.CODOBIECT) AND T.DATASTART &lt;= F.DATADOC AND T.DATASTOP &gt;= F.DATADOC )
                  )
                FROM INTRLINK IL
                  INNER JOIN INTRARI1 F1 ON F1.Codintr1 = IL.CodIntr1
                  INNER JOIN INTRARI  F  ON F.Codintr   = F1.CodIntr
                WHERE IL.CODLINIEAVIZ = In1.CodIntr1)
              ELSE 0
            END cdiscvf,
            CASE
              WHEN I1.Cant = 0 THEN 0
              WHEN I.TipDoc IN (1,9) THEN (SELECT pkg_contract_SIMCADOU_COD.wme_result FROM pkg_contract_SIMCADOU_COD(NULL, 1, In1.CodObiect, Intr.Partener, Intr.CodLocatie, Intr.Subunitatea, Intr.DataDoc::date))
              ELSE 0
            END cCodArtCadF,
            CASE
              WHEN I1.Cant = 0 THEN 0
              WHEN I.TipDoc IN (1,9) THEN (SELECT pkg_contract_SIMCADOU_CANT.wme_result FROM pkg_contract_SIMCADOU_CANT(NULL, 1, In1.CodObiect, Intr.Partener, Intr.CodLocatie, Intr.Subunitatea, Intr.DataDoc::date, L1.Cant))
              ELSE 0
            END cCantArtCadF';
  ELSE
    sDiscContr := sDiscContr0;
  END IF;

  sDiscNC0 := ',
            0 ncdisct,  0 ncdiscc,  0 ncdiscv,  NULL ncDenCad,  NULL ncUMCad,  NULL ncCantCad,  0 ncCantAsocCad,  0 ncZecCad,  0 ncPretCad,
            0 ncdisctf, 0 ncdisccf, 0 ncdiscvf, NULL ncDenCadF, NULL ncUMCadF, NULL ncCantCadF, 0 ncCantAsocCadF, 0 ncZecCadF, 0 ncPretCadF';

  IF current_setting('PKG_LIST_SELECTIEPROFIT.vExtra2', TRUE)::boolean THEN
    sJoinCadou := '
            LEFT JOIN (
              SELECT
                i1.codies1, o.denumire dencad, Sum(i1.cant) over (PARTITION BY ncc.codnccadouri) cantasoc,
                ncc.diferente/(CASE WHEN COALESCE(u1.paritate,0) = 0 THEN 1 ELSE u1.paritate END) cantcad, u1.den_um1 umcad, pm.lei * u1.paritate pretcad, COALESCE(u1.zecimale,7) zeccad
              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
            LEFT JOIN (
              SELECT
                i1.codintr1, o.denumire dencad, Sum(i1.cant) over (PARTITION BY ncc.codnccadouri) cantasoc,
                ncc.diferente/(CASE WHEN COALESCE(u1.paritate,0) = 0 THEN 1 ELSE u1.paritate END) cantcad, u1.den_um1 umcad, pm.lei * u1.paritate pretcad, COALESCE(u1.zecimale,7) zeccad
              FROM NCCADOURI NCC
                INNER JOIN NOTECREDIT  NC  ON NC.CODNCREDIT  = NCC.CODNCREDIT
                INNER JOIN NOTECREDIT1 NC1 ON NC1.CODNCREDIT = NCC.CODNCREDIT
                INNER JOIN INTRARI1    I1  ON NC1.CODDOC     = I1.CODINTR1 AND I1.CODOBIECT = NCC.CODOBIECTASOC
                INNER JOIN INTRARI     I   ON I.CODINTR      = I1.CODINTR  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 = 59
                AND NC1.TIPOPER = ''C''
            ) CadF ON cadf.codintr1 = in1.codintr1';
    sDiscNC := ',
            CASE
              WHEN COALESCE(I1.Cant,0) = 0 THEN 0
              WHEN I.TipDoc IN (19,26) THEN
                L1.Cant/I1.Cant*
                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 = I.TipDoc ),0)
              ELSE 0
            END ncdisct,
            CASE
              WHEN COALESCE(I1.Cant,0) = 0 THEN 0
              WHEN I.TipDoc IN (19,26) THEN
                L1.Cant/I1.Cant*
                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 = I.TipDoc ),0)
              ELSE 0
            END ncdiscc,
            CASE
              WHEN COALESCE(i1.cant,0) = 0 THEN 0
              WHEN COALESCE(i.valdoc,0) - COALESCE(i.tvadoc,0) = 0 THEN 0
              WHEN (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)) = 0 THEN 0
              WHEN I.TipDoc IN (19,26) THEN
                (SELECT pkg_notecredit_GetValDiscNCVol.wme_result FROM pkg_notecredit_GetValDiscNCVol(NULL, i1.codies1, l1.cant, i.codies, i.tipdoc, i1.cant, i1.pu, i1.tva, i1.addim, i1.coefdiscmaj, i1.valdiscpret, i.valdoc, i.tvadoc))
              ELSE 0
            END ncdiscv,
            cad.dencad ncDenCad, cad.umcad ncUMCad, cad.cantcad ncCantCad, cad.cantasoc ncCantAsocCad, cad.zeccad ncZecCad, cad.pretcad ncPretCad,
            CASE
              WHEN COALESCE(In1.Cant,0) = 0 THEN 0
              WHEN Intr.TipDoc IN (1,2,9)   THEN L1.Cant/In1.Cant*pkg_list_base_profit_getvalnc(ns.codintr1, 1)
              ELSE 0
            END ncdisctf,
            CASE
              WHEN COALESCE(In1.Cant,0) = 0 THEN 0
              WHEN Intr.TipDoc IN (1,2,9)   THEN L1.Cant/In1.Cant*pkg_list_base_profit_getvalnc(ns.codintr1, 3)
              ELSE 0
            END ncdisccf,
            CASE
              WHEN COALESCE(in1.cant,0) = 0 THEN 0
              WHEN COALESCE(intr.valdoc,0) - COALESCE(intr.tvadoc,0) = 0 THEN 0
              WHEN Intr.TipDoc = 1 THEN
                (select sum(l1.cant/inf1.cant*
                        COALESCE((
                          SELECT SUM(NC1.VALOARE)
                          FROM NOTECREDIT NC
                               INNER JOIN NOTECREDIT1 NC1 ON NC.CODNCREDIT  = NC1.CODNCREDIT
                               LEFT  JOIN CONTRACT    C   ON NC.CODCONTRACT = C.CODCONTRACT
                          WHERE ((NC.CODCONTRACT &gt; 0 AND COALESCE(C.TIPTARGETV,0) &lt; 2 AND NC.TIPDOC = 59 AND NC1.TIP = 2 AND NC1.CODDOC = Intrf.CodIntr AND NC1.TIPDOC = Intrf.TipDoc)
                                OR (NC.CODCONTRACT &gt; 0 AND COALESCE(C.TIPTARGETV,0) = 2 AND NC.TIPDOC = 59 AND NC1.TIP = 2 AND NC1.CODDOC = Inf1.CodIntr1 AND NC1.TIPDOC = Intrf.TipDoc)
                                OR (COALESCE(NC.CODCONTRACT,0) = 0 AND COALESCE(NC.VOLUMPEARTICOLE,0) = 0 AND NC.TIPDOC = 59 AND NC1.TIP = 2 AND NC1.CODDOC = Intrf.CodIntr AND NC1.TIPDOC = Intrf.TipDoc)
                                OR (COALESCE(NC.CODCONTRACT,0) = 0 AND NC.VOLUMPEARTICOLE = 1 AND NC.TIPDOC = 59 AND NC1.TIP = 2 AND NC1.CODDOC = Inf1.CodIntr1 AND NC1.TIPDOC = Intrf.TipDoc)
                                )
                           ),0))
                 from INTRARI1 INF1
                      INNER JOIN INTRARI INTRF ON INF1.CodIntr  = INTRF.CodIntr
                 where inf1.codintr1 = in1.codintr1
                )
              WHEN Intr.TipDoc IN (2,9) THEN
                l1.cant/ns.cantnir*(select sum(--l1.cant/COALESCE(INF1.CANT,in1.cant)*
                        COALESCE((
                          SELECT SUM(NC1.VALOARE)
                          FROM NOTECREDIT NC
                               INNER JOIN NOTECREDIT1 NC1 ON NC.CODNCREDIT  = NC1.CODNCREDIT
                               LEFT  JOIN CONTRACT    C   ON NC.CODCONTRACT = C.CODCONTRACT
                          WHERE ((NC.CODCONTRACT &gt; 0 AND COALESCE(C.TIPTARGETV,0) &lt; 2 AND NC.TIPDOC = 59 AND NC1.TIP = 2 AND NC1.CODDOC = COALESCE(INTRF.CODINTR,Intr.CodIntr) AND NC1.TIPDOC = COALESCE(INTRF.TIPDOC,Intr.TipDoc))
                                OR (NC.CODCONTRACT &gt; 0 AND COALESCE(C.TIPTARGETV,0) = 2 AND NC.TIPDOC = 59 AND NC1.TIP = 2 AND NC1.CODDOC = COALESCE(INF1.CODINTR1,In1.CodIntr1) AND NC1.TIPDOC = COALESCE(INTRF.TIPDOC,Intr.TipDoc))
                                OR (COALESCE(NC.CODCONTRACT,0) = 0 AND COALESCE(NC.VOLUMPEARTICOLE,0) = 0 AND NC.TIPDOC = 59 AND NC1.TIP = 2 AND NC1.CODDOC = COALESCE(INTRF.CODINTR,Intr.CodIntr) AND NC1.TIPDOC = COALESCE(INTRF.TIPDOC,Intr.TipDoc))
                                OR (COALESCE(NC.CODCONTRACT,0) = 0 AND NC.VOLUMPEARTICOLE = 1 AND NC.TIPDOC = 59 AND NC1.TIP = 2 AND NC1.CODDOC = COALESCE(INF1.CODINTR1,In1.CodIntr1) AND NC1.TIPDOC = COALESCE(INTRF.TIPDOC,Intr.TipDoc))
                                )
                           ),0))
                 from INTRARI1 INF1
                      INNER JOIN INTRARI INTRF ON INF1.CodIntr  = INTRF.CodIntr
                      INNER JOIN INTRLINK LNK  ON LNK.CODINTR1 = INF1.CODINTR1
                 where LNK.CODLINIEAVIZ = IN1.CODINTR1
                )
              ELSE 0
            END ncdiscvf,
            cadf.dencad ncDenCadF, cadf.umcad ncUMCadF, cadf.cantcad ncCantCadF, cadf.cantasoc ncCantAsocCadF, cadf.zeccad ncZecCadF, cadf.pretcad ncPretCadF';
  ELSE
    sDiscNC := sDiscNC0;
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(
        NAV_CodDoc, NAV_TipDoc, Articol, Cant, UM, PretFurn, PretAchiz, DiscIn, ProcDiscIn, PretClient, PretVanz, DiscVanz, ProcDiscVanz,
        Transport, PretRef, MonPretRef, Curs, UpLift, Client, ProfitUnitar, Doc, DocColet, DocTransport, Supliment, Subunitatea, PretMax, PretAchizC, PretInregC,
        Clasa, Agent, Producator, Judet, TerMedIes, TerMedIn, TipContLivr, ProcProfit, ADDIM, PROCTVA,
        DiscVol,   DiscTer,   DiscCant,   ArtCadou,   UMCadou,   PretCadou,
        DiscVolF,  DiscTerF,  DiscCantF,  ArtCadouF,  UMCadouF,  PretCadouF,
        CantCadou,
        CantCadouF,
        CDiscVol,  CDiscTer,  CDiscCant,  CArtCadou,  CUMCadou,  CCantCadou,  CPretCadou,
        CDiscVolF, CDiscTerF, CDiscCantF, CArtCadouF, CUMCadouF, CCantCadouF, CPretCadouF, CursDoc, CursRefAchiz, CursRefVanz,
        ContIOArt';

  FOR i in 1..coalesce(vMax::integer,0) loop
    sInsert := COALESCE(sInsert,'')||', CLS'||i::varchar;
  END LOOP;

  sInsert := coalesce(sInsert,'') || gUserFields || ') ';

  IF vDupaData THEN
    sCondI := '
            AND L.DataLivr ';
    IF vDataIni = vDataFin
    THEN sCondI := coalesce(sCondI,'') || '= To_Date(''' || vDataIni || ''',''dd.mm.yyyy'') ';
    ELSE sCondI := coalesce(sCondI,'') || 'BETWEEN To_Date(''' || vDataIni || ''',''dd.mm.yyyy'') AND To_Date(''' || vDataFin || ''',''dd.mm.yyyy'')';
    END IF;
    sCondT := sCondI;
  ELSE
    IF vDataIni = vDataFin
    THEN sCondI := '= ' || coalesce(vLunaAnIni, 0) || ' ';
    ELSE sCondI := 'BETWEEN ' || coalesce(vLunaAnIni, 0) || ' AND ' || coalesce(vLunaAnFin, 0) || ' ';
    END IF;
    sCondT := '
              AND (T.luna+T.an*12) ' || coalesce(sCondI,'');
    sCondI := '
              AND (I.luna+I.an*12) ' || coalesce(sCondI,'');
  END IF;

  sCondI := ' AND I.operat = 1 AND COALESCE(I.anulat, 0) = 0' || coalesce(sCondI,'') || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL)),'');
  sCondT := ' AND T.operat = 1 ' || coalesce(sCondT,'') || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'T',NULL,NULL,NULL)),'');

  IF NOT vToateGest THEN
    vCondGest := '
            AND COALESCE(n.gest, lv.gest)::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
  END IF;

  sWith := '
      WITH ';

  IF  COALESCE(vMax, 0) &gt; 0 THEN
    sWith := coalesce(sWith,'') || '
          Clase AS (
            SELECT codclasea ';
    IF  COALESCE(vMax, 0) &gt; 0 THEN
      for i in 1..coalesce(vMax::integer,0) loop
        sWith := COALESCE(sWith,'') ||',Max(CASE WHEN nivel = '||i::varchar||' THEN den_clasea ELSE '''' end) d'||i::varchar;
      end loop;
    END IF;
    swith := coalesce(sWith,'') || '
            FROM TMP_PROFIT_NCLASEA
            GROUP BY codclasea), ';
  END IF;

  sWithIni := sWith;
  sWith := coalesce(sWith,'') || '
        DISCFACTAVIZ as (
          SELECT SUM(COALESCE(F1.PRETORIG, 0)*(Case  When F.curs is NULL then 1 When F.curs=0 then 1 else F.curs end)*(1-COALESCE(F1.coefdiscmaj,1))) DISCOUNT, AV1.CODINTR1
          FROM INTRARI1 AV1
            INNER JOIN INTRARI AV  ON AV1.CODINTR    = AV.CODINTR
            INNER JOIN INTRLINK L  ON L.CODLINIEAVIZ = AV1.CODINTR1
            INNER JOIN INTRARI1 F1 ON L.CODINTR1     = F1.CODINTR1
            INNER JOIN INTRARI F   ON F1.CODINTR     = F.CODINTR
          WHERE AV.TIPDOC = 2 AND AV.ANULAT = 0 AND AV.OPERAT = 1 AND F.TIPDOC = 9 AND F.ANULAT = 0 AND F.OPERAT = 1
          GROUP BY AV1.CODINTR1),';
  sLG1 := '
        LG AS (
          SELECT
            L1.CODLIVR1, NSC.CODNIRSTOC, I.Curs, I.TipDoc, I1.CodObiect, P.Den_Part Client, I1.CoefDiscMaj, I1.PretOrig, IN1.ADDIM, I.Agent, I.Subunitatea, L1.cant / I1.Cant *COALESCE(I1.CostTransport, 0) Transport,
            I.DataDoc, I.NrDoc, I.PrefixDoc, I.An, I.Luna, I.CodIes CodDoc, I1.CodIes1 CodDoc1, L1.Cant, I1.Cant CantIes, In1.Cant CantIn, I1.UMSec,
            i1.pretorig  * (Case  When i.curs is NULL then 1 When i.curs=0 then 1 else i.curs end) PretClient, I1.PRETORIG * COALESCE(i1.coefdiscmaj,1) * (Case  When I.Curs is Null then 1 When I.Curs=0 then 1 else I.Curs end) PretVanz,
            (1-COALESCE(i1.coefdiscmaj,1)) * I1.PRETORIG * (Case  When i.curs is NULL then 1 When i.curs=0 then 1 else i.curs end) DiscVanz,
            (1-COALESCE(i1.coefdiscmaj,1)) * 100 ProcDiscVanz,
            CASE
              WHEN COALESCE(NS.CodNirStoc, 0) = 0 THEN COALESCE(LV.PretAchiz, 0)
              WHEN COALESCE(NS.CodIntr1, 0) &lt;&gt; 0 THEN
                CASE WHEN COALESCE(in1.pretorig,0) = 0 THEN COALESCE(NS.PRET - NS.ADAOS, LV.PRETACHIZ) ELSE COALESCE(in1.pretorig * (case when intr.curs is NULL then 1 when intr.curs = 0 then 1 else intr.curs end) * COALESCE(in1.coefdiscmaj,1), COALESCE(NS.PRET - NS.ADAOS, LV.PRETACHIZ)) END
                    + COALESCE(NS.SUPLIMENT/(Case  When COALESCE(NS.CANTNIR, 0)= 0 then  1 else NS.CANTNIR end)
                    - case when INTR.TIPDOC = 2 then COALESCE(discfactaviz.discount,0) else 0 end
                    , 0)
              WHEN COALESCE(NS.CodTransf1, 0) &lt;&gt; 0 THEN COALESCE(T1.PU, COALESCE(ns.pret - ns.adaos, LV.PRETACHIZ)) + COALESCE(NS.SUPLIMENT/(Case  When COALESCE(NS.CANTNIR, 0)= 0 then  1 else NS.CANTNIR end), 0)
              WHEN COALESCE(NS.CodDVI1, 0) &lt;&gt; 0 THEN COALESCE(DVI1.PretImport, COALESCE(NS.PRET - NS.ADAOS, LV.PRETACHIZ)) + COALESCE(NS.SUPLIMENT/(Case  When COALESCE(NS.CANTNIR, 0)= 0 then  1 else NS.CANTNIR end), 0)
            END PretAchiz,
            CASE
              WHEN COALESCE(NS.CodIntr1, 0) &lt;&gt; 0 THEN COALESCE(in1.pretorig*(Case  When intr.Curs is Null then 1 When intr.Curs=0 then 1 else intr.Curs end), COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0)))
              WHEN COALESCE(NS.CodTransf1, 0) &lt;&gt; 0 THEN COALESCE(T1.PU , COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0)))
              WHEN COALESCE(NS.CodDVI1, 0) &lt;&gt; 0 THEN COALESCE(DVI1.PretOriginal , COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0)))
            END PretFurn, NS.Furn,
            CASE
              WHEN COALESCE(NS.CodIntr1, 0) &lt;&gt; 0 AND INTR.TIPDOC &lt;&gt; 2 THEN COALESCE(IN1.PRETORIG, 0)*(Case  When intr.Curs is Null then 1 When intr.Curs=0 then 1 else intr.Curs end)*(1-COALESCE(in1.coefdiscmaj,1))
              WHEN COALESCE(NS.CodIntr1, 0) &lt;&gt; 0 AND INTR.TIPDOC = 2 THEN COALESCE(DISCFACTAVIZ.DISCOUNT,0)
              WHEN COALESCE(NS.CodTransf1, 0) &lt;&gt; 0 THEN 0
              WHEN COALESCE(NS.CodDVI1, 0) &lt;&gt; 0 THEN COALESCE(DVI1.PretOriginal,0)*(1-COALESCE(in1.coefdiscmaj,1))
            END ValDiscIntr,
            NS.SUPLIMENT/(Case  When COALESCE(NS.CANTNIR, 0)= 0 then  1 else NS.CANTNIR end) SUPLIMENT, COALESCE(NS.PUMaximal, 0) PretMax,
            COALESCE(nsc.pret - nsc.adaos, LV.PretAchiz) PretAchizC, COALESCE(nsc.pret, LV.PretInreg) PretInregC,
            PKG_LIST_BASE_PROFIT_GETTERIES(I.CodIes) TerMedIes,
            pkg_LIST_BASE_PROFIT_GETTERIN(INTR.CodIntr) TerMedIn,
            COALESCE(lv.codioart,nsc.codioart) codioart, I.CodLocatie CodAgenda, i1.codcentru, (CASE WHEN COALESCE(i.curs,1) = 0 THEN 1 ELSE COALESCE(i.curs,1) END) cursdoc,
            case when INTR.AN*12+INTR.LUNA &lt; (SELECT ANINITIAL*12+LUNAINITIALA FROM FIRMALUNI LIMIT 1 OFFSET 0) THEN NSC.CODGESTPROD ELSE INTR.CodGestProd END CODGESTPROD,
            (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.wme_result FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, fnc_GetValConstanta(''MonedaSitV'',COALESCE(intr.an,COALESCE(t.an, ies.an)), COALESCE(intr.luna,COALESCE(t.luna,ies.luna)))::NUMERIC,
                                                 fnc_GetValConstanta(''BancaSitV'',COALESCE(intr.an,COALESCE(t.an,ies.an)), COALESCE(intr.luna,COALESCE(t.luna,ies.luna)))::NUMERIC,
                                                 to_char(N.DataNIR, ''dd.mm.yyyy''))) CursRefAchiz,
            (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.wme_result FROM  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, fnc_GetValConstanta(''MonedaSitV'',I.An, I.Luna)::NUMERIC,
                                                 fnc_GetValConstanta(''BancaSitV'',I.An, I.Luna)::NUMERIC,
                                                 to_char(L.DataLivr, ''dd.mm.yyyy''))) CursRefVanz,G.CodGest' || coalesce(sDiscContr,'') || coalesce(sDiscNC,'') || '
          FROM IESIRI I
            INNER JOIN IESIRI1   I1 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
            LEFT  JOIN NIRSTOC  NSC ON L1.codnirstoc  = NSC.CodNIRStoc
            LEFT  JOIN NIRSTOC1 nsr ON nsr.codnirstoc = nsc.codnirstoc
            LEFT  JOIN NIRSTOC   NS ON NS.CodNIRStoc  = nsr.codnirstocOrig
            LEFT  JOIN NIR        N ON N.CodNIR       = NSC.CodNIR
            LEFT  JOIN IESIRI   IES ON IES.CODIES     = N.CODIES
            LEFT  JOIN NPART      P ON I.Partener     = P.CodPart
            LEFT  JOIN LIVRVAL   LV ON L1.CodLivr1    = LV.CodLivr1
            LEFT  JOIN NIR       NO ON NO.CodNIR      = NS.CodNIR
            LEFT  JOIN NGEST      G ON G.CodGest      = Coalesce(N.Gest,LV.Gest)
            LEFT  JOIN DVI1    DVI1 ON DVI1.CodDVI1   = NS.CodDVI1
            LEFT  JOIN INTRARI1 IN1 ON IN1.CodIntr1   = COALESCE(DVI1.CodIntr1,NS.CodIntr1)
            LEFT  JOIN DISCFACTAVIZ ON DISCFACTAVIZ.CODINTR1 = IN1.CODINTR1
            LEFT  JOIN INTRARI INTR ON IN1.CodIntr    = INTR.CodIntr
            LEFT  JOIN TRANSF1   T1 ON T1.CodTransf1  = NS.CodTransf1
            LEFT  JOIN TRANSF     T ON T1.CodTransf   = T.CodTransf' || coalesce(sJoinCadou,'') || '
          WHERE I.TipDoc IN (19, 21, 22) ' || coalesce(sCondI,'') || '
            AND L.codies IS NOT NULL AND L.operat = 1 AND COALESCE(L.anulat, 0) = 0
          AND I1.TipLinie = ''=''' || coalesce(vCondGest,'') || ')';
  sLG2 := '
        LG AS (
          SELECT
            L1.CODLIVR1, NSC.CODNIRSTOC, I.Curs, I.TipDoc, I1.CodObiect, P.Den_Part Client, I1.CoefDiscMaj, I1.PretOrig, IN1.ADDIM, I.Agent, I.Subunitatea, L1.Cant / I1.Cant * COALESCE(I1.CostTransport, 0) + L1.Cant / II1.Cant * COALESCE(II1.CostTransport, 0) Transport,
            I.DataDoc, I.NrDoc, I.PrefixDoc, I.An, I.Luna, I.CodIes CodDoc, I1.CodIes1 CodDoc1, round(L1.Cant*IL.Cant/II1.Cant, 7) Cant, I1.Cant CantIes, In1.Cant CantIn, I1.UMSec,
            i1.pretorig * (Case  When I.Curs is Null then 1 When I.Curs=0 then 1 else I.Curs end) PretClient, I1.PRETORIG * COALESCE(i1.coefdiscmaj,1) * (Case  When I.Curs is Null then 1 When I.Curs=0 then 1 else I.Curs end)
 PretVanz,
            (1-COALESCE(i1.coefdiscmaj,1)) * I1.PRETORIG * (Case  When I.Curs is Null then 1 When I.Curs=0 then 1 else I.Curs end) DiscVanz,
            (1-COALESCE(i1.coefdiscmaj,1)) * 100 ProcDiscVanz,
            CASE
              WHEN COALESCE(NS.CodNirStoc, 0) = 0 THEN COALESCE(LV.PretAchiz, 0)
              WHEN COALESCE(NS.CodIntr1, 0) &lt;&gt; 0 THEN CASE WHEN COALESCE(in1.pretorig,0) = 0 THEN COALESCE(NS.PRET - NS.ADAOS, LV.PRETACHIZ) ELSE COALESCE(in1.pretorig*(CASE WHEN intr.curs IS NULL THEN 1 WHEN INTR.CURS = 0 THEN 1 ELSE intr.curs END)*COALESCE(in1.coefdiscmaj,1), COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0))) + COALESCE(NS.SUPLIMENT/(CASE WHEN COALESCE(NS.CANTNIR, 0) = 0 THEN 1 ELSE NS.CANTNIR END), 0) END
              WHEN COALESCE(NS.CodTransf1, 0) &lt;&gt; 0 THEN COALESCE(T1.PU, COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0))) + COALESCE(NS.SUPLIMENT/(Case  When COALESCE(NS.CANTNIR, 0)= 0 then  1 else NS.CANTNIR end), 0)
              WHEN COALESCE(NS.CodDVI1, 0) &lt;&gt; 0 THEN COALESCE(DVI1.PretImport, COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0))) + COALESCE(NS.SUPLIMENT/(Case  When COALESCE(NS.CANTNIR, 0)= 0 then  1 else NS.CANTNIR end), 0)
            END PretAchiz,
            CASE
              WHEN COALESCE(NS.CodIntr1, 0) &lt;&gt; 0 THEN COALESCE(in1.pretorig*(Case  When intr.curs is NULL then 1 When intr.curs=0 then 1 else intr.curs end), COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0)))
              WHEN COALESCE(NS.CodTransf1, 0) &lt;&gt; 0 THEN COALESCE(T1.PU , COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0)))
              WHEN COALESCE(NS.CodDVI1, 0) &lt;&gt; 0 THEN COALESCE(DVI1.PretOriginal , COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0)))
            END PretFurn, NS.Furn,
            CASE
              WHEN COALESCE(NS.CodIntr1, 0) &lt;&gt; 0 AND INTR.TIPDOC &lt;&gt; 2 THEN COALESCE(IN1.PRETORIG, 0)*(Case  When intr.curs is NULL then 1 When intr.curs=0 then 1 else intr.curs end)*(1-COALESCE(in1.coefdiscmaj,1))
              WHEN COALESCE(NS.CodIntr1, 0) &lt;&gt; 0 AND INTR.TIPDOC = 2 THEN COALESCE(DISCFACTAVIZ.DISCOUNT,0)
              WHEN COALESCE(NS.CodTransf1, 0) &lt;&gt; 0 THEN 0
              WHEN COALESCE(NS.CodDVI1, 0) &lt;&gt; 0 THEN COALESCE(DVI1.PretOriginal,0)*(1-COALESCE(in1.coefdiscmaj,1))
            END ValDiscIntr,
            NS.SUPLIMENT/(Case  When COALESCE(NS.CANTNIR, 0)= 0 then  1 else NS.CANTNIR end) SUPLIMENT, COALESCE(NS.PUMaximal, 0) PretMax,
            COALESCE(nsc.pret - nsc.adaos, LV.PretAchiz) PretAchizC, COALESCE(nsc.pret, LV.PretInreg) PretInregC,
            pkg_LIST_BASE_PROFIT_GETTERIES(I.CodIes) TerMedIes,
            pkg_LIST_BASE_PROFIT_GETTERIN(INTR.CodIntr) TerMedIn,
            COALESCE(lv.codioart,nsc.codioart) codioart, I.CodLocatie CodAgenda, i1.codcentru, (CASE WHEN COALESCE(i.curs,1) = 0 THEN 1 ELSE COALESCE(i.curs,1) END) cursdoc,
            case when INTR.AN*12+INTR.LUNA &lt; (SELECT ANINITIAL*12+LUNAINITIALA FROM FIRMALUNI LIMIT 1 OFFSET 0) THEN NSC.CODGESTPROD ELSE INTR.CodGestProd END CODGESTPROD,
            (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.wme_result FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, fnc_GetValConstanta(''MonedaSitV'',COALESCE(intr.an,COALESCE(t.an, ies.an)), COALESCE(intr.luna,COALESCE(t.luna,ies.luna)))::NUMERIC,
                                                 fnc_GetValConstanta(''BancaSitV'',COALESCE(intr.an,COALESCE(t.an,ies.an)), COALESCE(intr.luna,COALESCE(t.luna,ies.luna)))::NUMERIC,
                                                 to_char(N.DataNIR, ''dd.mm.yyyy''))) CursRefAchiz,
            (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.wme_result FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, fnc_GetValConstanta(''MonedaSitV'',I.An, I.Luna)::NUMERIC,
                                                 fnc_GetValConstanta(''BancaSitV'', I.An, I.Luna)::NUMERIC,
                                                 to_char(L.DataLivr, ''dd.mm.yyyy''))) CursRefVanz,G.CodGest' || coalesce(sDiscContr,'') || coalesce(sDiscNC,'') || '
          FROM IESIRI I
            INNER JOIN IESIRI1   I1 ON I1.CodIes      = I.CodIes
            INNER JOIN IESLINK   IL ON I1.CodIes1     = IL.CodIes1
            INNER JOIN IESIRI1  II1 ON II1.CodIes1    = IL.CodLinieAviz
            INNER JOIN IESIRI    II ON II1.CodIes     = II.CodIes
            INNER JOIN LIVR       L ON II.CodIes      = L.CodIes
            INNER JOIN LIVR1     L1 ON II1.CodIes1    = L1.CodIes1 AND L1.CodLivr = L.CodLivr
            LEFT  JOIN LIVRVAL   LV ON L1.CodLivr1    = LV.CodLivr1
            LEFT  JOIN NIRSTOC  NSC ON L1.codnirstoc  = NSC.CodNIRStoc
            LEFT  JOIN NIR        N ON N.CodNIR       = NSC.CodNIR
            LEFT  JOIN NGEST      G ON G.CodGest      = COALESCE(N.Gest,LV.Gest)
            LEFT  JOIN NIRSTOC1 nsr ON nsr.codnirstoc = nsc.codnirstoc
            LEFT  JOIN NIRSTOC   NS ON NS.CodNIRStoc  = nsr.codnirstocOrig
            LEFT  JOIN NIR       NO ON NO.CodNIR      = NS.CodNIR
            LEFT  JOIN IESIRI   IES ON IES.CODIES     = NO.CODIES
            LEFT  JOIN NPART      P ON I.Partener     = P.CodPart
            LEFT  JOIN DVI1    DVI1 ON DVI1.CodDVI1   = NS.CodDVI1
            LEFT  JOIN INTRARI1 IN1 ON IN1.CodIntr1   = COALESCE(DVI1.CodIntr1,NS.CodIntr1)
            LEFT  JOIN INTRARI INTR ON IN1.CodIntr    = INTR.CodIntr
            LEFT  JOIN DISCFACTAVIZ ON DISCFACTAVIZ.CODINTR1 = IN1.CODINTR1
            LEFT  JOIN TRANSF1   T1 ON T1.CodTransf1  = NS.CodTransf1
            LEFT  JOIN TRANSF     T ON T1.CodTransf   = T.CodTransf' || coalesce(sJoinCadou,'') || '
          WHERE I.TipDoc = 26 ' || coalesce(sCondI,'') || '
            AND L.codies IS NOT NULL AND L.operat = 1 AND COALESCE(L.anulat, 0) = 0
            AND I1.TipLinie = ''=''' || coalesce(vCondGest,'') || ')';
  sLG2Ini := '
        LG AS (
          SELECT
            0 CODLIVR1, 0 CODNIRSTOC, I.Curs, I.TipDoc, I1.CodObiect, P.Den_Part Client, I1.CoefDiscMaj, I1.PretOrig, 0 ADDIM, I.Agent, I.Subunitatea, COALESCE(I1.CostTransport, 0) Transport,
            I.DataDoc, I.NrDoc, I.PrefixDoc, I.An, I.Luna, I.CodIes CodDoc, I1.CodIes1 CodDoc1, IL.Cant Cant, I1.Cant CantIes, 0 CantIn, I1.UMSec,
            i1.pretorig * (Case  When I.Curs is Null then 1 When I.Curs=0 then 1 else I.Curs end) PretClient, I1.PRETORIG * COALESCE(i1.coefdiscmaj,1) * (Case  When I.Curs is Null then 1 When I.Curs=0 then 1 else I.Curs end) PretVanz,
            (1-COALESCE(i1.coefdiscmaj,1)) * I1.PRETORIG * (Case  When I.Curs is Null then 1 When I.Curs=0 then 1 else I.Curs end) DiscVanz,
            (1-COALESCE(i1.coefdiscmaj,1)) * 100 ProcDiscVanz,
            II1.PUCORELAT PretAchiz,
            II1.PUCORELAT PretFurn, 0 Furn,
            0 ValDiscIntr,
            0 SUPLIMENT, 0 PretMax,
            II1.PUCORELAT PretAchizC, II1.PU PretInregC,
            pkg_LIST_BASE_PROFIT_GETTERIES(I.CodIes) TerMedIes,
            NULL::NUMERIC TerMedIn,
            II1.CODIOARTCUST codioart, I.CodLocatie CodAgenda, i1.codcentru, (CASE WHEN COALESCE(i.curs,1) = 0 THEN 1 ELSE COALESCE(i.curs,1) END) cursdoc,
            0 CODGESTPROD,
            1 CursRefAchiz,
            1 CursRefVanz, 0 CodGest' || coalesce(sDiscContr0,'') || coalesce(sDiscNC0,'') || '
          FROM IESIRI I
            INNER JOIN IESIRI1   I1 ON I1.CodIes      = I.CodIes
            INNER JOIN IESLINK   IL ON I1.CodIes1     = IL.CodIes1
            INNER JOIN IESIRI1  II1 ON II1.CodIes1    = IL.CodLinieAviz
            INNER JOIN IESIRI    II ON II1.CodIes     = II.CodIes
            LEFT  JOIN NPART      P ON I.Partener     = P.CodPart
          WHERE I.TipDoc = 26 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
            AND II.INITIALIZARI = 1 AND II.CUSTODIE = 1';

  IF vDupaData THEN
    sLG2Ini := coalesce(sLG2Ini,'') || '
            AND I.DataDoc ';
    IF vDataIni = vDataFin
    THEN sLG2Ini := coalesce(sLG2Ini,'') ||       '= To_Date(''' || vDataIni || ''',''dd.mm.yyyy'') ';
    ELSE sLG2Ini := coalesce(sLG2Ini,'') || 'BETWEEN To_Date(''' || vDataIni || ''',''dd.mm.yyyy'') AND To_Date(''' || vDataFin || ''',''dd.mm.yyyy'')';
    END IF;
  ELSE
    sLG2Ini := coalesce(sLG2Ini,'') || '
              AND (I.LUNA+I.AN*12) ';
    IF vDataIni = vDataFin
    THEN sLG2Ini := coalesce(sLG2Ini,'') || '= '       || coalesce(vLunaAnIni,0) || ' ';
    ELSE sLG2Ini := coalesce(sLG2Ini,'') || 'BETWEEN ' || coalesce(vLunaAnIni,0) || ' AND ' || coalesce(vLunaAnFin,0) || ' ';
    END IF;
  END IF;

  sLG2Ini := coalesce(sLG2Ini,'') || '
            AND I.operat = 1 AND COALESCE(I.anulat, 0) = 0' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
            AND I1.TipLinie = ''='')';
  sLG3 := '
        LG AS (
          SELECT
            L1.CODLIVR1, NSC.CODNIRSTOC, I.Curs, I.TipDoc, I1.CodObiect, S.Den_Subunit Client, I1.CoefDiscMaj, I1.PretOrig, IN1.ADDIM, I.Agent, I.Subunitatea,L1.Cant / I1.Cant * COALESCE(I1.CostTransport, 0) Transport,
            I.DataDoc,I.NrDoc, I.PrefixDoc, I.An, I.Luna, I.CodIes CodDoc, I1.CodIes1 CodDoc1, L1.Cant, I1.Cant CantIes, In1.Cant CantIn, I1.UMSec,
            i1.pretorig  * (Case  When I.Curs is Null then 1 When I.Curs=0 then 1 else I.Curs end) PretClient, I1.PRETORIG * COALESCE(i1.coefdiscmaj,1) * (Case  When I.Curs is Null then 1 When I.Curs=0 then 1 else I.Curs end) PretVanz,
            0 DiscVanz, 0 ProcDiscVanz,
            CASE
              WHEN COALESCE(NS.CodNirStoc, 0) = 0 THEN COALESCE(LV.PretAchiz, 0)
              WHEN COALESCE(NS.CodIntr1, 0) &lt;&gt; 0 THEN COALESCE(in1.pretorig*(Case  When intr.curs is NULL then 1 When intr.curs=0 then 1 else intr.curs end)*COALESCE(in1.coefdiscmaj,1), COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0))) + COALESCE(NS.SUPLIMENT/(Case  When COALESCE(NS.CANTNIR, 0)= 0 then  1 else NS.CANTNIR end), 0)
              WHEN COALESCE(NS.CodTransf1, 0) &lt;&gt; 0 THEN COALESCE(T1.PU, COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0))) + COALESCE(NS.SUPLIMENT/(Case  When COALESCE(NS.CANTNIR, 0)= 0 then  1 else NS.CANTNIR end), 0)
              WHEN COALESCE(NS.CodDVI1, 0) &lt;&gt; 0 THEN COALESCE(DVI1.PretImport, COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0))) + COALESCE(NS.SUPLIMENT/(Case  When COALESCE(NS.CANTNIR, 0)= 0 then  1 else NS.CANTNIR end), 0)
            END PretAchiz,
            CASE
              WHEN COALESCE(NS.CodIntr1, 0) &lt;&gt; 0 THEN COALESCE(in1.pretorig*(Case  When intr.curs is NULL then 1 When intr.curs=0 then 1 else intr.curs end) , COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0)))
              WHEN COALESCE(NS.CodTransf1, 0) &lt;&gt; 0 THEN COALESCE(T1.PU , COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0)))
              WHEN COALESCE(NS.CodDVI1, 0) &lt;&gt; 0 THEN COALESCE(DVI1.PretOriginal , COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0)))
            END PretFurn, NS.Furn,
            CASE
              WHEN COALESCE(NS.CodIntr1, 0) &lt;&gt; 0 AND INTR.TIPDOC &lt;&gt; 2 THEN COALESCE(IN1.PRETORIG, 0)*(Case  When intr.curs is NULL then 1 When intr.curs=0 then 1 else intr.curs end)*(1-COALESCE(in1.coefdiscmaj,1))
              WHEN COALESCE(NS.CodIntr1, 0) &lt;&gt; 0 THEN CASE WHEN COALESCE(in1.pretorig,0) = 0 THEN COALESCE(NS.PRET - NS.ADAOS, LV.PRETACHIZ) ELSE COALESCE(in1.pretorig*(CASE WHEN intr.curs IS NULL THEN 1 WHEN INTR.CURS = 0 THEN 1 ELSE intr.curs END)*COALESCE(in1.coefdiscmaj,1), COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0))) + COALESCE(NS.SUPLIMENT/(CASE WHEN COALESCE(NS.CANTNIR, 0) = 0 THEN 1 ELSE NS.CANTNIR END), 0) END
              WHEN COALESCE(NS.CodTransf1, 0) &lt;&gt; 0 THEN 0
              WHEN COALESCE(NS.CodDVI1, 0) &lt;&gt; 0 THEN COALESCE(DVI1.PretOriginal,0)*(1-COALESCE(in1.coefdiscmaj,1))
            END ValDiscIntr,
            NS.SUPLIMENT/(Case  When COALESCE(NS.CANTNIR, 0)= 0 then  1 else NS.CANTNIR end) SUPLIMENT, COALESCE(NS.PUMaximal, 0) PretMax,
            COALESCE(nsc.pret - nsc.adaos, LV.PretAchiz) PretAchizC, COALESCE(nsc.pret, LV.PretInreg) PretInregC,
            null::NUMERIC TerMedIes,
            pkg_LIST_BASE_PROFIT_GETTERIN(INTR.CodIntr) TerMedIn,
            COALESCE(lv.codioart,nsc.codioart) codioart, I.CodLocatie CodAgenda, i1.codcentru, (CASE WHEN COALESCE(i.curs,1) = 0 THEN 1 ELSE COALESCE(i.curs,1) END) cursdoc,
            case when INTR.AN*12+INTR.LUNA &lt; (SELECT ANINITIAL*12+LUNAINITIALA FROM FIRMALUNI LIMIT 1 OFFSET 0) THEN NSC.CODGESTPROD ELSE INTR.CodGestProd END CODGESTPROD,
            (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.wme_result FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, fnc_GetValConstanta(''MonedaSitV'',COALESCE(intr.an,COALESCE(t.an, ies.an)), COALESCE(intr.luna,COALESCE(t.luna,ies.luna)))::NUMERIC,
                                                 fnc_GetValConstanta(''BancaSitV'',COALESCE(intr.an,COALESCE(t.an,ies.an)), COALESCE(intr.luna,COALESCE(t.luna,ies.luna)))::NUMERIC,
                                                 to_char(N.DataNIR, ''dd.mm.yyyy''))) CursRefAchiz,
            (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.wme_result FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, fnc_GetValConstanta(''MonedaSitV'',I.An, I.Luna)::NUMERIC,
                                                 fnc_GetValConstanta(''BancaSitV'',I.An, I.Luna)::NUMERIC,
                                                 to_char(L.DataLivr, ''dd.mm.yyyy''))) CursRefVanz,G.CodGest' || coalesce(sDiscContr0,'') || coalesce(sDiscNC0,'') || '
          FROM IESIRI I
            INNER JOIN IESIRI1   I1 ON I1.CodIes      = I.CodIes
            INNER JOIN NSUBUNIT   S ON I.CodSubunit   = S.CodSubunit
            INNER JOIN LIVR       L ON I.CodIes       = L.CodIes
            INNER JOIN LIVR1     L1 ON I1.CodIes1     = L1.CodIes1 AND L1.CodLivr = L.CodLivr
            LEFT  JOIN LIVRVAL   LV ON L1.CodLivr1    = LV.CodLivr1
            LEFT  JOIN NIRSTOC  NSC ON L1.codnirstoc  = NSC.CodNIRStoc
            LEFT  JOIN NIR        N ON N.CodNIR       = NSC.CodNIR
            LEFT  JOIN NGEST      G ON G.CodGest      = COALESCE(N.Gest,LV.Gest)
            LEFT  JOIN NIRSTOC1 nsr ON nsr.codnirstoc = nsc.codnirstoc
            LEFT  JOIN NIRSTOC   NS ON NS.CodNIRStoc  = nsr.codnirstocOrig
            LEFT  JOIN NIR       NO ON NO.CodNIR      = NS.CodNIR
            LEFT  JOIN IESIRI   IES ON IES.CODIES     = NO.CODIES
            LEFT  JOIN DVI1    DVI1 ON DVI1.CodDVI1   = NS.CodDVI1
            LEFT  JOIN INTRARI1 IN1 ON NS.CodIntr1    = COALESCE(DVI1.CodIntr1,IN1.CodIntr1)
            LEFT  JOIN DISCFACTAVIZ ON DISCFACTAVIZ.CODINTR1 = IN1.CODINTR1
            LEFT  JOIN INTRARI INTR ON IN1.CodIntr    = INTR.CodIntr
            LEFT  JOIN TRANSF1   T1 ON T1.CodTransf1  = NS.CodTransf1
            LEFT  JOIN TRANSF     T ON T1.CodTransf   = T.CodTransf
          WHERE I.TipDoc = 23 ' || coalesce(sCondI,'') || '
            AND L.codies IS NOT NULL AND L.operat = 1 AND COALESCE(L.anulat, 0) = 0' || coalesce(vCondGest,'') || ')';
  sLG4 := '
        LG AS (
          SELECT
            L1.CODLIVR1, NSC.CODNIRSTOC, 1 Curs, T.TipDoc, T1.CodObiect, G.Den_gest Client, 0 CoefDiscMaj, NS.Pret PretOrig, IN1.ADDIM, 0 Agent, T.Subunitatea, L1.Cant / T1.Cant * COALESCE(T1.CostTransport, 0) Transport,
            T.DataDoc, T.NrDoc, T.PrefixDoc, T.An, T.Luna, T.CodTransf CodDoc, T1.CodTransf1 CodDoc1, T1.Cant, T1.Cant CantIes, IN1.Cant CantIn, T1.UMSec,
            NS.Pret PretClient, NS.Pret PretVanz,
            0 DiscVanz, 0 ProcDiscVanz,
            CASE
              WHEN COALESCE(NS.CodNirStoc, 0) = 0 THEN COALESCE(LV.PretAchiz, 0)
              WHEN COALESCE(NS.CodIntr1, 0) &lt;&gt; 0 THEN CASE WHEN COALESCE(in1.pretorig,0) = 0 THEN COALESCE(NS.PRET - NS.ADAOS, LV.PRETACHIZ) ELSE COALESCE(in1.pretorig*(CASE WHEN intr.curs IS NULL THEN 1 WHEN INTR.CURS = 0 THEN 1 ELSE intr.curs END)*COALESCE(in1.coefdiscmaj,1), COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0))) + COALESCE(NS.SUPLIMENT/(CASE WHEN COALESCE(NS.CANTNIR, 0) = 0 THEN 1 ELSE NS.CANTNIR END), 0) END
              WHEN COALESCE(NS.CodIntr1, 0) &lt;&gt; 0 THEN COALESCE(in1.pretorig*(Case  When intr.curs is NULL then 1 When intr.curs=0 then 1 else intr.curs end)*COALESCE(in1.coefdiscmaj,1), COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0))) + COALESCE(NS.SUPLIMENT/(Case  When COALESCE(NS.CANTNIR, 0)= 0 then  1 else NS.CANTNIR end), 0)
              WHEN COALESCE(NS.CodTransf1, 0) &lt;&gt; 0 THEN COALESCE(TI1.PU, COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0))) + COALESCE(NS.SUPLIMENT/(Case  When COALESCE(NS.CANTNIR, 0)= 0 then  1 else NS.CANTNIR end), 0)
              WHEN COALESCE(NS.CodDVI1, 0) &lt;&gt; 0 THEN COALESCE(DVI1.PretImport, COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0))) + COALESCE(NS.SUPLIMENT/(Case  When COALESCE(NS.CANTNIR, 0)= 0 then  1 else NS.CANTNIR end), 0)
            END PretAchiz,
            CASE
              WHEN COALESCE(LV.CodLivrVal, 0) &lt;&gt; 0 THEN COALESCE(LV.PretAchiz, 0)
              ELSE COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0)) + COALESCE(NS.SUPLIMENT/(Case  When COALESCE(NS.CANTNIR, 0)= 0 then  1 else NS.CANTNIR end), 0)
            END PretFurn, NS.Furn,
            CASE
              WHEN COALESCE(LV.CodLivrVal, 0) &lt;&gt; 0 THEN 0
              WHEN COALESCE(NS.CodIntr1, 0) &lt;&gt; 0 AND INTR.TIPDOC &lt;&gt; 2 THEN COALESCE(IN1.PRETORIG, 0)*(Case  When intr.curs is NULL then 1 When intr.curs=0 then 1 else intr.curs end)*(1-COALESCE(in1.coefdiscmaj,1))
              WHEN COALESCE(NS.CodIntr1, 0) &lt;&gt; 0 AND INTR.TIPDOC = 2 THEN COALESCE(DISCFACTAVIZ.DISCOUNT,0)
              WHEN COALESCE(NS.CodTransf1, 0) &lt;&gt; 0 THEN 0
              WHEN COALESCE(NS.CodDVI1, 0) &lt;&gt; 0 THEN COALESCE(DVI1.PretOriginal,0)*(1-COALESCE(in1.coefdiscmaj,1))
            END ValDiscIntr,
            NS.SUPLIMENT/(Case  When COALESCE(NS.CANTNIR, 0)= 0 then  1 else NS.CANTNIR end) SUPLIMENT, COALESCE(NS.PUMaximal, 0) PretMax,
            COALESCE(nsc.pret - nsc.adaos, LV.PretAchiz) PretAchizC, COALESCE(nsc.pret, LV.PretInreg) PretInregC,
            null::NUMERIC TerMedIes,
            pkg_LIST_BASE_PROFIT_GETTERIN(INTR.CodIntr) TerMedIn,
            COALESCE(lv.codioart,nsc.codioart) codioart, AG.CodAgenda, T1.codcentru, 1 cursdoc,
            case when INTR.AN*12+INTR.LUNA &lt; (SELECT ANINITIAL*12+LUNAINITIALA FROM FIRMALUNI LIMIT 1 OFFSET 0) THEN NSC.CODGESTPROD ELSE INTR.CodGestProd END CODGESTPROD,
            (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.wme_result FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, fnc_GetValConstanta(''MonedaSitV'',COALESCE(intr.an,COALESCE(t.an, ies.an)), COALESCE(intr.luna,COALESCE(t.luna,ies.luna)))::NUMERIC,
                                                 fnc_GetValConstanta(''BancaSitV'',COALESCE(intr.an,COALESCE(t.an,ies.an)), COALESCE(intr.luna,COALESCE(t.luna,ies.luna)))::NUMERIC,
                                                 to_char(N.DataNIR, ''dd.mm.yyyy''))) CursRefAchiz,
            (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.wme_result FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, fnc_GetValConstanta(''MonedaSitV'',T.An, T.Luna)::NUMERIC,
                                                 fnc_GetValConstanta(''BancaSitV'',T.An, T.Luna)::NUMERIC,
                                                 to_char(L.DataLivr, ''dd.mm.yyyy''))) CursRefVanz,G.CodGest' || coalesce(sDiscContr0,'') || coalesce(sDiscNC0,'') || '
          FROM TRANSF T
            INNER JOIN TRANSF1   T1 ON T1.CodTransf   = T.CodTransf
            INNER JOIN LIVR       L ON L.CodTransf    = T.CodTransf
            INNER JOIN LIVR1     L1 ON L1.CodIes1     = T1.CodTransf1 AND L1.CodLivr = L.CodLivr
            LEFT  JOIN LIVRVAL   LV ON L1.CodLivr1    = LV.CodLivr1
            LEFT  JOIN NIRSTOC  NSC ON L1.codnirstoc  = NSC.CodNIRStoc
            LEFT  JOIN NIR        N ON N.CodNIR       = NSC.CodNIR
            LEFT  JOIN NGEST      G ON G.CodGest      = COALESCE(N.Gest,LV.Gest)
            LEFT  JOIN NIRSTOC1 nsr ON nsr.codnirstoc = nsc.codnirstoc
            LEFT  JOIN NIRSTOC   NS ON NS.CodNIRStoc  = nsr.codnirstocOrig
            LEFT  JOIN NIR       NO ON NO.CodNIR      = NS.CodNIR
            LEFT  JOIN IESIRI   IES ON IES.CODIES     = NO.CODIES
            LEFT  JOIN DVI1    DVI1 ON DVI1.CodDVI1   = NS.CodDVI1
            LEFT  JOIN INTRARI1 IN1 ON IN1.CodIntr1   = COALESCE(DVI1.CodIntr1,NS.CodIntr1)
            LEFT  JOIN DISCFACTAVIZ ON DISCFACTAVIZ.CODINTR1 = IN1.CODINTR1
            LEFT  JOIN INTRARI INTR ON IN1.CodIntr    = INTR.CodIntr
            LEFT  JOIN TRANSF1  TI1 ON TI1.CodTransf1 = NS.CodTransf1
            LEFT  JOIN TRANSF    TI ON TI1.CodTransf  = TI.CodTransf
            LEFT  JOIN NAGENDA   AG ON AG.CodSubunit  = T.Subunitatea
          WHERE T.TipDoc = 12 ' || coalesce(sCondT,'') || '
            AND L.codies IS NOT NULL AND L.operat = 1 AND COALESCE(L.anulat, 0) = 0 ' || coalesce(vCondGest,'') || ')';
  sLGMon := '
        LG AS (
          SELECT
            L1.CODLIVR1, NSC.CODNIRSTOC, I.Curs, I.TipDoc, I1.CodObiect, P.Den_Part Client, I1.CoefDiscMaj, I1.PretOrig - i1.tva/i1.cant pretorig, IN1.ADDIM, I.Agent, I.Subunitatea, L1.cant / I1.Cant *COALESCE(I1.CostTransport, 0) Transport,
            I.DataDoc, I.NrDoc, I.PrefixDoc, I.An, I.Luna, I.CodIes CodDoc, I1.CodIes1 CodDoc1, L1.Cant, I1.Cant CantIes, In1.Cant CantIn, I1.UMSec,
            i1.pretorig PretClient, (I1.PRETORIG * COALESCE(i1.coefdiscmaj,1) - i1.tva/i1.cant) PretVanz,
            (1-COALESCE(i1.coefdiscmaj,1)) * I1.PRETORIG DiscVanz,
            (1-COALESCE(i1.coefdiscmaj,1)) * 100 ProcDiscVanz,
            CASE
              WHEN COALESCE(NS.CodNirStoc, 0) = 0 THEN COALESCE(LV.PretAchiz, 0)
              WHEN COALESCE(NS.CodIntr1, 0) &lt;&gt; 0 THEN
                    CASE WHEN COALESCE(in1.pretorig,0) = 0 THEN COALESCE(NS.PRET - NS.ADAOS, LV.PRETACHIZ) ELSE COALESCE(in1.pretorig * COALESCE(in1.coefdiscmaj,1), COALESCE(NS.PRET - NS.ADAOS, LV.PRETACHIZ)) END
                    + COALESCE(NS.SUPLIMENT/(Case  When COALESCE(NS.CANTNIR, 0)= 0 then  1 else NS.CANTNIR end)
                    - case when INTR.TIPDOC = 2 then COALESCE(discfactaviz.discount,0) else 0 end
                    , 0)
              WHEN COALESCE(NS.CodTransf1, 0) &lt;&gt; 0 THEN COALESCE(T1.PU, COALESCE(ns.pret - ns.adaos, LV.PRETACHIZ)) + COALESCE(NS.SUPLIMENT/(Case  When COALESCE(NS.CANTNIR, 0)= 0 then  1 else NS.CANTNIR end), 0)
              WHEN COALESCE(NS.CodDVI1, 0) &lt;&gt; 0 THEN COALESCE(DVI1.PretImport, COALESCE(NS.PRET - NS.ADAOS, LV.PRETACHIZ)) + COALESCE(NS.SUPLIMENT/(Case  When COALESCE(NS.CANTNIR, 0)= 0 then  1 else NS.CANTNIR end), 0)
            END PretAchiz,
            CASE
              WHEN COALESCE(NS.CodIntr1, 0) &lt;&gt; 0 THEN COALESCE(in1.pretorig, COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0)))
              WHEN COALESCE(NS.CodTransf1, 0) &lt;&gt; 0 THEN COALESCE(T1.PU , COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0)))
              WHEN COALESCE(NS.CodDVI1, 0) &lt;&gt; 0 THEN COALESCE(DVI1.PretOriginal , COALESCE(ns.pret - ns.adaos, COALESCE(LV.PretAchiz, 0)))
            END PretFurn, NS.Furn,
            CASE
              WHEN COALESCE(NS.CodIntr1, 0) &lt;&gt; 0 AND INTR.TIPDOC &lt;&gt; 2 THEN COALESCE(IN1.PRETORIG, 0)*(1-COALESCE(in1.coefdiscmaj,1))
              WHEN COALESCE(NS.CodIntr1, 0) &lt;&gt; 0 AND INTR.TIPDOC = 2 THEN COALESCE(DISCFACTAVIZ.DISCOUNT,0)
              WHEN COALESCE(NS.CodTransf1, 0) &lt;&gt; 0 THEN 0
              WHEN COALESCE(NS.CodDVI1, 0) &lt;&gt; 0 THEN COALESCE(DVI1.PretOriginal,0)*(1-COALESCE(in1.coefdiscmaj,1))
            END ValDiscIntr,
            NS.SUPLIMENT/(Case  When COALESCE(NS.CANTNIR, 0)= 0 then  1 else NS.CANTNIR end) SUPLIMENT, COALESCE(NS.PUMaximal, 0) PretMax,
            COALESCE(nsc.pret - nsc.adaos, LV.PretAchiz) PretAchizC, COALESCE(nsc.pret, LV.PretInreg) PretInregC,
            PKG_LIST_BASE_PROFIT_GETTERIES(I.CodIes) TerMedIes,
            pkg_LIST_BASE_PROFIT_GETTERIN(INTR.CodIntr) TerMedIn,
            COALESCE(lv.codioart,nsc.codioart) codioart, I.CodLocatie CodAgenda, i1.codcentru, (CASE when COALESCE(i.curs,1) = 0 THEN 1 ELSE COALESCE(i.curs,1) END) cursdoc,
            case when INTR.AN*12+INTR.LUNA &lt; (SELECT ANINITIAL*12+LUNAINITIALA FROM FIRMALUNI LIMIT 1 OFFSET 0) THEN NSC.CODGESTPROD ELSE INTR.CodGestProd END CODGESTPROD,
            (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.wme_result FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, fnc_GetValConstanta(''MonedaSitV'',COALESCE(intr.an,COALESCE(t.an, ies.an)), COALESCE(intr.luna,COALESCE(t.luna,ies.luna)))::NUMERIC,
                                                 fnc_GetValConstanta(''BancaSitV'',COALESCE(intr.an,COALESCE(t.an,ies.an)), COALESCE(intr.luna,COALESCE(t.luna,ies.luna)))::NUMERIC,
                                                 to_char(N.DataNIR, ''dd.mm.yyyy''))) CursRefAchiz,
            (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.wme_result FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, fnc_GetValConstanta(''MonedaSitV'',I.An, I.Luna)::NUMERIC,
                                                 fnc_GetValConstanta(''BancaSitV'',I.An, I.Luna)::NUMERIC,
                                                 to_char(L.DataLivr, ''dd.mm.yyyy''))) CursRefVanz,G.CodGest' || coalesce(sDiscContr0,'') || coalesce(sDiscNC0,'') || '
          FROM IESIRI I
            INNER JOIN IESIRI1   I1 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
            LEFT  JOIN NIRSTOC  NSC ON L1.codnirstoc  = NSC.CodNIRStoc
            LEFT  JOIN NIRSTOC1 nsr ON nsr.codnirstoc = nsc.codnirstoc
            LEFT  JOIN NIRSTOC   NS ON NS.CodNIRStoc  = nsr.codnirstocOrig
            LEFT  JOIN NIR        N ON N.CodNIR       = NS.CodNIR
            LEFT  JOIN IESIRI   IES ON IES.CODIES     = N.CODIES
            LEFT  JOIN NPART      P ON I.Partener     = P.CodPart
            LEFT  JOIN LIVRVAL   LV ON L1.CodLivr1    = LV.CodLivr1
            LEFT  JOIN NIR       NN ON NN.CodNIR      = NSC.CodNIR
            LEFT  JOIN NGEST      G ON G.CodGest      = COALESCE(NN.Gest,LV.Gest)
            LEFT  JOIN DVI1    DVI1 ON DVI1.CodDVI1   = NS.CodDVI1
            LEFT  JOIN INTRARI1 IN1 ON IN1.CodIntr1   = COALESCE(DVI1.CodIntr1,NS.CodIntr1)
            LEFT  JOIN DISCFACTAVIZ ON DISCFACTAVIZ.CODINTR1 = IN1.CODINTR1
            LEFT  JOIN INTRARI INTR ON IN1.CodIntr    = INTR.CodIntr
            LEFT  JOIN TRANSF1   T1 ON T1.CodTransf1  = NS.CodTransf1
            LEFT  JOIN TRANSF     T ON T1.CodTransf   = T.CodTransf' || coalesce(sJoinCadou,'') || '
          WHERE I.TipDoc = 16 ' || coalesce(sCondI,'') || '
            AND L.codies IS NOT NULL AND L.operat = 1 AND COALESCE(L.anulat, 0) = 0 and COALESCE(i1.cant,0) &lt;&gt; 0
            AND I1.TipLinie = ''=''' || coalesce(vCondGest,'') || ')';
  sSelect := '
      SELECT
        LG.CodDoc, LG.TipDoc, OBJ.Denumire, LG.Cant, UM1.Den_Um1, COALESCE(LG.PretFurn, 0), case when lg.coefdiscmaj = 0 then 0 else COALESCE(LG.PretAchiz, 0) end, COALESCE(LG.ValDiscIntr, 0) DiscIn,
        COALESCE(LG.ValDiscIntr, 0) / (CASE WHEN COALESCE(LG.PretAchiz, 0) = 0 THEN 1 ELSE  COALESCE(LG.PRETAchiz, 0) END) * 100 ProcDiscIn,
        LG.PretClient, LG.PretVanz, LG.DiscVanz, LG.ProcDiscVanz, LG.Transport, COALESCE(NO1.PretReferinta, 0) PretRef, MONREF.Simbol MonPretRef,
        (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.wme_result FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, NO1.CodMoneda::numeric, fnc_getvalconstanta(''BancaSitV'',LG.An, LG.Luna)::numeric, to_char(LG.datadoc, ''dd.mm.yyyy''))) Curs,
        COALESCE(NO1.UpLift, 0) UpLift, LG.Client,
        CASE
          WHEN LG.CANT = 0 THEN 0
          WHEN LG.TipDoc &lt;&gt; 12 THEN COALESCE((LG.pretorig * COALESCE(lg.coefdiscmaj,1) * COALESCE(LG.Curs, 1)) - LG.PretAchiz  - COALESCE(LG.Transport, 0) / LG.Cant, 0)
          ELSE COALESCE(LG.Pretorig - LG.PretAchiz  - COALESCE(LG.Transport, 0) / LG.Cant, 0)
        END ProfitUnitar,
        LG.PrefixDoc||''-''||LG.NrDoc||''/''||to_char(LG.DataDoc,''dd.mm.yyyy'') Doc,
        CASE
          WHEN COALESCE(C.CodPachete, 0) &gt; 0 THEN C.NrDoc||''/''||To_Char(C.DataP, ''dd.mm.yyyy'')
          ELSE null
        END DocColet,
        CASE
          WHEN COALESCE(T.CodTransport, 0) &gt; 0 THEN T.Indicativ||''/''||to_char(T.DataTransport,''dd.mm.yyyy'')
          ELSE null
        END DocTransport,
        COALESCE(LG.Supliment,0) Supliment, SUB.Den_Subunit, LG.PretMax, LG.PretAchizC, LG.PretInregC, CLASAA.Den_ClaseA,
        NP.Nume||'' ''||NP.Prenume, COALESCE(GPROD.Den_Gest, PROD.Den_Part) Producator, CASE WHEN NOT LG.TipDoc IN (12,23) THEN J.Den_Judet END Den_Judet,
        LG.TerMedIes, LG.TerMedIn, io.den_ioart,
        CASE
          WHEN LG.PretAchiz = 0 THEN 0
          WHEN LG.TipDoc &lt;&gt; 12 THEN COALESCE((LG.pretorig * COALESCE(lg.coefdiscmaj,1) * COALESCE(LG.Curs, 1)) - LG.PretAchiz  - COALESCE(LG.Transport, 0), 0)/(CASE WHEN COALESCE(LG.PretAchiz, 0) =  0 THEN 1 ELSE COALESCE(LG.PRETAchiz, 0) END) * 100
          ELSE COALESCE(LG.Pretorig - LG.PretAchiz  - COALESCE(LG.Transport, 0), 0)/(CASE WHEN COALESCE(LG.PretAchiz, 0) = 0 THEN 1 ELSE COALESCE(LG.PRETAchiz, 0) END)*100
        END ProcProfit,
        LG.ADDIM, NT1.PROCENT,
        lg.ncdiscv , lg.ncdisct , lg.ncdiscc , lg.ncdenCad,  lg.ncumCad,  lg.ncPretCad,
        lg.ncdiscvF, lg.ncdisctF, lg.ncdisccF, lg.ncdencadF, lg.ncumcadF, lg.ncpretcadF,
        CASE
          WHEN COALESCE(lg.ncCantAsocCad,0) = 0 THEN 0
          WHEN lg.cant = lg.ncCantAsocCad THEN lg.ncCantCad::numeric
          ELSE Round(lg.ncCantCad::numeric*lg.cant/lg.ncCantAsocCad,lg.ncZecCad::integer)
        END,
        CASE
          WHEN COALESCE(lg.ncCantAsocCadF,0) = 0 THEN 0
          WHEN lg.cant = lg.ncCantAsocCadF THEN lg.ncCantCadF::numeric
          ELSE Round(lg.ncCantCadF::numeric*lg.cant/lg.ncCantAsocCadF,lg.ncZecCadF::integer)
        END,
        lg.cdiscv , lg.cdisct , lg.cdiscc , cad.denumire,  ucad.den_um , lg.cCantArtCad , pcad.lei,
        lg.cdiscvF, lg.cdisctF, lg.cdisccF, cadF.denumire, ucadF.den_um, lg.cCantArtCadF, pcadF.lei, LG.CursDoc, LG.CursRefAchiz, LG.CursRefVanz, CIO.SIMBOL ';

  FOR i in 1..coalesce(vMax::integer,0) loop
    sSelect := COALESCE(sSelect,'')||', CLSC.D'||i::varchar;
  END loop;

  sSelect := coalesce(sSelect,'') || gUserAlias || '
      FROM LG
        LEFT JOIN NIRSTOC           NS ON NS.CODNIRSTOC     = LG.CODNIRSTOC
        LEFT JOIN LIVR1             L1 ON L1.CODLIVR1       = LG.CODLIVR1
        LEFT JOIN NARTOBJ          OBJ ON LG.Codobiect      = OBJ.CodObiect
        LEFT JOIN NART             ART ON OBJ.CodArticol    = ART.CodArticol
        LEFT JOIN NUM1             UM1 ON LG.UMSec          = UM1.Codum1
        LEFT JOIN IOART             IO ON IO.CODIOART       = LG.CODIOART
        LEFT JOIN NCLASEA       CLASAA ON ART.Clasa         = CLASAA.CodClaseA
        LEFT JOIN NPART           PROD ON OBJ.CodProducator = PROD.CodPart
        LEFT JOIN NGEST          GPROD ON GPROD.Codgest     = LG.CodGestProd
        LEFT JOIN PACHETE1          C1 ON LG.CodDoc         = C1.CodDoc AND LG.TipDoc = C1.Tipdoc
        LEFT JOIN PACHETE            C ON C1.CodPachete     = C.Codpachete
        LEFT JOIN TRANSPORT1        T1 ON LG.CodDoc         = T1.CodDoc AND LG.TipDoc = T1.Tipdoc
        LEFT JOIN TRANSPORT          T ON T1.CodTransport   = T.CodTransport
        LEFT JOIN NARTOBJ1         NO1 ON NO1.CodObiect     = LG.CodObiect   AND LG.An*12+LG.Luna BETWEEN NO1.ALStart AND NO1.ALStop
        LEFT JOIN NART1            NA1 ON NA1.CodArticol    = OBJ.CodArticol AND LG.An*12+LG.Luna BETWEEN NA1.ALStart AND NA1.ALStop
        LEFT JOIN NTVA1            NT1 ON NT1.CodTVA        = NA1.CodTVA     AND LG.An*12+LG.Luna BETWEEN NT1.ALStart AND NT1.ALStop
        LEFT JOIN IOART1           IO1 ON IO1.CODIOART      = LG.CODIOART    AND LG.An*12+LG.Luna BETWEEN IO1.ALStart AND IO1.ALStop
        LEFT JOIN NMONEDE       MONREF ON MONREF.CodMoneda  = COALESCE(NO1.CodMoneda, 0)
        LEFT JOIN NSUBUNIT         SUB ON LG.Subunitatea    = SUB.CodSubunit
        LEFT JOIN NPERS             NP ON LG.Agent          = NP.CodPers
        LEFT JOIN NAGENDA          SED ON SED.CodAgenda     = LG.CodAgenda
        LEFT JOIN NLOCALIT         LOC ON LOC.CodLocalit    = SED.CodLocalit
        LEFT JOIN NJUDET             J ON J.CodJudet        = LOC.CodJudet
        LEFT JOIN CENTRECOST        CC ON LG.CodCentru      = CC.CodCentru
        LEFT JOIN NARTOBJ          CAD ON CAD.CODOBIECT     = LG.cCodArtCad
        LEFT JOIN NART            ACAD ON ACAD.CODARTICOL   = CAD.CodArticol
        LEFT JOIN NUM             UCAD ON UCAD.CODUM        = ACAD.UM
        LEFT JOIN PRETM           PCAD ON PCAD.CODOBIECT    = LG.cCodArtCad AND PCAD.IMPLICIT = 1 AND PCAD.SUBUNITATEA = LG.Subunitatea
        LEFT JOIN NARTOBJ         CADF ON CADF.CODOBIECT    = LG.cCodArtCadF
        LEFT JOIN NART           ACADF ON ACADF.CODARTICOL  = CADF.CodArticol
        LEFT JOIN NUM            UCADF ON UCADF.CODUM       = ACADF.UM
        LEFT JOIN PRETM          PCADF ON PCADF.CODOBIECT   = LG.cCodArtCadF AND PCADF.IMPLICIT = 1 AND PCADF.SUBUNITATEA = LG.Subunitatea
        LEFT JOIN NCONT            CIO ON CIO.CODCONT       = IO1.CONT ' || gSuplJoins;

  IF  COALESCE(vMax, 0) &gt; 0 THEN
    sSelect := coalesce(sSelect,'') || '
        LEFT  JOIN CLASE          CLSC ON CLSC.CodClasea    = ART.Clasa ';
  END IF;

  CALL PRC_AL_CHECK('NARTOBJ1');
  CALL PRC_AL_CHECK('NART1');
  CALL PRC_AL_CHECK('NTVA1');
  CALL PRC_AL_CHECK('IOART1');

  IF vFactInt THEN
  --INSERT INTO x (view_name, test) VALUES ('sLG1',coalesce(sInsert,'') || coalesce(sWith,'') || coalesce(sLG1,'') || coalesce(sSelect,''));
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sWith,'') || coalesce(sLG1,'') || coalesce(sSelect,''), aListID, aListVer);
  END IF;

  IF vFactAviz THEN
    --INSERT INTO x (view_name, test) VALUES ('sLG2',coalesce(sInsert,'') || coalesce(sWith,'') || coalesce(sLG2,'') || coalesce(sSelect,''));
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sWith,'') || coalesce(sLG2,'') || coalesce(sSelect,''), aListID, aListVer);
    --INSERT INTO x (view_name, test) VALUES ('sLG2Ini',coalesce(sInsert,'') || coalesce(sWith,'') || coalesce(sLG2Ini,'') || coalesce(sSelect,''));
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sWithIni,'') || coalesce(sLG2Ini,'') || coalesce(sSelect,''), aListID, aListVer);
  END IF;

  IF vSubunit THEN
    --INSERT INTO x (view_name, test) VALUES ('sLG3',coalesce(sInsert,'') || coalesce(sWith,'') || coalesce(sLG3,'') || coalesce(sSelect,''));
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sWith,'') || coalesce(sLG3,'') || coalesce(sSelect,''), aListID, aListVer);
  END IF;

  IF vTransf THEN
    --INSERT INTO x (view_name, test) VALUES ('sLG4',coalesce(sInsert,'') || coalesce(sWith,'') || coalesce(sLG4,'') || coalesce(sSelect,''));
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sWith,'') || coalesce(sLG4,'') || coalesce(sSelect,''), aListID, aListVer);
  END IF;

  IF vMon THEN
    --INSERT INTO x (view_name, test) VALUES ('sLGMon',coalesce(sInsert,'') || coalesce(sWith,'') || coalesce(sLGMon,'') || coalesce(sSelect,''));
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sWith,'') || coalesce(sLGMon,'') || coalesce(sSelect,''), aListID, aListVer);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_proglunfab_processlist</obj_name>
  <obj_hashval>7661e2bc940905a3a46a33bbb5971025</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_proglunfab_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar := '';
  sWith       varchar := '';
  sSelect     varchar := '';
  sCondNeop   varchar := '';
  gSuplCols   varchar := '';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Adina 11.01.2021 tichet 42112
  --Florin 14.09.2020
  IF NOT current_setting('PKG_LIST_BASE_PROGLUNFAB.vCentralizare', true)::boolean THEN
    gSuplCols := 'PRODCOMP PC, COMANDA C, COMANDA1 C1, NARTOBJ PRODUS, NARTOBJ COMPONENT, FORMATII FORMATII, num umcomponent';
  ELSE
    gSuplCols := 'PRODCOMP PC, COMANDA C, COMANDA1 C1, NARTOBJ PRODUS, FORMATII FORMATII';
  END IF;

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXTP' , 'OEXTP.CODOBIECT = PRODUS.CODOBIECT'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATRP' , 'OATRP.CODOBIECT = PRODUS.CODOBIECT'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXTC' , 'OEXTC.CODOBIECT = COMPONENT.CODOBIECT'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATRC' , 'OATRC.CODOBIECT = COMPONENT.CODOBIECT'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDC'   , 'CCEXT' , 'CCEXT.CODCOMANDA = COMCLI.CODCOMANDA'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDC1'  , 'CC1EXT', 'CC1EXT.CODCOMANDA1 = COMCLI.CODCOMANDA1',NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('pkg_list_base_proglunfab.gSuplCols', gSuplCols, FALSE);

  IF NOT current_setting('PKG_LIST_BASE_PROGLUNFAB.vNeoperate', true)::boolean THEN
    sCondNeop := ' and c.operat = 1 ';
  END IF;

  IF current_setting('PKG_LIST_BASE_PROGLUNFAB.vLunar', true)::boolean THEN
    DELETE FROM tmp_comcli;

    sWith := 'insert into tmp_comcli(CODCOMANDA1,CARNETDOCCLI,NRDOCCLI,DATADOCCLI,SERIEDOCCLI,CLIENT,TERMENLIVR,COMCLOSED,COMCANCELED,CODCOMANDA,CODCOMANDA1C)' || coalesce(chr(13),'') ||
    'with recursive tmp(codcmdint1, codcmdcli1) as
    (SELECT ci1.codcomanda1 codcmdint1,
            cc1.codcomanda1 codcmdcli1
     from
           comanda1 ci1
           inner join comanda  ci  on ci1.codcomanda    = ci.codcomanda
           inner join cmdlink  l   on l.codcomanda1     = ci1.codcomanda1
           inner join comanda1 cc1 on l.codliniecomanda = cc1.codcomanda1
           inner join comanda  cc  on cc1.codcomanda    = cc.codcomanda
     where cc.tipdoc = 18 and ci.tipdoc = 53
           and ci.an*12+ci.luna &lt;= getanlucru()*12+getlunalucru() and l.codcomanda1 = ci1.CodComanda1 '|| PKG_LIST_BASE_UTILS_COND_SUBUNIT('CI','SUBUNITATEA',NULL,NULL)|| '
     UNION ALL
     select ci1.codcomanda1 codcmdint1,
            cc1.codcomanda1 codcmdcli1
     from comanda1 ci1 inner join tmp t ON t.codcmdint1 = codcmdint1
          inner join comanda  ci  on ci1.codcomanda    = ci.codcomanda
          inner join cmdlink  l   on l.codcomanda1     = ci1.codcomanda1
          inner join comanda1 cc1 on l.codliniecomanda = cc1.codcomanda1
          inner join comanda  cc  on cc1.codcomanda    = cc.codcomanda
     where cc.tipdoc = 18 and ci.tipdoc = 53
           and ci.an*12+ci.luna &lt;= getanlucru()*12+getlunalucru() and l.codcomanda1 = cc1.codcomanda1 '|| PKG_LIST_BASE_UTILS_COND_SUBUNIT('CI','SUBUNITATEA',NULL,NULL)|| ')'
    || 'SELECT '                                                          || coalesce(chr(13),'') ||
    '  cli.CodCmdInt1 codcomanda1, '                                      || coalesce(chr(13),'') ||
    '  doc.simbol CarnetDocCli, '                                         || coalesce(chr(13),'') ||
    '  cc.NrDoc NrDocCli, '                                               || coalesce(chr(13),'') ||
    '  cc.DataDoc DataDocCli, '                                           || coalesce(chr(13),'') ||
    '  doc.serie SerieDocCli, '                                           || coalesce(chr(13),'') ||
    '  P.den_part client, '                                               || coalesce(chr(13),'') ||
    '  cc1.Termen TermenLivr, '                                           || coalesce(chr(13),'') ||
    '  case when cc.inchisa = 1 then ''DA'' else ''NU'' end ComClosed, '  || coalesce(chr(13),'') ||
    '  case when cc.anulat = 1 then ''DA'' else ''NU'' end ComCanceled, ' || coalesce(chr(13),'') ||
    '  cc.codcomanda,CLI.CODCMDCLI1 '                                     || coalesce(chr(13),'') ||
    'FROM '                                                               || coalesce(chr(13),'') ||
    '  tmp cli'                                                           || coalesce(chr(13),'') ||
    '  inner join comanda1 cc1 on cli.codcmdcli1 = cc1.codcomanda1 '      || coalesce(chr(13),'') ||
    '  inner join comanda cc on cc1.codcomanda = cc.codcomanda '          || coalesce(chr(13),'') ||
    '  inner join npart p on cc.partener = p.codpart
                  left join doccarnete doc on cc.carnetdoc = doc.codcarnet ';
    PERFORM LIST_EXECUTE_IMMEDIATE(sWith, aListID, aListVer);

    IF NOT current_setting('PKG_LIST_BASE_PROGLUNFAB.vCentralizare', true)::boolean THEN
      sInsert := 'INSERT INTO ' || 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,
                                      Component,
                                      CantComp,
                                      UMComp,
                                      Schimb,
                                      Formatie,
                                      GestImp,
                                      Facturat,
                                      FNrDoc,
                                      FDataDoc,
                                      ComClosed,
                                      Subunitate,
                                      CmdSubSerie,
                                      CmdSubNrDoc,
                                      CmdSubDataDoc,
                                      Saptamana,
                                      ComCanceled,
                                      ComCliClosed,
                                      ComCliCanceled,
                                      ComCliOperata ' || gUserFields || ')';
      sWith := 'WITH ';
      sWith := sWith || 'ComProd as ('                                                      || coalesce(chr(13),'') ||
      'select '                                                                             || coalesce(chr(13),'') ||
      '  c.CodComanda, '                                                                    || coalesce(chr(13),'') ||
      '  c.TipDoc, '                                                                        || coalesce(chr(13),'') ||
      '  c1.CodComanda1, '                                                                  || coalesce(chr(13),'') ||
      '  mat.CodCmdProdMat, '                                                               || coalesce(chr(13),'') ||
      '  doc.simbol CarnetDocProd, '                                                        || coalesce(chr(13),'') ||
      '  c.NrDoc NrDocProd, '                                                               || coalesce(chr(13),'') ||
      '  c.DataDoc DataDocProd, '                                                           || coalesce(chr(13),'') ||
      '  doc.serie SerieDocProd, '                                                          || coalesce(chr(13),'') ||
      '  obj.denumire produs, '                                                             || coalesce(chr(13),'') ||
      '  obj.codobiect codprodus, '                                                         || coalesce(chr(13),'') ||
      '  ret.obs Reteta, '                                                                  || coalesce(chr(13),'') ||
      '  c1.Termen TermenExec, '                                                            || coalesce(chr(13),'') ||
      '  num1.den_um1 DenUM, '                                                              || coalesce(chr(13),'') ||
      '  mat.Cant CantLansata, '                                                            || coalesce(chr(13),'') ||
      '  mat.Pret PretLansat, '                                                             || coalesce(chr(13),'') ||
      '  mat.Cant*mat.Pret ValLansata, '                                                    || coalesce(chr(13),'') ||
      '  mat.Cant - mat.Rest CantRealiz, '                                                  || coalesce(chr(13),'') ||
      '  (mat.Cant - mat.Rest)*mat.Pret ValRealiz, '                                        || coalesce(chr(13),'') ||
      '  mat.Rest DifCant, '                                                                || coalesce(chr(13),'') ||
      '  mat.Rest*mat.Pret DifVal, '                                                        || coalesce(chr(13),'') ||
      '  G.Den_gest Sectie, '                                                               || coalesce(chr(13),'') ||
      '  objc.denumire component, '                                                         || coalesce(chr(13),'') ||
      '  objc.codobiect codcomponent, '                                                     || coalesce(chr(13),'') ||
      '  c.CodFormatie, '                                                                   || coalesce(chr(13),'') ||
      '  COALESCE(c.schimb, 0) schimb, '                                                    || coalesce(chr(13),'') ||
      '  matc.cant CantComp, '                                                              || coalesce(chr(13),'') ||
      '  case when c.inchisa = 1 then ''DA'' else ''NU'' end ComClosed, '                   || coalesce(chr(13),'') ||
      '  to_char(c1.termen, ''WW'')::numeric saptamana, '                                   || coalesce(chr(13),'') ||
      '  case when c.anulat = 1 then ''DA'' else ''NU'' end ComCanceled, '                  || coalesce(chr(13),'') ||
      '  case when c.operat = 1 then ''DA'' else ''NU'' end ComOperata '                    || coalesce(chr(13),'') ||
      'from '                                                                               || coalesce(chr(13),'') ||
      '  comanda c '                                                                        || coalesce(chr(13),'') ||
      '  inner join ngest         g on c.codgest      = g.codgest '                         || coalesce(chr(13),'') ||
      '  inner join comanda1     c1 on c1.codcomanda  = c.codcomanda '                      || coalesce(chr(13),'') ||
      '  inner join cmdprodmat  mat on c1.codcomanda1 = mat.codcomanda1 and mat.tip = 0 '   || coalesce(chr(13),'') ||
      '  inner join cmdprodmat matc on c1.codcomanda1 = matc.codcomanda1 and matc.tip &gt; 0 ' || coalesce(chr(13),'') ||
      '  inner join nartobj     obj on mat.codobiect  = obj.codobiect '                     || coalesce(chr(13),'') ||
      '  inner join nartobj    objc on matc.codobiect = objc.codobiect '                    || coalesce(chr(13),'') ||
      '  inner join num1            on c1.umsec       = num1.codum1 '                       || coalesce(chr(13),'') ||
      '  left  join doccarnete  doc on c.carnetdoc    = doc.codcarnet '                     || coalesce(chr(13),'') ||
      '  left  join prodcomp    ret on c1.codreteta   = ret.codprodcomp '                   || coalesce(chr(13),'') ||
      'where c.an*12+c.luna = getanlucru()*12+ getlunalucru() ' || coalesce(sCondNeop,'') || PKG_LIST_BASE_UTILS_COND_SUBUNIT('C', 'SUBUNITATEA',NULL,NULL) ||
      '), ';

      sWith := sWith || 'ComSub as ('                                             || coalesce(chr(13),'') ||
      'select '                                                                   || coalesce(chr(13),'') ||
      '  c1.CodComanda1, '                                                        || coalesce(chr(13),'') ||
      '  doc.simbol CarnetDocSub, '                                               || coalesce(chr(13),'') ||
      '  c.NrDoc NrDocSub, '                                                      || coalesce(chr(13),'') ||
      '  c.DataDoc DataDocSub, '                                                  || coalesce(chr(13),'') ||
      '  doc.serie SerieDocSub, '                                                 || coalesce(chr(13),'') ||
      '  s.den_subunit subunitate, '                                              || coalesce(chr(13),'') ||
      '  c1.Termen TermenLivr '                                                   || coalesce(chr(13),'') ||
      'from '                                                                     || coalesce(chr(13),'') ||
      '  comanda c '                                                              || coalesce(chr(13),'') ||
      '  inner join nsubunit     s on c.subunitatea  = s.codsubunit '             || coalesce(chr(13),'') ||
      '  inner join comanda1    c1 on c1.codcomanda  = c.codcomanda '             || coalesce(chr(13),'') ||
      '  left  join doccarnete doc on c.carnetdoc    = doc.codcarnet '            || coalesce(chr(13),'') ||
      'where c.tipdoc = 44 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C', 'SUBUNITSURSA',NULL,NULL),'') ||
      '), ';
      sWith := sWith || 'CantRealLC as ('                                         || coalesce(chr(13),'') ||
      'select '                                                                   || coalesce(chr(13),'') ||
      '  sum(i1.Cant) cant, '                                                     || coalesce(chr(13),'') ||
      '  pl.codliniecomanda '                                                     || coalesce(chr(13),'') ||
      'from '                                                                     || coalesce(chr(13),'') ||
      '  intrari i '                                                              || coalesce(chr(13),'') ||
      '  inner join intrari1     i1 on i.codintr   = i1.codintr '                 || coalesce(chr(13),'') ||
      '  inner join intrprodlink PL on i1.codintr1 = PL.codintr1 '                || coalesce(chr(13),'') ||
      'where i.tipdoc = 7 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', 'SUBUNITATEA',NULL,NULL),'') ||
      'group by pl.codliniecomanda
      ), ';
      sWith := sWith || 'facturat as ('                                           || coalesce(chr(13),'') ||
      'select '                                                                   || coalesce(chr(13),'') ||
      '  c1.Codcomanda1, '                                                        || coalesce(chr(13),'') ||
      '  sum(i1.Cant) cant, '                                                     || coalesce(chr(13),'') ||
      '  string_agg(i.nrdoc::varchar, '''') nrdoc, '                              || coalesce(chr(13),'') ||
      '  string_agg(to_char(i.datadoc, ''DD.MM.YYYY''), '''') datadoc '           || coalesce(chr(13),'') ||
      'from '                                                                     || coalesce(chr(13),'') ||
      '  iesiri i '                                                               || coalesce(chr(13),'') ||
      '  inner join iesiri1  i1 on i.codies          = i1.codies '                || coalesce(chr(13),'') ||
      '  inner join ieslink  L  on i1.codies1        = L.codies1 '                || coalesce(chr(13),'') ||
      '  inner join comanda1 c1 on l.codliniecomanda = c1.codcomanda1 '           || coalesce(chr(13),'') ||
      'where 1=1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', 'SUBUNITATEA',NULL,NULL),'') ||
      'group by c1.codcomanda1
      ), ';
      sWith := sWith || 'DL as ('                                                 || coalesce(chr(13),'') ||
      'select '                                                                   || coalesce(chr(13),'') ||
      '  c1.Codcomanda1, '                                                        || coalesce(chr(13),'') ||
      '  sum(i1.Cant) cant, '                                                     || coalesce(chr(13),'') ||
      '  string_agg(i.nrdoc::varchar, '''') nrdoc, '                              || coalesce(chr(13),'') ||
      '  string_agg(to_char(i.datadoc, ''DD.MM.YYYY''), '''') datadoc '           || coalesce(chr(13),'') ||
      'from '                                                                     || coalesce(chr(13),'') ||
      '  iesiri i '                                                               || coalesce(chr(13),'') ||
      '  inner join iesiri1     i1 on i.codies           = i1.codies '            || coalesce(chr(13),'') ||
      '  inner join ieslink     L  on i1.codies1         = L.codies1 '            || coalesce(chr(13),'') ||
      '  inner join cmdlivrlink LL on L.codliniecomanda  = LL.codcomanda1 '       || coalesce(chr(13),'') ||
      '  inner join comanda1    c1 on LL.codliniecomanda = c1.codcomanda1 '       || coalesce(chr(13),'') ||
      'where 1=1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', 'SUBUNITATEA',NULL,NULL),'') ||
      'group by c1.codcomanda1
      ) ';
      sSelect := '
           select ComProd.CodComanda, '                                                                       || coalesce(chr(13),'') ||
                 'ComProd.TipDoc, '                                                                           || coalesce(chr(13),'') ||
                 'ComProd.CarnetDocProd, '                                                                    || coalesce(chr(13),'') ||
                 'ComProd.NrDocProd, '                                                                        || coalesce(chr(13),'') ||
                 'ComProd.DataDocProd, '                                                                      || coalesce(chr(13),'') ||
                 'ComProd.SerieDocProd, '                                                                     || coalesce(chr(13),'') ||
                 'ComProd.Produs, '                                                                           || coalesce(chr(13),'') ||
                 'ComProd.Reteta, '                                                                           || coalesce(chr(13),'') ||
                 'ComProd.TermenExec, '                                                                       || coalesce(chr(13),'') ||
                 'ComProd.DenUM, '                                                                            || coalesce(chr(13),'') ||
                 'ComProd.CantLansata, '                                                                      || coalesce(chr(13),'') ||
                 'ComProd.PretLansat, '                                                                       || coalesce(chr(13),'') ||
                 'ComProd.ValLansata, '                                                                       || coalesce(chr(13),'') ||
                 'ComProd.CantRealiz, '                                                                       || coalesce(chr(13),'') ||
                 'CantRealLC.Cant, '                                                                          || coalesce(chr(13),'') ||
                 'ComProd.ValRealiz, '                                                                        || coalesce(chr(13),'') ||
                 'ComProd.DifCant, '                                                                          || coalesce(chr(13),'') ||
                 'ComProd.DifVal, '                                                                           || coalesce(chr(13),'') ||
                 'ComCli.Client, '                                                                            || coalesce(chr(13),'') ||
                 'ComCli.CarnetDocCli, '                                                                      || coalesce(chr(13),'') ||
                 'ComCli.NrDocCli, '                                                                          || coalesce(chr(13),'') ||
                 'ComCli.DataDocCli, '                                                                        || coalesce(chr(13),'') ||
                 'ComCli.SerieDocCli, '                                                                       || coalesce(chr(13),'') ||
                 'ComProd.Sectie, '                                                                           || coalesce(chr(13),'') ||
                 'ComCli.TermenLivr, '                                                                        || coalesce(chr(13),'') ||
                 'ComProd.Component, '                                                                        || coalesce(chr(13),'') ||
                 'ComProd.CantComp, '                                                                         || coalesce(chr(13),'') ||
                 'umcomponent.den_um, '                                                                       || coalesce(chr(13),'') ||
                 'ComProd.Schimb, '                                                                           || coalesce(chr(13),'') ||
                 'formatii.den_formatie, '                                                                    || coalesce(chr(13),'') ||
                 'gimp.den_gest, '                                                                            || coalesce(chr(13),'') ||
                 'case when COALESCE(facturat.codcomanda1,0) = 0 then DL.cant else facturat.cant end, '       || coalesce(chr(13),'') ||
                 'case when COALESCE(facturat.codcomanda1,0) = 0 then DL.nrdoc else facturat.nrdoc end, '     || coalesce(chr(13),'') ||
                 'case when COALESCE(facturat.codcomanda1,0) = 0 then DL.datadoc else facturat.datadoc end, ' || coalesce(chr(13),'') ||
                 'ComProd.ComClosed, '                                                                        || coalesce(chr(13),'') ||
                 'ComSub.Subunitate, '                                                                        || coalesce(chr(13),'') ||
                 'ComSub.SerieDocSub, '                                                                       || coalesce(chr(13),'') ||
                 'ComSub.NrDocSub, '                                                                          || coalesce(chr(13),'') ||
                 'ComSub.DataDocSub, '                                                                        || coalesce(chr(13),'') ||
                 'ComProd.Saptamana, '                                                                        || coalesce(chr(13),'') ||
                 'ComProd.ComCanceled, '                                                                      || coalesce(chr(13),'') ||
                 'ComCli.ComClosed, '                                                                         || coalesce(chr(13),'') ||
                 'ComCli.ComCanceled, '                                                                       || coalesce(chr(13),'') ||
                 'comprod.comoperata ' || coalesce(gUserAlias,'') || '
            from ComProd
              inner join nartobj       produs      on produs.codobiect                 = comprod.codprodus
              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
              inner join comanda       c           on c.codcomanda                     = ComProd.codcomanda
              inner join comanda1      c1          on c1.codcomanda1                   = ComProd.codcomanda1
              LEFT  JOIN PRODCOMP      PC          ON PC.CODPRODCOMP                   = C1.CODRETETA
              left  join formatii                  on COALESCE(comprod.codformatie, 0) = formatii.codformatie
              left  join tmp_comcli    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.codcomanda1c
              left  join DL                        on DL.codcomanda1                   = comcli.codcomanda1
              left  join nartimplicite artcimp     on artc.codarticol                  = artcimp.codarticol    AND artcimp.codsubunit = getsubunitate()
              left  join ngest         gimp        on artcimp.gestimplicita            = gimp.codgest
              left  join cantrealLC                on cantreallc.codliniecomanda       = comprod.codcmdprodmat ' || coalesce(gSuplJoins,'');
    ELSE
      sInsert := 'INSERT INTO ' || 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,
                                      Schimb,
                                      Formatie,
                                      Facturat,
                                      FNrDoc,
                                      FDataDoc,
                                      ComClosed,
                                      Subunitate,
                                      CmdSubSerie,
                                      CmdSubNrDoc,
                                      CmdSubDataDoc,
                                      Saptamana,
                                      ComCanceled,
                                      ComCliClosed,
                                      ComCliCanceled,
                                      ComCliOperata ' || gUserFields || ')';
      sWith := 'WITH ';
      sWith := sWith || 'ComProd as ('                                                      || coalesce(chr(13),'') ||
      'select '                                                                             || coalesce(chr(13),'') ||
      '  c.CodComanda, '                                                                    || coalesce(chr(13),'') ||
      '  c.TipDoc, '                                                                        || coalesce(chr(13),'') ||
      '  c1.CodComanda1, '                                                                  || coalesce(chr(13),'') ||
      '  mat.CodCmdProdMat, '                                                               || coalesce(chr(13),'') ||
      '  doc.simbol CarnetDocProd, '                                                        || coalesce(chr(13),'') ||
      '  c.NrDoc NrDocProd, '                                                               || coalesce(chr(13),'') ||
      '  c.DataDoc DataDocProd, '                                                           || coalesce(chr(13),'') ||
      '  doc.serie SerieDocProd, '                                                          || coalesce(chr(13),'') ||
      '  obj.denumire produs, '                                                             || coalesce(chr(13),'') ||
      '  obj.codobiect codprodus, '                                                         || coalesce(chr(13),'') ||
      '  ret.obs Reteta, '                                                                  || coalesce(chr(13),'') ||
      '  c1.Termen TermenExec, '                                                            || coalesce(chr(13),'') ||
      '  num1.den_um1 DenUM, '                                                              || coalesce(chr(13),'') ||
      '  mat.Cant CantLansata, '                                                            || coalesce(chr(13),'') ||
      '  mat.Pret PretLansat, '                                                             || coalesce(chr(13),'') ||
      '  mat.Cant*mat.Pret ValLansata, '                                                    || coalesce(chr(13),'') ||
      '  mat.Cant - mat.Rest CantRealiz, '                                                  || coalesce(chr(13),'') ||
      '  (mat.Cant - mat.Rest)*mat.Pret ValRealiz, '                                        || coalesce(chr(13),'') ||
      '  mat.Rest DifCant, '                                                                || coalesce(chr(13),'') ||
      '  mat.Rest*mat.Pret DifVal, '                                                        || coalesce(chr(13),'') ||
      '  G.Den_gest Sectie, '                                                               || coalesce(chr(13),'') ||
      '  0 codcomponent, '                                                                  || coalesce(chr(13),'') ||
      '  c.CodFormatie, '                                                                   || coalesce(chr(13),'') ||
      '  COALESCE(c.schimb, 0) schimb, '                                                    || coalesce(chr(13),'') ||
      '  case when c.inchisa = 1 then ''DA'' else ''NU'' end ComClosed, '                   || coalesce(chr(13),'') ||
      '  to_char(c1.termen, ''WW'')::numeric saptamana, '                                   || coalesce(chr(13),'') ||
      '  case when c.anulat = 1 then ''DA'' else ''NU'' end ComCanceled, '                  || coalesce(chr(13),'') ||
      '  case when c.operat = 1 then ''DA'' else ''NU'' end ComOperata '                    || coalesce(chr(13),'') ||
      'from '                                                                               || coalesce(chr(13),'') ||
      '  comanda c '                                                                        || coalesce(chr(13),'') ||
      '  inner join ngest         g on c.codgest      = g.codgest '                         || coalesce(chr(13),'') ||
      '  inner join comanda1     c1 on c1.codcomanda  = c.codcomanda '                      || coalesce(chr(13),'') ||
      '  inner join cmdprodmat  mat on c1.codcomanda1 = mat.codcomanda1 and mat.tip = 0 '   || coalesce(chr(13),'') ||
      '  inner join nartobj     obj on mat.codobiect  = obj.codobiect '                     || coalesce(chr(13),'') ||
      '  inner join num1            on c1.umsec       = num1.codum1 '                       || coalesce(chr(13),'') ||
      '  left  join doccarnete  doc on c.carnetdoc    = doc.codcarnet '                     || coalesce(chr(13),'') ||
      '  left  join prodcomp    ret on c1.codreteta   = ret.codprodcomp '                   || coalesce(chr(13),'') ||
      'where c.an*12+c.luna = getanlucru()*12+ getlunalucru() ' || coalesce(sCondNeop,'') || PKG_LIST_BASE_UTILS_COND_SUBUNIT('C', 'SUBUNITATEA',NULL,NULL) ||
      '), ';
      sWith := sWith || 'ComSub as ('                                  || coalesce(chr(13),'') ||
      'select '                                                        || coalesce(chr(13),'') ||
      '  c1.CodComanda1, '                                             || coalesce(chr(13),'') ||
      '  doc.simbol CarnetDocSub, '                                    || coalesce(chr(13),'') ||
      '  c.NrDoc NrDocSub, '                                           || coalesce(chr(13),'') ||
      '  c.DataDoc DataDocSub, '                                       || coalesce(chr(13),'') ||
      '  doc.serie SerieDocSub, '                                      || coalesce(chr(13),'') ||
      '  s.den_subunit subunitate, '                                   || coalesce(chr(13),'') ||
      '  c1.Termen TermenLivr '                                        || coalesce(chr(13),'') ||
      'from '                                                          || coalesce(chr(13),'') ||
      '  comanda c '                                                   || coalesce(chr(13),'') ||
      '  inner join nsubunit     s on c.subunitatea  = s.codsubunit '  || coalesce(chr(13),'') ||
      '  inner join comanda1    c1 on c1.codcomanda  = c.codcomanda '  || coalesce(chr(13),'') ||
      '  left  join doccarnete doc on c.carnetdoc    = doc.codcarnet ' || coalesce(chr(13),'') ||
      'where c.tipdoc = 44 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C', 'SUBUNITSURSA',NULL,NULL),'') ||
      '), ';
      sWith := sWith || 'CantRealLC as ('                            || coalesce(chr(13),'') ||
      'select '                                                      || coalesce(chr(13),'') ||
      '  sum(i1.Cant) cant, '                                        || coalesce(chr(13),'') ||
      '  pl.codliniecomanda '                                        || coalesce(chr(13),'') ||
      'from '                                                        || coalesce(chr(13),'') ||
      '  intrari i '                                                 || coalesce(chr(13),'') ||
      '  inner join intrari1    i1 on i.codintr = i1.codintr '       || coalesce(chr(13),'') ||
      '  inner join intrprodlink PL on i1.codintr1 = PL.codintr1 '   || coalesce(chr(13),'') ||
      'where i.tipdoc = 7 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', 'SUBUNITATEA',NULL,NULL),'') ||
      'group by pl.codliniecomanda
      ), ';
      sWith := sWith || 'facturat as ('                                   || coalesce(chr(13),'') ||
      'select '                                                           || coalesce(chr(13),'') ||
      '  c1.Codcomanda1, '                                                || coalesce(chr(13),'') ||
      '  sum(i1.Cant) cant, '                                             || coalesce(chr(13),'') ||
      '  string_agg(i.nrdoc::varchar, '''') nrdoc, '                      || coalesce(chr(13),'') ||
      '  string_agg(to_char(i.datadoc, ''DD.MM.YYYY''), '''') datadoc '   || coalesce(chr(13),'') ||
      'from '                                                             || coalesce(chr(13),'') ||
      '  iesiri i '                                                       || coalesce(chr(13),'') ||
      '  inner join iesiri1  i1 on i.codies          = i1.codies '        || coalesce(chr(13),'') ||
      '  inner join ieslink  L  on i1.codies1        = L.codies1 '        || coalesce(chr(13),'') ||
      '  inner join comanda1 c1 on l.codliniecomanda = c1.codcomanda1 '   || coalesce(chr(13),'') ||
      'where 1=1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', 'SUBUNITATEA',NULL,NULL),'') ||
      ' group by c1.codcomanda1
      ), ';
      sWith := sWith || 'DL as ('                                            || coalesce(chr(13),'') ||
      'select '                                                              || coalesce(chr(13),'') ||
      '  c1.Codcomanda1, '                                                   || coalesce(chr(13),'') ||
      '  sum(i1.Cant) cant, '                                                || coalesce(chr(13),'') ||
      '  string_agg(i.nrdoc::varchar, '''') nrdoc, '                         || coalesce(chr(13),'') ||
      '  string_agg(to_char(i.datadoc, ''DD.MM.YYYY''), '''') datadoc '      || coalesce(chr(13),'') ||
      'from '                                                                || coalesce(chr(13),'') ||
      '  iesiri i '                                                          || coalesce(chr(13),'') ||
      '  inner join iesiri1     i1 on i.codies           = i1.codies '       || coalesce(chr(13),'') ||
      '  inner join ieslink     L  on i1.codies1         = L.codies1 '       || coalesce(chr(13),'') ||
      '  inner join cmdlivrlink LL on L.codliniecomanda  = LL.codcomanda1 '  || coalesce(chr(13),'') ||
      '  inner join comanda1    c1 on LL.codliniecomanda = c1.codcomanda1 '  || coalesce(chr(13),'') ||
      'where 1=1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', 'SUBUNITATEA',NULL,NULL),'') ||
      ' group by c1.codcomanda1
      ) ';
      sSelect := '
           select ComProd.CodComanda, ' || coalesce(chr(13),'') ||
           'ComProd.TipDoc, '           || coalesce(chr(13),'') ||
           'ComProd.CarnetDocProd, '    || coalesce(chr(13),'') ||
           'ComProd.NrDocProd, '        || coalesce(chr(13),'') ||
           'ComProd.DataDocProd, '      || coalesce(chr(13),'') ||
           'ComProd.SerieDocProd, '     || coalesce(chr(13),'') ||
           'ComProd.Produs, '           || coalesce(chr(13),'') ||
           'ComProd.Reteta, '           || coalesce(chr(13),'') ||
           'ComProd.TermenExec, '       || coalesce(chr(13),'') ||
           'ComProd.DenUM, '            || coalesce(chr(13),'') ||
           'ComProd.CantLansata, '      || coalesce(chr(13),'') ||
           'ComProd.PretLansat, '       || coalesce(chr(13),'') ||
           'ComProd.ValLansata, '       || coalesce(chr(13),'') ||
           'ComProd.CantRealiz, '       || coalesce(chr(13),'') ||
           'CantRealLC.Cant, '          || coalesce(chr(13),'') ||
           'ComProd.ValRealiz, '        || coalesce(chr(13),'') ||
           'ComProd.DifCant, '          || coalesce(chr(13),'') ||
           'ComProd.DifVal, '           || coalesce(chr(13),'') ||
           'ComCli.Client, '            || coalesce(chr(13),'') ||
           'ComCli.CarnetDocCli, '      || coalesce(chr(13),'') ||
           'ComCli.NrDocCli, '          || coalesce(chr(13),'') ||
           'ComCli.DataDocCli, '        || coalesce(chr(13),'') ||
           'ComCli.SerieDocCli, '       || coalesce(chr(13),'') ||
           'ComProd.Sectie, '           || coalesce(chr(13),'') ||
           'ComCli.TermenLivr, '        || coalesce(chr(13),'') ||
           'ComProd.Schimb, '           || coalesce(chr(13),'') ||
           'formatii.den_formatie, '    || coalesce(chr(13),'') ||
           'case when COALESCE(facturat.codcomanda1,0) = 0 then DL.cant else facturat.cant end, '       || coalesce(chr(13),'') ||
           'case when COALESCE(facturat.codcomanda1,0) = 0 then DL.nrdoc else facturat.nrdoc end, '     || coalesce(chr(13),'') ||
           'case when COALESCE(facturat.codcomanda1,0) = 0 then DL.datadoc else facturat.datadoc end, ' || coalesce(chr(13),'') ||
           'ComProd.ComClosed, '   || coalesce(chr(13),'') ||
           'ComSub.Subunitate, '   || coalesce(chr(13),'') ||
           'ComSub.SerieDocSub, '  || coalesce(chr(13),'') ||
           'ComSub.NrDocSub, '     || coalesce(chr(13),'') ||
           'ComSub.DataDocSub, '   || coalesce(chr(13),'') ||
           'ComProd.Saptamana, '   || coalesce(chr(13),'') ||
           'ComProd.ComCanceled, ' || coalesce(chr(13),'') ||
           'ComCli.ComClosed, '    || coalesce(chr(13),'') ||
           'ComCli.ComCanceled, '  || coalesce(chr(13),'') ||
           'comprod.comoperata '   || coalesce(gUserAlias,'') || '
            from ComProd
              inner join nartobj    produs    on produs.codobiect                 = comprod.codprodus
              inner join comanda    c         on c.codcomanda                     = ComProd.codcomanda
              inner join comanda1   c1        on c1.codcomanda1                   = ComProd.codcomanda1
              left  join nartobj    component on component.codobiect              = comprod.codcomponent
              LEFT  JOIN PRODCOMP   PC        ON PC.CODPRODCOMP                   = C1.CODRETETA
              left  join formatii             on COALESCE(comprod.codformatie, 0) = formatii.codformatie
              left  join tmp_comcli 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.codcomanda1c
              left  join DL                   on DL.codcomanda1                   = comcli.codcomanda1
              left  join cantrealLC           on cantreallc.codliniecomanda       = comprod.codcmdprodmat ' || gSuplJoins;
    END IF;
  ELSE
    DELETE FROM tmp_comcli;

    sWith := 'insert into tmp_comcli(CODCOMANDA1,CARNETDOCCLI,NRDOCCLI,DATADOCCLI,SERIEDOCCLI,CLIENT,TERMENLIVR,COMCLOSED,COMCANCELED,CODCOMANDA,CODCOMANDA1C)' || coalesce(chr(13),'') ||
      'with recursive tmp(codcmdint1, codcmdcli1) as
       (SELECT ci1.codcomanda1 codcmdint1, cc1.codcomanda1 codcmdcli1
        from comanda1 ci1
             inner join comanda  ci  on ci1.codcomanda = ci.codcomanda
             inner join cmdlink  l   on l.codcomanda1 = ci1.codcomanda1
             inner join comanda1 cc1 on l.codliniecomanda = cc1.codcomanda1
             inner join comanda  cc  on cc1.codcomanda = cc.codcomanda where cc.tipdoc = 18
                                        and ci.tipdoc = 53 and ci.datadoc &lt;= to_date(''' || coalesce(current_setting('PKG_LIST_BASE_PROGLUNFAB.vZiuaFin', true),'') || ''',''dd.mm.yyyy'')
                                        and l.codcomanda1 = ci1.CodComanda1
        UNION ALL
        select ci1.codcomanda1 codcmdint1, cc1.codcomanda1 codcmdcli1
        from comanda1 ci1
             inner join tmp      t   ON t.codcmdint1 = codcmdint1
             inner join comanda  ci  on ci1.codcomanda = ci.codcomanda
             inner join cmdlink  l   on l.codcomanda1 = ci1.codcomanda1
             inner join comanda1 cc1 on l.codliniecomanda = cc1.codcomanda1
             inner join comanda  cc  on cc1.codcomanda = cc.codcomanda where cc.tipdoc = 18 and ci.tipdoc = 53
                                        and ci.datadoc &lt;= to_date(''' || coalesce(current_setting('PKG_LIST_BASE_PROGLUNFAB.vZiuaFin', true),'') || ''',''dd.mm.yyyy'')
                                        and l.codcomanda1 = cc1.codcomanda1
       )' ||
    'SELECT '                                                                || coalesce(chr(13),'') ||
      '  cli.CodCmdInt1 codcomanda1, '                                       || coalesce(chr(13),'') ||
      '  doc.simbol CarnetDocCli, '                                          || coalesce(chr(13),'') ||
      '  cc.NrDoc NrDocCli, '                                                || coalesce(chr(13),'') ||
      '  cc.DataDoc DataDocCli, '                                            || coalesce(chr(13),'') ||
      '  doc.serie SerieDocCli, '                                            || coalesce(chr(13),'') ||
      '  P.den_part client, '                                                || coalesce(chr(13),'') ||
      '  cc1.Termen TermenLivr, '                                            || coalesce(chr(13),'') ||
      '  case when cc.inchisa = 1 then ''DA'' else ''NU'' end ComClosed, '   || coalesce(chr(13),'') ||
      '  case when cc.anulat  = 1 then ''DA'' else ''NU'' end ComCanceled, ' || coalesce(chr(13),'') ||
      '  cC.codcomanda,CLI.CODCMDCLI1 '                                      || coalesce(chr(13),'') ||
    'FROM '                                                                  || coalesce(chr(13),'') ||
      '   tmp cli
              inner join comanda1  cc1 on cli.codcmdcli1 = cc1.codcomanda1 ' ||chr(13)||
           '  inner join comanda   cc  on cc1.codcomanda = cc.codcomanda '   ||chr(13)||
           '  inner join npart     p   on cc.partener    = p.codpart
              left join doccarnete doc on cc.carnetdoc   = doc.codcarnet ';
    PERFORM LIST_EXECUTE_IMMEDIATE(swith, aListID, aListVer);

    IF NOT current_setting('PKG_LIST_BASE_PROGLUNFAB.vCentralizare', true)::boolean THEN
      sInsert := 'INSERT INTO ' || 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,
                                        Component,
                                        CantComp,
                                        UMComp,
                                        Schimb,
                                        Formatie,
                                        GestImp,
                                        Facturat,
                                        FNrDoc,
                                        FDataDoc,
                                        ComClosed,
                                        Subunitate,
                                        CmdSubSerie,
                                        CmdSubNrDoc,
                                        CmdSubDataDoc,
                                        Saptamana,
                                        ComCanceled,
                                        ComCliClosed,
                                        ComCliCanceled,
                                        ComCliOperata ' || gUserFields || ')';
      sWith := 'WITH ';
      sWith := sWith || 'ComProd as ('                                                      || coalesce(chr(13),'') ||
      'select '                                                                             || coalesce(chr(13),'') ||
      '  c.CodComanda, '                                                                    || coalesce(chr(13),'') ||
      '  c.TipDoc, '                                                                        || coalesce(chr(13),'') ||
      '  c1.CodComanda1, '                                                                  || coalesce(chr(13),'') ||
      '  mat.CodCmdProdMat, '                                                               || coalesce(chr(13),'') ||
      '  doc.simbol CarnetDocProd, '                                                        || coalesce(chr(13),'') ||
      '  c.NrDoc NrDocProd, '                                                               || coalesce(chr(13),'') ||
      '  c.DataDoc DataDocProd, '                                                           || coalesce(chr(13),'') ||
      '  doc.serie SerieDocProd, '                                                          || coalesce(chr(13),'') ||
      '  obj.denumire produs, '                                                             || coalesce(chr(13),'') ||
      '  obj.codobiect codprodus, '                                                         || coalesce(chr(13),'') ||
      '  ret.obs Reteta, '                                                                  || coalesce(chr(13),'') ||
      '  c1.Termen TermenExec, '                                                            || coalesce(chr(13),'') ||
      '  num1.den_um1 DenUM, '                                                              || coalesce(chr(13),'') ||
      '  mat.Cant CantLansata, '                                                            || coalesce(chr(13),'') ||
      '  mat.Pret PretLansat, '                                                             || coalesce(chr(13),'') ||
      '  mat.Cant*mat.Pret ValLansata, '                                                    || coalesce(chr(13),'') ||
      '  mat.Cant - mat.Rest CantRealiz, '                                                  || coalesce(chr(13),'') ||
      '  (mat.Cant - mat.Rest)*mat.Pret ValRealiz, '                                        || coalesce(chr(13),'') ||
      '  mat.Rest DifCant, '                                                                || coalesce(chr(13),'') ||
      '  mat.Rest*mat.Pret DifVal, '                                                        || coalesce(chr(13),'') ||
      '  G.Den_gest Sectie, '                                                               || coalesce(chr(13),'') ||
      '  objc.denumire component, '                                                         || coalesce(chr(13),'') ||
      '  objc.codobiect codcomponent, '                                                     || coalesce(chr(13),'') ||
      '  c.CodFormatie, '                                                                   || coalesce(chr(13),'') ||
      '  COALESCE(c.schimb, 0) schimb, '                                                    || coalesce(chr(13),'') ||
      '  matc.cant CantComp, '                                                              || coalesce(chr(13),'') ||
      '  case when c.inchisa = 1 then ''DA'' else ''NU'' end ComClosed, '                   || coalesce(chr(13),'') ||
      '  to_char(c1.termen, ''WW'')::numeric saptamana, '                                   || coalesce(chr(13),'') ||
      '  case when c.anulat = 1 then ''DA'' else ''NU'' end ComCanceled, '                  || coalesce(chr(13),'') ||
      '  case when c.operat = 1 then ''DA'' else ''NU'' end ComOperata '                    || coalesce(chr(13),'') ||
      'from '                                                                               || coalesce(chr(13),'') ||
      '  comanda c '                                                                        || coalesce(chr(13),'') ||
      '  inner join ngest         g on c.codgest      = g.codgest '                         || coalesce(chr(13),'') ||
      '  inner join comanda1     c1 on c1.codcomanda  = c.codcomanda '                      || coalesce(chr(13),'') ||
      '  inner join cmdprodmat  mat on c1.codcomanda1 = mat.codcomanda1 and mat.tip = 0 '   || coalesce(chr(13),'') ||
      '  inner join cmdprodmat matc on c1.codcomanda1 = matc.codcomanda1 and matc.tip &gt; 0 ' || coalesce(chr(13),'') ||
      '  inner join nartobj     obj on mat.codobiect  = obj.codobiect '                     || coalesce(chr(13),'') ||
      '  inner join nartobj    objc on matc.codobiect = objc.codobiect '                    || coalesce(chr(13),'') ||
      '  inner join num1            on c1.umsec       = num1.codum1 '                       || coalesce(chr(13),'') ||
      '  left  join doccarnete  doc on c.carnetdoc    = doc.codcarnet '                     || coalesce(chr(13),'') ||
      '  left  join prodcomp    ret on c1.codreteta   = ret.codprodcomp '                   || coalesce(chr(13),'') ||
      'where c.datadoc between to_date(''' || coalesce(current_setting('PKG_LIST_BASE_PROGLUNFAB.vZiuaIni', true),'') || ''',''dd.mm.yyyy'')
                           and to_date(''' || coalesce(current_setting('PKG_LIST_BASE_PROGLUNFAB.vZiuaFin', true),'') || ''',''dd.mm.yyyy'') ' || coalesce(sCondNeop,'')
      || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C', 'SUBUNITATEA',NULL,NULL),'') ||
      '), ';

      sWith := sWith || 'ComSub as (' || coalesce(chr(13),'') ||
      'select '                       || coalesce(chr(13),'') ||
      '  c1.CodComanda1, '            || coalesce(chr(13),'') ||
      '  doc.simbol CarnetDocSub, '   || coalesce(chr(13),'') ||
      '  c.NrDoc NrDocSub, '          || coalesce(chr(13),'') ||
      '  c.DataDoc DataDocSub, '      || coalesce(chr(13),'') ||
      '  doc.serie SerieDocSub, '     || coalesce(chr(13),'') ||
      '  s.den_subunit subunitate, '  || coalesce(chr(13),'') ||
      '  c1.Termen TermenLivr '       || coalesce(chr(13),'') ||
      'from '                         || coalesce(chr(13),'') ||
      '  comanda c '                  || coalesce(chr(13),'') ||
      '  inner join nsubunit     s on c.subunitatea  = s.codsubunit '  || coalesce(chr(13),'') ||
      '  inner join comanda1    c1 on c1.codcomanda  = c.codcomanda '  || coalesce(chr(13),'') ||
      '  left  join doccarnete doc on c.carnetdoc    = doc.codcarnet ' || coalesce(chr(13),'') ||
      'where c.tipdoc = 44 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C', 'SUBUNITSURSA',NULL,NULL),'') ||
      '), ';

      sWith := sWith || 'CantRealLC as (' || coalesce(chr(13),'') ||
      'select '                           || coalesce(chr(13),'') ||
      '  sum(i1.Cant) cant, '             || coalesce(chr(13),'') ||
      '  pl.codliniecomanda '             || coalesce(chr(13),'') ||
      'from '                             || coalesce(chr(13),'') ||
      '  intrari i '                      || coalesce(chr(13),'') ||
      '  inner join intrari1     i1 on i.codintr   = i1.codintr '  || coalesce(chr(13),'') ||
      '  inner join intrprodlink PL on i1.codintr1 = PL.codintr1 ' || coalesce(chr(13),'') ||
      'where i.tipdoc = 7 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', 'SUBUNITATEA',NULL,NULL),'') ||
      'group by pl.codliniecomanda
      ), ';

      sWith := sWith || 'facturat as (' || coalesce(chr(13),'') ||
      'select '                         || coalesce(chr(13),'') ||
      '  c1.Codcomanda1, '              || coalesce(chr(13),'') ||
      '  sum(i1.Cant) cant, '                                           || coalesce(chr(13),'') ||
      '  string_agg(i.nrdoc::varchar, '''') nrdoc, '                    || coalesce(chr(13),'') ||
      '  string_agg(to_char(i.datadoc, ''DD.MM.YYYY''), '''') datadoc ' || coalesce(chr(13),'') ||
      'from '                                                           || coalesce(chr(13),'') ||
      '  iesiri i '                                                     || coalesce(chr(13),'') ||
      '  inner join iesiri1  i1 on i.codies          = i1.codies '      || coalesce(chr(13),'') ||
      '  inner join ieslink  L  on i1.codies1        = L.codies1 '      || coalesce(chr(13),'') ||
      '  inner join comanda1 c1 on l.codliniecomanda = c1.codcomanda1 ' || coalesce(chr(13),'') ||
      'where 1=1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', 'SUBUNITATEA',NULL,NULL),'') ||
      'group by c1.codcomanda1
      ), ';

      sWith := sWith || 'DL as ('                                           || coalesce(chr(13),'') ||
      'select '                                                             || coalesce(chr(13),'') ||
       '  c1.Codcomanda1, '                                                  || coalesce(chr(13),'') ||
      '  sum(i1.Cant) cant, '                                               || coalesce(chr(13),'') ||
      '  string_agg(i.nrdoc::varchar, '''') nrdoc, '                        || coalesce(chr(13),'') ||
      '  string_agg(to_char(i.datadoc, ''DD.MM.YYYY''), '''') datadoc '     || coalesce(chr(13),'') ||
      'from '                                                               || coalesce(chr(13),'') ||
      '  iesiri i '                                                         || coalesce(chr(13),'') ||
      '  inner join iesiri1     i1 on i.codies           = i1.codies '      || coalesce(chr(13),'') ||
      '  inner join ieslink     L  on i1.codies1         = L.codies1 '      || coalesce(chr(13),'') ||
      '  inner join cmdlivrlink LL on L.codliniecomanda  = LL.codcomanda1 ' || coalesce(chr(13),'') ||
      '  inner join comanda1    c1 on LL.codliniecomanda = c1.codcomanda1 ' || coalesce(chr(13),'') ||
      'where 1=1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', 'SUBUNITATEA',NULL,NULL),'') ||
      'group by c1.codcomanda1
      ) ';

      sSelect := '
           select ComProd.CodComanda, ' || coalesce(chr(13),'') ||
           'ComProd.TipDoc, '           || coalesce(chr(13),'') ||
           'ComProd.CarnetDocProd, '    || coalesce(chr(13),'') ||
           'ComProd.NrDocProd, '        || coalesce(chr(13),'') ||
           'ComProd.DataDocProd, '      || coalesce(chr(13),'') ||
           'ComProd.SerieDocProd, '     || coalesce(chr(13),'') ||
           'ComProd.Produs, '           || coalesce(chr(13),'') ||
           'ComProd.Reteta, '           || coalesce(chr(13),'') ||
           'ComProd.TermenExec, '       || coalesce(chr(13),'') ||
           'ComProd.DenUM, '            || coalesce(chr(13),'') ||
           'ComProd.CantLansata, '      || coalesce(chr(13),'') ||
           'ComProd.PretLansat, '       || coalesce(chr(13),'') ||
           'ComProd.ValLansata, '       || coalesce(chr(13),'') ||
           'ComProd.CantRealiz, '       || coalesce(chr(13),'') ||
           'CantRealLC.Cant, '          || coalesce(chr(13),'') ||
           'ComProd.ValRealiz, '        || coalesce(chr(13),'') ||
           'ComProd.DifCant, '          || coalesce(chr(13),'') ||
           'ComProd.DifVal, '           || coalesce(chr(13),'') ||
           'ComCli.Client, '            || coalesce(chr(13),'') ||
           'ComCli.CarnetDocCli, '      || coalesce(chr(13),'') ||
           'ComCli.NrDocCli, '          || coalesce(chr(13),'') ||
           'ComCli.DataDocCli, '        || coalesce(chr(13),'') ||
           'ComCli.SerieDocCli, '       || coalesce(chr(13),'') ||
           'ComProd.Sectie, '           || coalesce(chr(13),'') ||
           'ComCli.TermenLivr, '        || coalesce(chr(13),'') ||
           'ComProd.Component, '        || coalesce(chr(13),'') ||
           'ComProd.CantComp, '         || coalesce(chr(13),'') ||
           'umcomponent.den_um, '       || coalesce(chr(13),'') ||
           'ComProd.Schimb, '           || coalesce(chr(13),'') ||
           'formatii.den_formatie, '    || coalesce(chr(13),'') ||
           'gimp.den_gest, '            || coalesce(chr(13),'') ||
           'case when COALESCE(facturat.codcomanda1,0) = 0 then DL.cant else facturat.cant end, '       || coalesce(chr(13),'') ||
           'case when COALESCE(facturat.codcomanda1,0) = 0 then DL.nrdoc else facturat.nrdoc end, '     || coalesce(chr(13),'') ||
           'case when COALESCE(facturat.codcomanda1,0) = 0 then DL.datadoc else facturat.datadoc end, ' || coalesce(chr(13),'') ||
           'ComProd.ComClosed, '   || coalesce(chr(13),'') ||
           'ComSub.Subunitate, '   || coalesce(chr(13),'') ||
           'ComSub.SerieDocSub, '  || coalesce(chr(13),'') ||
           'ComSub.NrDocSub, '     || coalesce(chr(13),'') ||
           'ComSub.DataDocSub, '   || coalesce(chr(13),'') ||
           'ComProd.Saptamana, '   || coalesce(chr(13),'') ||
           'ComProd.ComCanceled, ' || coalesce(chr(13),'') ||
           'ComCli.ComClosed, '    || coalesce(chr(13),'') ||
           'ComCli.ComCanceled, '  || coalesce(chr(13),'') ||
           'comprod.comoperata '   || coalesce(gUserAlias,'') || '
            from ComProd
              inner join nartobj       produs      on produs.codobiect     = comprod.codprodus
              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
              inner join comanda       c           on c.codcomanda                     = ComProd.codcomanda
              inner join comanda1      c1          on c1.codcomanda1                   = ComProd.codcomanda1
              LEFT  JOIN PRODCOMP      PC          ON PC.CODPRODCOMP                   = C1.CODRETETA
              left  join formatii                  on COALESCE(comprod.codformatie, 0) = formatii.codformatie
              left  join tmp_comcli    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.codcomanda1c
              left  join DL                        on DL.codcomanda1             = comcli.codcomanda1
              left  join nartimplicite artcimp     on artc.codarticol            = artcimp.codarticol         AND artcimp.codsubunit = getsubunitate()
              left  join ngest         gimp        on artcimp.gestimplicita      = gimp.codgest
              left  join cantrealLC                on cantreallc.codliniecomanda = comprod.codcmdprodmat ' || gSuplJoins;
    ELSE
      sInsert := 'INSERT INTO ' || 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,
                                      Schimb,
                                      Formatie,
                                      Facturat,
                                      FNrDoc,
                                      FDataDoc,
                                      ComClosed,
                                      Subunitate,
                                      CmdSubSerie,
                                      CmdSubNrDoc,
                                      CmdSubDataDoc,
                                      Saptamana,
                                      ComCanceled,
                                      ComCliClosed,
                                      ComCliCanceled,
                                      ComCliOperata ' || gUserFields || ')';
      sWith := 'WITH ';
      sWith := coalesce(sWith,'') || 'ComProd    as (' || coalesce(chr(13),'') || 'select ' || coalesce(chr(13),'') || '  c.CodComanda, '      || coalesce(chr(13),'') || '  c.TipDoc, '                || coalesce(chr(13),'') || '  c1.CodComanda1, '   || coalesce(chr(13),'') || '  mat.CodCmdProdMat, '    || coalesce(chr(13),'') || '  doc.simbol CarnetDocProd, ' || coalesce(chr(13),'') || '  c.NrDoc NrDocProd, '        || coalesce(chr(13),'') || '  c.DataDoc DataDocProd, ' || coalesce(chr(13),'') || '  doc.serie SerieDocProd, ' || coalesce(chr(13),'') || '  obj.denumire produs, ' || coalesce(chr(13),'') || '  obj.codobiect codprodus, ' || coalesce(chr(13),'') || '  ret.obs Reteta, ' || coalesce(chr(13),'') || '  c1.Termen TermenExec, ' || coalesce(chr(13),'') || '  num1.den_um1 DenUM, ' || coalesce(chr(13),'') || '  mat.Cant CantLansata, ' || coalesce(chr(13),'') || '  mat.Pret PretLansat, ' || coalesce(chr(13),'') || '  mat.Cant*mat.Pret ValLansata, ' || coalesce(chr(13),'') || '  mat.Cant - mat.Rest CantRealiz, ' || coalesce(chr(13),'') || '  (mat.Cant - mat.Rest)*mat.Pret ValRealiz, ' || coalesce(chr(13),'') || '  mat.Rest DifCant, ' || coalesce(chr(13),'') || '  mat.Rest*mat.Pret DifVal, ' || coalesce(chr(13),'') || '  G.Den_gest Sectie, ' || coalesce(chr(13),'') || '  0 codcomponent, ' || coalesce(chr(13),'') || '  c.CodFormatie, ' || coalesce(chr(13),'') || '  COALESCE(c.schimb, 0) schimb, ' || coalesce(chr(13),'') || '  case when c.inchisa = 1 then ''DA'' else ''NU'' end ComClosed, ' || coalesce(chr(13),'') || '  to_char(c1.termen, ''WW'')::numeric saptamana, ' || coalesce(chr(13),'') || '  case when c.anulat = 1 then ''DA'' else ''NU'' end ComCanceled, ' || coalesce(chr(13),'') || '  case when c.operat = 1 then ''DA'' else ''NU'' end ComOperata ' || coalesce(chr(13),'') || 'from ' || coalesce(chr(13),'') || '  comanda c ' || coalesce(chr(13),'') || '  inner join ngest         g on c.codgest      = g.codgest ' || coalesce(chr(13),'') || '  inner join comanda1     c1 on c1.codcomanda  = c.codcomanda ' || coalesce(chr(13),'') || '  inner join cmdprodmat  mat on c1.codcomanda1 = mat.codcomanda1 and mat.tip = 0 ' || coalesce(chr(13),'') || '  inner join nartobj     obj on mat.codobiect  = obj.codobiect ' || coalesce(chr(13),'') || '  inner join num1            on c1.umsec       = num1.codum1 ' || coalesce(chr(13),'') || '  left  join doccarnete  doc on c.carnetdoc    = doc.codcarnet ' || coalesce(chr(13),'') || '  left  join prodcomp    ret on c1.codreteta   = ret.codprodcomp ' || coalesce(chr(13),'') || 'where c.datadoc between to_date(''' || coalesce(current_setting('PKG_LIST_BASE_PROGLUNFAB.vZiuaIni', true),'') || ''',''dd.mm.yyyy'') and to_date(''' || coalesce(current_setting('PKG_LIST_BASE_PROGLUNFAB.vZiuaFin', true),'') || ''',''dd.mm.yyyy'') ' || coalesce(sCondNeop,'') || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'C', 'SUBUNITATEA',NULL,NULL)),'') || '), ';
      sWith := coalesce(sWith,'') || 'ComSub     as (' || coalesce(chr(13),'') || 'select ' || coalesce(chr(13),'') || '  c1.CodComanda1, '    || coalesce(chr(13),'') || '  doc.simbol CarnetDocSub, ' || coalesce(chr(13),'') || '  c.NrDoc NrDocSub, ' || coalesce(chr(13),'') || '  c.DataDoc DataDocSub, ' || coalesce(chr(13),'') || '  doc.serie SerieDocSub, '    || coalesce(chr(13),'') || '  s.den_subunit subunitate, ' || coalesce(chr(13),'') || '  c1.Termen TermenLivr '   || coalesce(chr(13),'') || 'from ' || coalesce(chr(13),'') || '  comanda c ' || coalesce(chr(13),'') || '  inner join nsubunit     s on c.subunitatea   = s.codsubunit ' || coalesce(chr(13),'') || '  inner join comanda1    c1 on c1.codcomanda  = c.codcomanda ' || coalesce(chr(13),'') || '  left  join doccarnete doc on c.carnetdoc    = doc.codcarnet ' || coalesce(chr(13),'') || 'where c.tipdoc = 44 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'C', 'SUBUNITSURSA',NULL,NULL)),'') || '), ';
      sWith := coalesce(sWith,'') || 'CantRealLC as (' || coalesce(chr(13),'') || 'select ' || coalesce(chr(13),'') || '  sum(i1.Cant) cant, ' || coalesce(chr(13),'') || '  pl.codliniecomanda '       || coalesce(chr(13),'') || 'from ' || coalesce(chr(13),'') || '  intrari i ' || coalesce(chr(13),'') || '  inner join intrari1    i1 on i.codintr = i1.codintr ' || coalesce(chr(13),'') || '  inner join intrprodlink PL on i1.codintr1 = PL.codintr1 ' || coalesce(chr(13),'') || 'where i.tipdoc = 7 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I', 'SUBUNITATEA',NULL,NULL)),'') || ' group by pl.codliniecomanda ), ';
      sWith := coalesce(sWith,'') || 'facturat   as (' || coalesce(chr(13),'') || 'select ' || coalesce(chr(13),'') || '  c1.Codcomanda1, '    || coalesce(chr(13),'') || '  sum(i1.Cant) cant, '       || coalesce(chr(13),'') || '  string_agg(i.nrdoc::varchar, '''') nrdoc, ' || coalesce(chr(13),'') || '  string_agg(to_char(i.datadoc, ''DD.MM.YYYY''), '''') datadoc ' || coalesce(chr(13),'') || 'from ' || coalesce(chr(13),'') || '  iesiri i ' || coalesce(chr(13),'') || '  inner join iesiri1 i1 on i.codies = i1.codies ' || coalesce(chr(13),'') || '  inner join ieslink L on i1.codies1 = L.codies1 ' || coalesce(chr(13),'') || '  inner join comanda1 c1 on l.codliniecomanda = c1.codcomanda1 ' || coalesce(chr(13),'') || 'where 1=1 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I', 'SUBUNITATEA',NULL,NULL)),'') || ' group by c1.codcomanda1 ), ';
      sWith := coalesce(sWith,'') || 'DL         as (' || coalesce(chr(13),'') || 'select ' || coalesce(chr(13),'') || '  c1.Codcomanda1, '    || coalesce(chr(13),'') || '  sum(i1.Cant) cant, '       || coalesce(chr(13),'') || '  string_agg(i.nrdoc::varchar, '''') nrdoc, ' || coalesce(chr(13),'') || '  string_agg(to_char(i.datadoc, ''DD.MM.YYYY''), '''') datadoc ' || coalesce(chr(13),'') || 'from ' || coalesce(chr(13),'') || '  iesiri i ' || coalesce(chr(13),'') || '  inner join iesiri1 i1 on i.codies = i1.codies ' || coalesce(chr(13),'') || '  inner join ieslink L on i1.codies1 = L.codies1 ' || coalesce(chr(13),'') || '  inner join cmdlivrlink LL on L.codliniecomanda = LL.codcomanda1 ' || coalesce(chr(13),'') || '  inner join comanda1 c1 on LL.codliniecomanda = c1.codcomanda1 ' || coalesce(chr(13),'') || 'where 1=1 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I', 'SUBUNITATEA',NULL,NULL)),'') || ' group by c1.codcomanda1 ) ';
      sSelect := '
           select ComProd.CodComanda, ' || coalesce(chr(13),'') ||
           'ComProd.TipDoc, '           || coalesce(chr(13),'') ||
           'ComProd.CarnetDocProd, '    || coalesce(chr(13),'') ||
           'ComProd.NrDocProd, '        || coalesce(chr(13),'') ||
           'ComProd.DataDocProd, '      || coalesce(chr(13),'') ||
           'ComProd.SerieDocProd, '     || coalesce(chr(13),'') ||
           'ComProd.Produs, '           || coalesce(chr(13),'') ||
           'ComProd.Reteta, '           || coalesce(chr(13),'') ||
           'ComProd.TermenExec, '       || coalesce(chr(13),'') ||
           'ComProd.DenUM, '            || coalesce(chr(13),'') ||
           'ComProd.CantLansata, '      || coalesce(chr(13),'') ||
           'ComProd.PretLansat, '       || coalesce(chr(13),'') ||
           'ComProd.ValLansata, '       || coalesce(chr(13),'') ||
           'ComProd.CantRealiz, '       || coalesce(chr(13),'') ||
           'CantRealLC.Cant, '          || coalesce(chr(13),'') ||
           'ComProd.ValRealiz, '        || coalesce(chr(13),'') ||
           'ComProd.DifCant, '          || coalesce(chr(13),'') ||
           'ComProd.DifVal, '           || coalesce(chr(13),'') ||
           'ComCli.Client, '            || coalesce(chr(13),'') ||
           'ComCli.CarnetDocCli, '      || coalesce(chr(13),'') ||
           'ComCli.NrDocCli, '          || coalesce(chr(13),'') ||
           'ComCli.DataDocCli, '        || coalesce(chr(13),'') ||
           'ComCli.SerieDocCli, '       || coalesce(chr(13),'') ||
           'ComProd.Sectie, '           || coalesce(chr(13),'') ||
           'ComCli.TermenLivr, '        || coalesce(chr(13),'') ||
           'ComProd.Schimb, '           || coalesce(chr(13),'') ||
           'formatii.den_formatie, '    || coalesce(chr(13),'') ||
           'case when COALESCE(facturat.codcomanda1,0) = 0 then DL.cant    else facturat.cant    end, '       || coalesce(chr(13),'') ||
           'case when COALESCE(facturat.codcomanda1,0) = 0 then DL.nrdoc   else facturat.nrdoc   end, '       || coalesce(chr(13),'') ||
           'case when COALESCE(facturat.codcomanda1,0) = 0 then DL.datadoc else facturat.datadoc end, '       || coalesce(chr(13),'') ||
           'ComProd.ComClosed, '   || coalesce(chr(13),'') ||
           'ComSub.Subunitate, '   || coalesce(chr(13),'') ||
           'ComSub.SerieDocSub, '  || coalesce(chr(13),'') ||
           'ComSub.NrDocSub, '     || coalesce(chr(13),'') ||
           'ComSub.DataDocSub, '   || coalesce(chr(13),'') ||
           'ComProd.Saptamana, '   || coalesce(chr(13),'') ||
           'ComProd.ComCanceled, ' || coalesce(chr(13),'') ||
           'ComCli.ComClosed, '    || coalesce(chr(13),'') ||
           'ComCli.ComCanceled, '  || coalesce(chr(13),'') ||
           'comprod.comoperata '   || coalesce(gUserAlias,'') || '
            from ComProd
              inner join nartobj   produs    on produs.codobiect                 = comprod.codprodus
              inner join comanda   c         on c.codcomanda                     = ComProd.codcomanda
              inner join comanda1  c1        on c1.codcomanda1                   = ComProd.codcomanda1
              left join nartobj    component on component.codobiect              = comprod.codcomponent
              LEFT JOIN PRODCOMP   PC        ON PC.CODPRODCOMP                   = C1.CODRETETA
              left join formatii             on COALESCE(comprod.codformatie, 0) = formatii.codformatie
              left join tmp_comcli 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.codcomanda1c
              left join DL                   on DL.codcomanda1                   = comcli.codcomanda1
              left join cantrealLC           on cantreallc.codliniecomanda       = comprod.codcmdprodmat ' || gSuplJoins;
    END IF;
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_proglunfab_setjoinuri</obj_name>
  <obj_hashval>323749d455bf3657a4071f6c1c9ee4d2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_proglunfab_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 15.09.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_PROGLUNFAB.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rac_masinioc_setjoinuri</obj_name>
  <obj_hashval>da74cbcec11e304c875c2c25caff25a4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rac_masinioc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 06.06.2025 - sinc. Oracle
  --Adina 15.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_rac_masinioc.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rapconsprod_bagamaterialesemi</obj_name>
  <obj_hashval>3f6529146146ee3befb4126185be66c3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rapconsprod_bagamaterialesemi(aprodus numeric, anodparinte numeric, aparitate numeric, acodcomanda1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  N     RECORD;
BEGIN
  --Adina 17.02.2021 - add modif.Oracle din 16.02.2021
  --Adina 15 septembrie 2020
  if aParitate &lt; 0.0000001 then return; end if;
  FOR v_rec IN (WITH man_cons AS (
                    SELECT   aProdus PRODUS, ies1.codobiect MATERIAL, l1.cant, COALESCE(ns1.pretmat, 0) * l1.cant VALOARE, ns1.tipdoc,
                            COALESCE(ii1.codcmdint1, 0) CODCMDINT1, ies1.codies1, l1.codlivr1, ns.codnirstoc CODNIRSTOCPRED,
                            COALESCE(it1.cant, 0) CANTPRED, it1.codintr1,
                            CASE WHEN  ns1.tipdoc = 7 and  prod.tip = 0 THEN 1 ELSE 0 END  TIP
                    FROM   iesiri1                 ies1
                          INNER JOIN iesiri       ies  ON  ies1.codies        = ies.codies
                          INNER JOIN livr1        l1    ON  l1.codies1         = ies1.codies1
                          INNER JOIN livr         l     ON  l.codlivr          = l1.codlivr     and  ies.codies = l.codies
                          INNER JOIN nirstoc1     ns1  ON  l1.codnirstoc      = ns1.codnirstoc
                          INNER JOIN nirstoc      ns    ON  ns.codnirstoc      = ns1.codnirstocorig
                          LEFT  JOIN intrari1     ii1  ON  ii1.codintr1       = ns.codintr1
                          LEFT  JOIN intrari1     it1  ON  it1.codcmdint1     = ii1.codcmdint1 and  it1.codobiect = ies1.codobiect
                          LEFT  JOIN intrprodlink lk   ON  lk.codintr1        = it1.codintr1
                          LEFT  JOIN cmdprodmat   prod ON  prod.codcmdprodmat = lk.codliniecomanda
                    WHERE ies.operat = 1 and  COALESCE(ies.anulat, 0) = 0 and  ns1.tipdoc = 7 and  prod.tip = 0 and  ies1.codcmdint1 = aCodComanda1
                ),
                man_cons_mat AS (
                    SELECT   aProdus PRODUS, ies1.codobiect MATERIAL, l1.cant, COALESCE(ns1.pretmat, 0) * l1.cant VALOARE, ns1.tipdoc,
                            0 CODCMDINT1, ies1.codies1, l1.codlivr1, ns.codnirstoc CODNIRSTOCPRED,
                            COALESCE(it1.cant, 0) CANTPRED, it1.codintr1,
                            CASE WHEN  ns1.tipdoc = 7 and  prod.tip = 0 THEN 1 ELSE 0 END  TIP
                    FROM   iesiri1                 ies1
                          INNER JOIN iesiri       ies  ON  ies1.codies        = ies.codies
                          INNER JOIN livr1        l1    ON  l1.codies1         = ies1.codies1
                          INNER JOIN livr         l    ON  l.codlivr          = l1.codlivr     and  ies.codies = l.codies
                          INNER JOIN nirstoc1     ns1  ON  l1.codnirstoc      = ns1.codnirstoc
                          INNER JOIN nirstoc      ns    ON  ns.codnirstoc      = ns1.codnirstocorig
                          LEFT  JOIN intrari1     ii1  ON  ii1.codintr1       = ns.codintr1
                          LEFT  JOIN intrari1     it1  ON  it1.codcmdint1     = ii1.codcmdint1 and  it1.codobiect = ies1.codobiect
                          LEFT  JOIN intrprodlink lk   ON  lk.codintr1        = it1.codintr1
                          LEFT  JOIN cmdprodmat   prod ON  prod.codcmdprodmat = lk.codliniecomanda
                    WHERE ies.operat = 1 and  COALESCE(ies.anulat, 0) = 0 and  NOT (   ns1.tipdoc = 7 and  COALESCE(prod.tip, -1) = 0)  and  ies1.codcmdint1 = aCodComanda1
                )
                SELECT produs, material, sum(cant * aparitate) CANT, sum(valoare * aparitate) VALOARE, codcmdint1, totcons, totval, totpred, tip, codlivr1
                FROM (SELECT  DISTINCT man_cons_mat.produs, man_cons_mat.material, man_cons_mat.cant, man_cons_mat.valoare, man_cons_mat.codcmdint1,
                              tot_cons.cant TOTCONS, tot_cons.valoare TOTVAL, 0 TOTPRED, man_cons_mat.tip, man_cons_mat.codlivr1
                      FROM   man_cons_mat
                            INNER JOIN nartobj obj ON  obj.codobiect = man_cons_mat.material
                            INNER JOIN (SELECT sum(cant) CANT, material, produs, codcmdint1, tip, sum(valoare) VALOARE
                                        FROM (SELECT  DISTINCT cant, codlivr1, material, produs, codcmdint1, tip, valoare FROM man_cons_mat) A_PG
                                        GROUP BY material, produs, codcmdint1, tip
                                       ) tot_cons ON  tot_cons.material   = man_cons_mat.material   and
                                                       tot_cons.produs     = man_cons_mat.produs     and
                                                       tot_cons.codcmdint1 = man_cons_mat.codcmdint1 and
                                                       tot_cons.tip        = man_cons_mat.tip
                      union ALL
                      SELECT  DISTINCT man_cons.produs, man_cons.material, man_cons.cant, man_cons.valoare,
                              CASE WHEN  man_cons.tip = 1 THEN man_cons.codcmdint1 ELSE 0 END  CODCMDINT1,
                              tot_cons.cant TOTCONS, tot_cons.valoare TOTVAL, COALESCE(tot_pred.total, 0) TOTPRED, man_cons.tip, 0 CODLIVR1
                      FROM   man_cons
                            INNER JOIN nartobj obj ON  obj.codobiect = man_cons.material
                            INNER JOIN (SELECT sum(cant) CANT, material, produs, codcmdint1, tip, sum(valoare) VALOARE
                                        FROM (SELECT  DISTINCT cant, codlivr1, material, produs, codcmdint1, tip, valoare FROM man_cons) B_PG
                                        GROUP BY material, produs, codcmdint1, tip
                                       ) tot_cons ON  tot_cons.material   = man_cons.material   and
                                                       tot_cons.produs     = man_cons.produs     and
                                                       tot_cons.codcmdint1 = man_cons.codcmdint1 and
                                                       tot_cons.tip        = man_cons.tip
                            LEFT JOIN (SELECT sum(cantpred) TOTAL, material, produs, codcmdint1, tip
                                       FROM (SELECT  DISTINCT produs, material, codcmdint1, cantpred, codintr1, tip FROM man_cons WHERE tipdoc = 7 AND  TIP = 1) C_PG
                                       GROUP BY produs, material, codcmdint1, tip
                                      ) tot_pred ON  tot_pred.produs     = man_cons.produs     and
                                                     tot_pred.material   = man_cons.material   and
                                                     tot_pred.codcmdint1 = man_cons.codcmdint1 and
                                                     tot_pred.tip        = man_cons.tip
                      ) D_PG
                GROUP BY produs, material, codcmdint1, totcons, totpred, tip, totval, codlivr1
  )
  LOOP
    IF  v_rec.codcmdint1 &gt; 0 and  v_rec.tip = 1 THEN
      PERFORM pkg_list_base_rapconsprod_BagaMaterialeSemi(aprodus, v_rec.material, aParitate * v_rec.totcons / v_rec.totpred, v_rec.codcmdint1);
    ELSE
      FOR N IN (SELECT aProdus PRODUS, aNodParinte NODPARINTE, V_REC.MATERIAL MATERIAL, V_REC.cant CANT, V_REC.valoare VALOARE, v_rec.totcons TOTCONS, v_rec.totval TOTVAL)
      LOOP
        UPDATE  MANEVRA_CONSUM C
           SET CANT = COALESCE(C.CANT, 0) + N.CANT, VALOARE = COALESCE(C.VALOARE, 0) + N.VALOARE
        WHERE C.CODOBIECT = N.MATERIAL and  C.NODPARINTE = N.NODPARINTE and  C.PRODUS = N.PRODUS;

        IF NOT FOUND THEN
          INSERT INTO MANEVRA_CONSUM AS C (CODOBIECT, VALOARE, CANT, NODPARINTE, PRODUS) VALUES (N.MATERIAL, N.VALOARE, N.CANT, N.NODPARINTE, N.PRODUS) ;
        END IF;
      END LOOP;
    END IF;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rapconsumprod_processparams</obj_name>
  <obj_hashval>9467483f1cec15849f0fdb5c4945869a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rapconsumprod_processparams()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
BEGIN
  --Adina 15.10.2020
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN
  (
    SELECT P.Descriere
    FROM   TMP_RAPORTARE_CONSUM TMP
          INNER JOIN COMANDA1 C1 ON  C1.CODCOMANDA1 = TMP.CODCOMANDA1
          INNER JOIN PRODCOMP P  ON  C1.CODRETETA   = P.CODPRODCOMP
  )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Descriere', v_rec.descriere);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rapconsumprod_setjoinuri</obj_name>
  <obj_hashval>fbdfaa1974e42e7cf7f8bef403fa229c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rapconsumprod_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_RAPCONSUMPROD.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rapcreditcli_processlist</obj_name>
  <obj_hashval>3cdf8a5c9f7924237bdcd7f509c63084</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rapcreditcli_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;
  sTotalSold varchar;
  sCoefTvaCC varchar;
  vAnLunaC   NUMERIC;
  vAnPrec    NUMERIC;
  vLunaPrec  NUMERIC;
BEGIN
  --Adina 26.03.2021 - alstart, alstop
  --Bogdan 10.09.2020
  gSuplCols := 'NPART P, NPART1 P1, IOPART IOP, NAGENDA SSOC, NLOCALIT LSOC, NJUDET JSOC, NTARI TSOC, NPERS AG';

  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_RAPCREDITCLI.gSuplCols',gSuplCols,false);

  PERFORM pkg_NomPart_SET_CODPART_SOLD_ANALIZAT (0);

  SELECT ancurent * 12 + lunacurenta INTO vAnLunaC FROM FirmaLuni;

  select pkg_globals_CALCULEAZA_LUNA_PRECEDENTA.newan, pkg_globals_CALCULEAZA_LUNA_PRECEDENTA.newluna
  from pkg_globals_CALCULEAZA_LUNA_PRECEDENTA (getAnLucru(), getLunaLucru(), vAnPrec, vLunaPrec) into  vAnPrec, vLunaPrec;

  PERFORM pkg_globals_SetLunaPRECEDENTA (vAnPrec, vLunaPrec);

  PERFORM pkg_globals_SetLunaTemp (getAnLucru(), getLunaLucru());

  IF (getAnLunaLucru() &gt;= vAnLunaC ) THEN
    PERFORM PKG_INCHIDERI_MAKE_REST_OBLIGPIF_LUNA();
  END IF;

  IF Coalesce (fnc_GetValConstantalucru('SoldFaraCECNeinc'), '0') = '1'
  THEN sTotalSold := '(COALESCE(RESTFACT,0) + COALESCE(CECCURS,0) - COALESCE(INCAVANS,0) + COALESCE(AENEFACT,0) + COALESCE(AECUSTNEFACT,0))';
  ELSE sTotalSold := '(COALESCE(RESTFACT,0) - COALESCE(INCAVANS,0) + COALESCE(AENEFACT,0) + COALESCE(AECUSTNEFACT,0))';
  END IF;

  IF Coalesce (fnc_GetValConstantalucru('ModulCereale'), '2') = '1'
  THEN sCoefTvaCC := '*(1+CASE WHEN Trim(o.codd394) IS NOT NULL AND Upper(Trim(F.CodFiscal)) LIKE ''RO%'' THEN 0 ELSE COALESCE(tva1.procent/100,0) END)';
  ELSE sCoefTvaCC := '*(1+COALESCE(tva1.procent/100,0))';
  END IF;

  sInsert := 'INSERT INTO ' || tmpName
            || '( PART, LIMCREDIT, RESTFACT, CECCURS, INCAVANS, AENEFACT, AECUSTNEFACT, FACTNEOP, COMCURS ' || coalesce (gUserFields ,'') || ')
          WITH
          R AS
          ( SELECT DISTINCT R1.CODGENERAL,
                   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;= ' || coalesce (  getAnLunaLucru()::varchar  ,'') || '
          )
          ,
          SP AS
          ( SELECT O.CODPART,
              Sum (OL.REST * COALESCE (R.CURS, NULLIF (G.CURS,0) , 1) * CASE WHEN O.SEMNIFICATIE = 200 THEN 1 ELSE 0 END) RESTFACT,
              Sum (OL.REST * COALESCE (R.CURS, NULLIF (G.CURS,0) , 1) * CASE WHEN O.SEMNIFICATIE = 600 THEN 1 ELSE 0 END) CECCURS,
              Sum (OL.REST * COALESCE (R.CURS, NULLIF (G.CURS,0) , 1) * CASE WHEN O.SEMNIFICATIE IN (210,410) THEN 1 WHEN O.SEMNIFICATIE = 330 THEN -1 ELSE 0 END) INCAVANS,
              Sum (OL.REST * COALESCE (R.CURS, NULLIF (G.CURS,0) , 1) * CASE WHEN O.SEMNIFICATIE = 240 AND G.TIPDOC = 20 AND COALESCE (I.CUSTODIE,0) = 0 THEN 1 ELSE 0 END) AENEFACT
            FROM OBLIGPIFLUNA     OL
              INNER JOIN OBLIGPIF O ON O.CODOBLIGPIF = OL.CODOBLIGPIF
              INNER JOIN GENERAL  G ON G.CODGENERAL  = O.CODGENERAL
              LEFT JOIN IESIRI    I ON I.CODIES      = G.CODDOC AND I.TIPDOC = G.TIPDOC
              LEFT JOIN (SELECT SUM (V1.PU * (V1.CANT - COALESCE (ST.CANT,0))) REST, V.CODIES
                         FROM IESIRI             V
                              INNER JOIN IESIRI1 V1 ON V.CODIES = V1.CODIES
                              LEFT  JOIN (SELECT SUM (L.CANT) CANT, L.CODLINIEAVIZ FROM IESLINK L GROUP BY L.CODLINIEAVIZ) ST ON ST.CODLINIEAVIZ = V1.CODIES1
                         WHERE V.TIPDOC = 20 AND V.CUSTODIE = 1
                         GROUP BY V.CODIES
                        ) CUST ON CUST.CODIES  = I.CODIES
              LEFT JOIN   R    ON R.CODGENERAL = G.CODGENERAL
            WHERE O.SEMNIFICATIE IN (200, 210, 240, 330, 410, 600) AND OL.AN = ' || coalesce (getAnLucru()::varchar,'') || ' AND OL.LUNA = ' || coalesce (getLunaLucru()::varchar,'') || '
            GROUP BY O.CODPART
          )
          ,
          FN AS
          ( SELECT Partener, SUM (Valdoc) FACTNEOP
            FROM iesiri
            WHERE tipdoc IN (19, 26) AND operat = 0 AND anulat = 0 AND an * 12 + luna &lt;= ' || coalesce (  getAnLunaLucru()::varchar  ,'') || '
            GROUP BY Partener
          )
          ,
          CC AS
          ( SELECT C.Partener, SUM (c1.restacceptat * c1.pretorig * coalesce (c1.coefdiscmaj,1) ' || coalesce (sCoefTvaCC,'') || ') COMCURS
            FROM comanda c
              INNER JOIN comanda1     c1   ON c1.codcomanda   = c.codcomanda
              INNER JOIN nartobj      o    ON o.codobiect     = c1.codobiect
              LEFT  JOIN npartcodfisc f    ON f.cod_codfiscal = c.codfiscal
              LEFT  JOIN nart1        a1   ON a1.codarticol   = o.codarticol AND ' || coalesce ( getAnLunaLucru()::varchar ,'') || ' BETWEEN   a1.ALSTART and   a1.ALSTOP
              LEFT  JOIN ntva1        tva1 ON tva1.codtva     = a1.codtva    AND ' || coalesce ( getAnLunaLucru()::varchar ,'') || ' BETWEEN tva1.ALSTART and tva1.ALSTOP
            WHERE c.tipdoc = 18 AND c.operat = 1 AND c.anulat = 0 and coalesce (c.inchisa,0) = 0 AND c1.restacceptat &gt; 0
              AND c.an * 12 + c.luna &lt;= ' || coalesce (  getAnLunaLucru()::varchar ,'') || '
            GROUP BY C.Partener
          )
          SELECT P.DEN_PART, P1.CREDITCLIENT, COALESCE (SP.RESTFACT,0), COALESCE (SP.CECCURS,0), COALESCE (SP.INCAVANS,0), COALESCE (SP.AENEFACT,0),
                 (SELECT COALESCE (SUM (v1.pu * v1.cant) ,0)
                  FROM IESIRI V INNER JOIN IESIRI1 V1 ON V.CODIES = V1.CODIES
                  WHERE V.TIPDOC = 20 AND V.CUSTODIE = 1 AND V.PARTENER = P.CODPART
                 )
                 - (SELECT COALESCE (SUM (v1.pu * l.cant) ,0)
                    FROM IESIRI          V
                      INNER JOIN IESIRI1 V1 ON V.CODIES       = V1.CODIES
                      INNER JOIN IESLINK L  ON L.CODLINIEAVIZ = V1.CODIES1
                      INNER JOIN IESIRI1 I1 ON I1.CODIES1     = L.CODIES1
                      INNER JOIN IESIRI  I  ON I.CODIES       = I1.CODIES
                    WHERE V.TIPDOC = 20 AND V.CUSTODIE = 1 AND V.PARTENER = P.CODPART
                      AND I.AN * 12 + I.LUNA &lt;= ' || coalesce (  getAnLunaLucru()::varchar  ,'') || ' AND I.OPERAT = 1 AND I.ANULAT = 0
                   ) AECUSTNEFACT,
                 COALESCE (FN.FACTNEOP,0) ,
                 COALESCE (CC.COMCURS,0) ' || coalesce (gUserAlias ,'') || '
          FROM NPART1             P1
              INNER JOIN NPART    P    ON P.CODPART       = P1.CODPART AND ' || coalesce ( getAnLunaLucru()::varchar ,'') || ' BETWEEN P1.ALSTART and P1.ALSTOP
              LEFT  JOIN IOPART   IOP  ON IOP.CODIOPART   = P1.CODIOPART
              LEFT  JOIN NAGENDA  SSOC ON SSOC.CODPART    = P1.CODPART AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND COALESCE (SSOC.INACTIV, 0) = 0
              LEFT  JOIN NLOCALIT LSOC ON LSOC.CODLOCALIT = COALESCE (SSOC.CODLOCALIT, 0)
              LEFT  JOIN NJUDET   JSOC ON JSOC.CODJUDET   = COALESCE (LSOC.CODJUDET  , 0)
              LEFT  JOIN NTARI    TSOC ON TSOC.CODTARA    = COALESCE (LSOC.CODTARA   , 0)
              LEFT  JOIN NPERS    AG   ON AG.CODPERS      = COALESCE (SSOC.CODAGENT  , 0)
              LEFT  JOIN SP            ON SP.CODPART      = P1.CODPART
              LEFT  JOIN FN            ON FN.PARTENER     = P1.CODPART
              LEFT  JOIN CC            ON CC.PARTENER     = P1.CODPART'
              || coalesce (gSuplJoins ,'') || '
          WHERE P1.CREDITCLIENT &lt;&gt; 0';

  PERFORM LIST_EXECUTE_IMMEDIATE (sInsert, aListID, aListVer);
  EXECUTE 'UPDATE ' || coalesce (tmpName,'') || ' SET TOTALSOLD = ' || coalesce (sTotalSold,'') || ', RESTCREDIT = LIMCREDIT - ' || coalesce (sTotalSold,'');
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_raportcumparari_setparams</obj_name>
  <obj_hashval>8ae62e90e34f72366f4985d28c7df363</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportcumparari_setparams(ptipdata numeric, pinceput character varying, psfarsit character varying, ptiptarget numeric, pvaluta numeric, pcatpret numeric, pallpart numeric, v_codjob1 numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAuxData   date;
  vAuxData1  date;
  xLunaAnIni NUMERIC;
  xLunaAnFin NUMERIC;
  sDataS     varchar;
  sDataF     varchar;
BEGIN
  --Florin 26.01.2022 - fixat 52779
  --Florin 31.08.2020
  PERFORM set_config('PKG_LIST_BASE_RAPORTCUMPARARI.vTipTarget', pTipTarget::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_RAPORTCUMPARARI.vValuta'   , ((COALESCE(pValuta, 0) = 1)::varchar), FALSE);
  PERFORM set_config('PKG_LIST_BASE_RAPORTCUMPARARI.vCatPret'  , pCatPret::varchar, FALSE);
  PERFORM set_config('PKG_LIST_BASE_RAPORTCUMPARARI.vAllPart'  , pAllPart::varchar, FALSE);
  sDataS := pInceput;
  sDataF := pSfarsit;
  PERFORM set_config('PKG_LIST_BASE_RAPORTCUMPARARI.vTipData', (COALESCE(pTipData, 0) = 1)::varchar,false);

  IF COALESCE(pTipData, 0) = 1 THEN
    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'));
    PERFORM set_config('PKG_LIST_BASE_RAPORTCUMPARARI.vInceput', 'To_Date(''' || sDataS || ''', ''dd.mm.yyyy'')', FALSE);
    PERFORM set_config('PKG_LIST_BASE_RAPORTCUMPARARI.vSfarsit', 'To_Date(''' || sDataF || ''', ''dd.mm.yyyy'')', FALSE);

    IF COALESCE(v_CodJob1, 0) &gt; 0 THEN
      PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, current_setting('PKG_LIST_BASE_RAPORTCUMPARARI.vInceput', true), current_setting('PKG_LIST_BASE_RAPORTCUMPARARI.vSfarsit', true), xLunaAnIni, xLunaAnFin);
    END IF;

    PERFORM set_config('PKG_LIST_BASE_RAPORTCUMPARARI.xInceput', current_setting('PKG_LIST_BASE_RAPORTCUMPARARI.vInceput', TRUE), FALSE);
    PERFORM set_config('PKG_LIST_BASE_RAPORTCUMPARARI.xSfarsit', current_setting('PKG_LIST_BASE_RAPORTCUMPARARI.vSfarsit', TRUE), FALSE);
  ELSE
    xLunaAnIni := getanlucru() * 12 + sDataS::NUMERIC;
    xLunaAnFin := getanlucru() * 12 + sDataF::NUMERIC;
    PERFORM set_config('PKG_LIST_BASE_RAPORTCUMPARARI.vInceput', sDataS, FALSE);
    PERFORM set_config('PKG_LIST_BASE_RAPORTCUMPARARI.vSfarsit', sDataF, FALSE);
    vAuxData := DATE_TRUNC('MONTH',To_Date(coalesce(getanlucru(), 0) || '.' || coalesce(sDataS,''), 'yyyy.mm'));
    vAuxData1 := TO_DATE(TO_CHAR(DATE_TRUNC('MONTH',To_Date(COALESCE(getanlucru(), 0)::varchar || '.' || coalesce(sDataF,''), 'yyyy.mm')), 'dd.mm.yyyy'), 'dd.mm.yyyy');
    IF COALESCE(v_CodJob1, 0) &gt; 0 THEN
      PERFORM PKG_ORA_LISTS_SET_INTERVAL_DINAMIC(V_CODJOB1, vAuxData, vAuxData1, xLunaAnIni, xLunaAnFin);
    END IF;
    PERFORM set_config('PKG_LIST_BASE_RAPORTCUMPARARI.xInceput', 'To_Date(''' || vAuxData::varchar  ||''',''dd-mm-yyyy'')', FALSE);
    PERFORM set_config('PKG_LIST_BASE_RAPORTCUMPARARI.xSfarsit', 'To_Date(''' || vAuxData1::varchar ||''',''dd-mm-yyyy'')', FALSE);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_raportgestpmp_processlist</obj_name>
  <obj_hashval>5ccdbecfc4053728809ef5905febccd5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportgestpmp_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sDebug      varchar :='';
  sInsert     varchar :='';
  sSelect     varchar :='';
  sDataIni    varchar := coalesce(to_char((SELECT WME_RESULT FROM PKG_LIST_SELECTGEST2_ZiuaIni(NULL,NULL)), 'fm00'),'') || '.' || coalesce(to_char(getlunalucru(), 'fm00'),'') || '.' || coalesce(to_char(getanlucru(), 'fm0000'),'');
  sDataFin    varchar := coalesce(to_char((SELECT WME_RESULT FROM PKG_LIST_SELECTGEST2_ZiuaFin(NULL,NULL)), 'fm00'),'') || '.' || coalesce(to_char(getlunalucru(), 'fm00'),'') || '.' || coalesce(to_char(getanlucru(), 'fm0000'),'');
  sCondData   varchar :='';
  sTipPMP     varchar :='';
  vTipPmp     numeric;
BEGIN
  --Stef   01.03.2023
  --Florin 20.02.2023 - fixat 52282
  --ADina 07.04.2021 - alstart,alstop
  --Adina iulie 2020
   sTipPMP := Coalesce(fnc_GetValConstanta('TipPMP', getANLUCRU(), getLUNALUCRU()), '1');
   vTipPmp := sTipPMP::numeric;

   IF  (SELECT WME_RESULT FROM PKG_LIST_SELECTGEST2_ZiuaIni(NULL,NULL)) = (SELECT WME_RESULT FROM PKG_LIST_SELECTGEST2_ZiuaFin(NULL,NULL)) THEN
    sCondData := ' = to_date(''' || coalesce(sDataIni,'') || ''',''DD.MM.YYYY'') ';
   ELSE
    sCondData := ' BETWEEN to_date(''' || coalesce(sDataIni,'') || ''',''DD.MM.YYYY'') AND to_date(''' || coalesce(sDataFin,'') || ''',''DD.MM.YYYY'') ';
   END IF;

   sInsert :=
    'INSERT INTO '||tmpName||' (
      NAV_CodDoc, NAV_TipDoc, PrefixDoc, NrDoc, DataDoc, Document, TipDoc,
      ValDFTVA, ValCFTVA, SoldFinFTVA,
      SursaDest, DenIOART,
      DenGest, DenCONT, SimbCONT, RecLivr, Zi, ZiDoc )';

   sSelect := '
  WITH
      IOA AS (
        SELECT IO.CODIOART, IO.DEN_IOART, C.DEN_CONT, C.SIMBOL SIMB_CONT
        FROM ioart1 io1
          INNER JOIN ioart io  ON io.codioart = io1.codioart AND '||getAnLunaLucru()::varchar||' BETWEEN io1.ALStart and io1.ALStop
          LEFT  JOIN ncont c   ON c.codcont   = io1.cont
        WHERE IO1.MG = 3
      ),
      SM AS (
        SELECT CODOBIECT, CODIOART, GEST, SUBUNITATEA, SUM (REST*PRET) VAL
        FROM   (
          SELECT
            NS.CODOBIECT, N.GEST, NS.CODIOART, G.CODSUBUNIT SUBUNITATEA, NL.REST,
            CASE WHEN COALESCE(P.PMPPREC,0) = 0 THEN NS.PRET - COALESCE(NS.ADAOS,0) ELSE P.PMPPREC END PRET
          FROM NIRLUNA NL
            INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = NL.CODNIRSTOC
            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 '||
            coalesce((PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT',NULL,NULL))::varchar,'')||
            coalesce((select wme_result from pkg_list_base_raportgestpmp_JOINTMP('','N.GEST'))::varchar,'')||'
            LEFT JOIN tmp_pmp p ON P.CODOBIECT = NS.CODOBIECT'||CASE WHEN vTipPmp &lt;&gt; 1 THEN ' AND P.CODSUBUNIT = G.CODSUBUNIT' else '' END||'
          WHERE (NL.AN * 12 + NL.LUNA + 1) = '||getAnLunaLucru()::varchar||'
          UNION ALL
          SELECT
            NS.CODOBIECT, N.GEST, NS.CODIOART, I.SUBUNITATEA, NS.CANTNIR REST,
            NS.PRET - COALESCE(NS.ADAOS,0) PRET
          FROM NIRSTOC NS
            INNER JOIN IOA       ON IOA.CODIOART = NS.CODIOART
            INNER JOIN NIR     N ON N.CODNIR     = NS.CODNIR'||coalesce((select wme_result from pkg_list_base_raportgestpmp_JOINTMP('','N.GEST'))::varchar,'')||'
            INNER JOIN INTRARI I ON I.CODINTR    = N.CODINTR
          WHERE I.TIPDOC IN (1, 2, 3, 4, 5, 6, 7) AND I.ANULAT = 0 AND I.OPERAT = 1
            AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
            AND N.DATANIR &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'') '||
            coalesce((PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,NULL,NULL))::varchar,'')||'
          UNION ALL
          SELECT
            NS.CODOBIECT, N.GEST, NS.CODIOART, T.SUBUNITATEA, NS.CANTNIR REST,
            CASE WHEN COALESCE(P.PMP,0) = 0 THEN NS.PRET - COALESCE(NS.ADAOS,0) ELSE P.PMPPREC END PRET
          FROM NIRSTOC NS
            INNER JOIN IOA       ON IOA.CODIOART = NS.CODIOART
            INNER JOIN NIR     N ON N.CODNIR     = NS.CODNIR' ||coalesce((select wme_result from pkg_list_base_raportgestpmp_JOINTMP('','N.GEST'))::varchar,'')||'
            INNER JOIN TRANSF  T ON T.CODTRANSF  = N.CODTRANSF
            LEFT  JOIN tmp_pmp p ON P.CODOBIECT  = NS.CODOBIECT' ||CASE WHEN vTipPmp &lt;&gt; 1 THEN ' AND P.CODSUBUNIT = T.SUBUNITATEA' else '' END||'
          WHERE T.TIPDOC IN (12, 13) AND T.ANULAT = 0 AND T.OPERAT = 1 AND N.OPERAT = 1
            AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
            AND N.DATANIR &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'') '||
            coalesce((PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',null,NULL,NULL))::varchar,'')||'
          UNION ALL
          SELECT
            NS.CODOBIECT, N.GEST, NS.CODIOART, I.SUBUNITATEA, - L1.CANT REST,
            CASE WHEN COALESCE(P.PMP,0) = 0 THEN NS.PRET - COALESCE(NS.ADAOS,0) ELSE P.PMPPREC END PRET
          FROM LIVR1 L1
            INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
            INNER JOIN IOA        ON IOA.CODIOART  = NS.CODIOART
            INNER JOIN NIR     N  ON N.CODNIR      = NS.CODNIR' ||coalesce((select wme_result from pkg_list_base_raportgestpmp_JOINTMP('','N.GEST'))::varchar,'')||'
            INNER JOIN LIVR    L  ON L.CODLIVR     = L1.CODLIVR
            INNER JOIN INTRARI I  ON I.CODINTR     = L.CODINTR
            LEFT  JOIN tmp_pmp p  ON P.CODOBIECT   = NS.CODOBIECT' ||CASE WHEN vTipPmp &lt;&gt; 1 THEN ' AND P.CODSUBUNIT = I.SUBUNITATEA' else '' END||'
          WHERE I.TIPDOC IN (1, 2, 3, 4, 5, 6, 7) AND I.OPERAT = 1 AND I.ANULAT = 0
            AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
            AND L.DATALIVR &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'') '||
            coalesce((PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,NULL,NULL))::varchar,'')||'
          UNION ALL
          SELECT
            NS.CODOBIECT, N.GEST, NS.CODIOART, T.SUBUNITATEA, - L1.CANT REST,
            CASE WHEN COALESCE(P.PMP,0) = 0 THEN NS.PRET - COALESCE(NS.ADAOS,0) ELSE P.PMPPREC END PRET
          FROM LIVR1 L1
            INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
            INNER JOIN IOA        ON IOA.CODIOART  = NS.CODIOART
            INNER JOIN NIR     N  ON N.CODNIR      = NS.CODNIR'||coalesce((select wme_result from pkg_list_base_raportgestpmp_JOINTMP('','N.GEST'))::varchar,'')||'
            INNER JOIN LIVR    L  ON L.CODLIVR     = L1.CODLIVR
            INNER JOIN TRANSF  T  ON T.CODTRANSF   = L.CODTRANSF
            LEFT  JOIN tmp_pmp p  ON P.CODOBIECT   = NS.CODOBIECT'||CASE WHEN vTipPmp &lt;&gt; 1 THEN ' AND P.CODSUBUNIT = T.SUBUNITATEA' else '' END||'
          WHERE T.CODTRANSF IN (12, 13) AND T.OPERAT = 1 AND T.ANULAT = 0
            AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
            AND L.DATALIVR &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'') '||
            coalesce((PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',null,NULL,NULL))::varchar,'')||'
          UNION ALL
          SELECT
            NS.CODOBIECT, N.GEST, NS.CODIOART, I.SUBUNITATEA, (case when I.TIPDOC=15 then 1 else -1 end) * L1.CANT REST,
            CASE
              WHEN I.TIPDOC = 23 AND '||vTipPmp::varchar||'=1 THEN NS.PRET - COALESCE(NS.ADAOS,0)
              WHEN I.TIPDOC = 15 THEN NS.PRET - COALESCE(NS.ADAOS,0)
              WHEN I.TIPDOC = 14 AND L1.CANT &lt; 0 AND N.CODIES = I.CODIES THEN NS.PRET - COALESCE(NS.ADAOS,0)
              WHEN COALESCE(P.PMP,0) = 0 THEN NS.PRET - COALESCE(NS.ADAOS,0)
              ELSE P.PMP
            END PRET
          FROM LIVR1 L1
            INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
            INNER JOIN IOA        ON IOA.CODIOART  = NS.CODIOART
            INNER JOIN NIR     N  ON N.CODNIR      = NS.CODNIR'||coalesce((select wme_result from pkg_list_base_raportgestpmp_JOINTMP('','N.GEST'))::varchar,'')||'
            INNER JOIN LIVR    L  ON L.CODLIVR     = L1.CODLIVR
            INNER JOIN IESIRI  I  ON I.CODIES      = L.CODIES
            LEFT  JOIN tmp_pmp p  ON P.CODOBIECT   = NS.CODOBIECT'||CASE WHEN vTipPmp &lt;&gt; 1 THEN ' AND P.CODSUBUNIT = I.SUBUNITATEA' else '' END||'
          WHERE I.TIPDOC IN (14, 15, 16, 19, 20, 21, 22, 23, 24) AND I.OPERAT = 1 AND I.ANULAT = 0
            AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
            AND L.DATALIVR &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'') '||
            coalesce((PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,NULL,NULL))::varchar,'')||'
        ) a_pg
        GROUP BY CODOBIECT, GEST, CODIOART, SUBUNITATEA
      )
      --END WITH
      SELECT
        NULL CodDoc, NULL TipDoc, '' '' PrefixDoc, NULL NrDoc, to_date('''||sDataIni||''',''DD.MM.YYYY'') DataDoc, ''Sold initial'' Doc, '' '' TipDoc,
        0 ValDFTva, 0 ValCFTva,
        SUM(SM.VAL) SoldFinFTva,
        NULL SursaDest, IOA.DEN_IOART, NG.DEN_GEST, IOA.DEN_CONT, IOA.SIMB_CONT,
        NULL RecLivr, 0 Zi, 0 ZiDoc
      FROM SM
        INNER JOIN IOA        ON IOA.CODIOART = SM.CODIOART
        INNER JOIN NGEST   NG ON NG.CODGEST   = SM.GEST
        LEFT  JOIN tmp_pmp p  ON P.CODOBIECT  = SM.CODOBIECT'||CASE WHEN vTipPmp &lt;&gt; 1 THEN ' AND P.CODSUBUNIT = SM.SUBUNITATEA' else '' END||'
      GROUP BY NG.DEN_GEST, IOA.DEN_IOART, IOA.DEN_CONT, IOA.SIMB_CONT
      UNION ALL -- INTRARI
      SELECT
        I.CODINTR CodDoc, I.TIPDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC,
      --i.prefixdoc ||i.seriadoc||i.nrdoc ||''/''||to_char(i.datadoc,''dd.mm.yyyy'') Doc,
        coalesce(i.prefixdoc,'''') ||coalesce(i.seriadoc,'''')||coalesce(i.nrdoc::varchar,'''') ||''/''||coalesce(to_char(i.datadoc,''dd.mm.yyyy''),'''') Doc,
        coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',I.TIPDOC)),''''),
        SUM(NS.CANTNIR * (NS.PRET - COALESCE(NS.ADAOS,0))) ValDFTva, 0 ValCFTva,
        SUM(NS.CANTNIR * (NS.PRET - COALESCE(NS.ADAOS,0))) SoldFinFTva,
        (case when I.TIPDOC=6 then S.DEN_SUBUNIT when I.TIPDOC=7 then G.DEN_GEST else NP.DEN_PART end) SursaDest, IOA.DEN_IOART, NG.DEN_GEST, IOA.DEN_CONT, IOA.SIMB_CONT,
        N.NRNIR||''/''||to_char(N.DATANIR,''dd.mm.yyyy'') RecLivr, TO_CHAR(N.DATANIR,''DD'')::numeric Zi, TO_CHAR(I.DATADOC,''DD'')::numeric ZiDoc
      FROM NIRSTOC NS
        INNER JOIN IOA         ON IOA.CODIOART = NS.CODIOART
        INNER JOIN NIR      N  ON N.CODNIR     = NS.CODNIR'||coalesce((select wme_result from pkg_list_base_raportgestpmp_JOINTMP('','N.GEST'))::varchar,'')||'
        INNER JOIN NGEST    NG ON NG.CODGEST   = N.GEST '|| coalesce((PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG','CODSUBUNIT',NULL,NULL))::varchar,'')||'
        INNER JOIN INTRARI  I  ON I.CODINTR    = N.CODINTR
        LEFT  JOIN NPART    NP ON NP.CODPART   = I.PARTENER
        LEFT  JOIN NGEST    G  ON G.CODGEST    = I.CODGESTPROD
        LEFT  JOIN NSUBUNIT S  ON S.CODSUBUNIT = I.CODSUBUNIT
      WHERE I.TIPDOC IN (1, 2, 3, 4, 5, 6, 7) AND I.ANULAT = 0 AND I.OPERAT = 1
        AND N.DATANIR'||sCondData||'
        AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
      GROUP BY I.CODINTR, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC, N.NRNIR, N.DATANIR, IOA.DEN_IOART, IOA.DEN_CONT, IOA.SIMB_CONT, NG.DEN_GEST, NP.DEN_PART, S.DEN_SUBUNIT, G.DEN_GEST
      UNION ALL -- INTRARI DIN TRANSFERURI
      SELECT
        T.CODTRANSF CodDoc, T.TIPDOC, T.PREFIXDOC, T.NRDOC, T.DATADOC,
      --t.prefixdoc ||t.seriadoc||t.nrdoc||''/''||to_char(t.datadoc,''dd.mm.yyyy'') Doc,
        coalesce(t.prefixdoc,'''') ||coalesce(t.seriadoc,'''')||coalesce(t.nrdoc::varchar,'''')||''/''||coalesce(to_char(t.datadoc,''dd.mm.yyyy''),'''') Doc,
        coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',T.TIPDOC)),''''),
        SUM(NS.CANTNIR *(case when COALESCE(P.PMP,0)=0 then NS.PRET - COALESCE(NS.ADAOS,0) else P.PMP end)) ValDFTva, 0 ValCFTva,
        SUM(NS.CANTNIR * (case when COALESCE(P.PMP,0)=0 then NS.PRET - COALESCE(NS.ADAOS,0) else P.PMP end)) SoldFinFTva,
        NG_S.DEN_GEST SursaDest, IOA.DEN_IOART, NG.DEN_GEST, IOA.DEN_CONT, IOA.SIMB_CONT,
        N.NRNIR||''/''||to_char(N.DATANIR,''dd.mm.yyyy'') RecLivr, TO_CHAR(N.DATANIR'||',''DD'')::numeric Zi, TO_CHAR(T.DATADOC,''DD'')::numeric ZiDoc
      FROM TRANSF T
        INNER JOIN NIR     N    ON N.CODTRANSF     = T.CODTRANSF'||coalesce((select wme_result from pkg_list_base_raportgestpmp_JOINTMP('','N.GEST'))::varchar,'')||'
        INNER JOIN NIRSTOC NS   ON NS.CODNIR       = N.CODNIR
        INNER JOIN IOA          ON IOA.CODIOART    = NS.CODIOART
        INNER JOIN NGEST   NG   ON NG.CODGEST      = N.GEST '|| coalesce((PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG','CODSUBUNIT',NULL,NULL))::varchar,'')||'
        LEFT  JOIN tmp_pmp p    ON P.CODOBIECT     = NS.CODOBIECT'||CASE WHEN vTipPmp &lt;&gt; 1 THEN ' AND P.CODSUBUNIT = NG.CODSUBUNIT' else '' END||'
        LEFT  JOIN NIRSTOC NS_S ON NS_S.CODNIRSTOC = NS.CODNIRSTOCPARINTE AND (NS.CODNIRSTOCPARINTE IS NOT NULL)
        LEFT  JOIN NIR     N_S  ON N_S.CODNIR      = NS_S.CODNIR
        LEFT  JOIN LIVRVAL LV_S ON LV_S.CODLIVR1   = NS.CODLIVR1
        LEFT  JOIN NGEST   NG_S ON NG_S.CODGEST    = COALESCE(N_S.GEST,LV_S.GEST)
      WHERE T.TIPDOC = 12 AND T.ANULAT = 0 AND T.OPERAT = 1 AND N.OPERAT = 1
        AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
        AND N.DATANIR'||sCondData||'
      GROUP BY T.CODTRANSF, T.TIPDOC, T.PREFIXDOC, T.SERIADOC, T.NRDOC, T.DATADOC, N.NRNIR, N.DATANIR, IOA.DEN_IOART, IOA.DEN_CONT, IOA.SIMB_CONT, NG.DEN_GEST, NG_S.DEN_GEST
      UNION ALL -- IESIRI PRIN TRANSFER STOC
      SELECT
        T.CODTRANSF CodDoc, T.TIPDOC, T.PREFIXDOC, T.NRDOC, T.DATADOC,
        coalesce(t.prefixdoc,'''') ||coalesce(t.seriadoc,'''')||coalesce(t.nrdoc::varchar,'''')||''/''||coalesce(to_char(t.datadoc,''dd.mm.yyyy''),'''') Doc,
        coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',T.TIPDOC)),''''),
        0 ValDFTva, SUM(L1.CANT * (case when COALESCE(P.PMP,0)=0 then NS.PRET - COALESCE(NS.ADAOS,0) else P.PMP end)) ValCFTva,
        -SUM(L1.CANT * (case when COALESCE(P.PMP,0)=0 then NS.PRET - COALESCE(NS.ADAOS,0) else P.PMP end)) SoldFinFTva,
        NG_D.DEN_GEST SursaDest, IOA.DEN_IOART, NG.DEN_GEST, IOA.DEN_CONT, IOA.SIMB_CONT,
        L.NRLIVR||''/''||to_char(L.DATALIVR,''dd.mm.yyyy'') RecLivr, TO_CHAR(L.DATALIVR,''DD'')::numeric Zi, TO_CHAR(T.DATADOC,''DD'')::numeric ZiDoc
      FROM TRANSF T
        INNER JOIN LIVR    L    ON L.CODTRANSF   = T.CODTRANSF
        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'||coalesce((select wme_result from pkg_list_base_raportgestpmp_JOINTMP('','N.GEST'))::varchar,'')||'
        INNER JOIN IOA          ON IOA.CODIOART  = NS.CODIOART
        INNER JOIN NGEST   NG   ON NG.CODGEST    = N.GEST '|| coalesce((PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG','CODSUBUNIT',NULL,NULL))::varchar,'')||'
        LEFT  JOIN tmp_pmp p    ON P.CODOBIECT   = NS.CODOBIECT'||CASE WHEN vTipPmp &lt;&gt; 1 THEN ' AND P.CODSUBUNIT = NG.CODSUBUNIT' else '' END||'
        LEFT  JOIN NIRSTOC NS_D ON NS_D.CODLIVR1 = L1.CODLIVR1
        LEFT  JOIN NIR     N_D  ON N_D.CODNIR    = NS_D.CODNIR
        LEFT  JOIN NGEST   NG_D ON NG_D.CODGEST  = N_D.GEST
      WHERE T.TIPDOC = 12 AND T.OPERAT = 1 AND T.ANULAT = 0
        AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
        AND L.DATALIVR'||sCondData||'
      GROUP BY T.CODTRANSF, T.TIPDOC, T.PREFIXDOC, T.SERIADOC, T.NRDOC, T.DATADOC,  L.NRLIVR, L.DATALIVR, IOA.DEN_IOART, IOA.DEN_CONT, IOA.SIMB_CONT, NG.DEN_GEST, NG_D.DEN_GEST
      UNION ALL -- MODIFICARI DE PRET
      SELECT
        T.CODTRANSF CodDoc, T.TIPDOC, T.PREFIXDOC, T.NRDOC, T.DATADOC,
        coalesce(t.prefixdoc,'''') ||coalesce(t.seriadoc,'''')||coalesce(t.nrdoc::varchar,'''')||''/''||coalesce(to_char(t.datadoc,''dd.mm.yyyy''),'''') Doc,
        coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',T.TIPDOC)),''''),
        SUM(NS.CANTNIR * (NS.PRET - COALESCE(NS.ADAOS,0))) ValDFTva, SUM(NS.CANTNIR * (case when COALESCE(P.PMP,0)=0 then NS.PRET - COALESCE(NS.ADAOS,0) else P.PMP end)) ValCFTva,
        SUM(NS.CANTNIR * ((NS.PRET - COALESCE(NS.ADAOS,0)) - (case when COALESCE(P.PMP,0)=0 then NS.PRET - COALESCE(NS.ADAOS,0) else P.PMP end))) SoldFinFTva,
        NG.DEN_GEST SursaDest, IOA.DEN_IOART,
        NG.DEN_GEST, IOA.DEN_CONT, IOA.SIMB_CONT,
        N.NRNIR||''/''||to_char(N.DATANIR,''dd.mm.yyyy'') RecLivr, TO_CHAR(N.DATANIR'||',''DD'')::numeric Zi, TO_CHAR(T.DATADOC,''DD'')::numeric ZiDoc
      FROM TRANSF T
        INNER JOIN NIR     N  ON N.CODTRANSF  = T.CODTRANSF'||coalesce((select wme_result from pkg_list_base_raportgestpmp_JOINTMP('','N.GEST'))::varchar,'')||'
        INNER JOIN NIRSTOC NS ON NS.CODNIR    = N.CODNIR
        INNER JOIN IOA        ON IOA.CODIOART = NS.CODIOART
        INNER JOIN NGEST   NG ON NG.CODGEST   = N.GEST '|| coalesce((PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG','CODSUBUNIT',NULL,NULL))::varchar,'')||'
        LEFT  JOIN tmp_pmp p  ON P.CODOBIECT  = NS.CODOBIECT'||CASE WHEN vTipPmp &lt;&gt; 1 THEN ' AND P.CODSUBUNIT = NG.CODSUBUNIT' else '' END||'
      WHERE T.TIPDOC = 13 AND T.ANULAT = 0 AND T.OPERAT = 1 AND N.OPERAT = 1
        AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
        AND N.DATANIR'||sCondData||'
      GROUP BY T.CODTRANSF, T.TIPDOC, T.PREFIXDOC, T.SERIADOC, T.NRDOC, T.DATADOC, N.NRNIR, N.DATANIR, IOA.DEN_IOART, IOA.DEN_CONT, IOA.SIMB_CONT, NG.DEN_GEST
      UNION ALL -- RETUR INTRARI STOC
      SELECT
        I.CODINTR CodDoc, I.TIPDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC,
        coalesce(i.prefixdoc,'''') ||coalesce(i.seriadoc,'''')||coalesce(i.nrdoc::varchar,'''') ||''/''||coalesce(to_char(i.datadoc,''dd.mm.yyyy''),'''') Doc,
        coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',I.TIPDOC)),''''),
        -SUM(L1.CANT * (case when COALESCE(P.PMP,0)=0 then NS.PRET - COALESCE(NS.ADAOS,0) else P.PMP end)) ValDFTva, 0 ValCFTva,
        -SUM(L1.CANT * (case when COALESCE(P.PMP,0)=0 then NS.PRET - COALESCE(NS.ADAOS,0) else P.PMP end)) SoldFinFTva,
        (case when I.TIPDOC=6 then S.DEN_SUBUNIT when I.TIPDOC=7 then G.DEN_GEST else NP.DEN_PART end) SursaDest, IOA.DEN_IOART, NG.DEN_GEST, IOA.DEN_CONT, IOA.SIMB_CONT,
        L.NRLIVR||''/''||to_char(L.DATALIVR,''dd.mm.yyyy'') RecLivr, TO_CHAR(L.DATALIVR,''DD'')::numeric Zi, TO_CHAR(I.DATADOC,''DD'')::numeric ZiDoc
      FROM INTRARI I
        INNER JOIN LIVR     L  ON L.CODINTR     = I.CODINTR
        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'||coalesce((select wme_result from pkg_list_base_raportgestpmp_JOINTMP('','N.GEST'))::varchar,'')||'
        INNER JOIN IOA         ON IOA.CODIOART  = NS.CODIOART
        INNER JOIN NGEST    NG ON NG.CODGEST    = N.GEST '|| coalesce((PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG','CODSUBUNIT',NULL,NULL))::varchar,'')||'
        LEFT  JOIN tmp_pmp  p  ON P.CODOBIECT   = NS.CODOBIECT'||CASE WHEN vTipPmp &lt;&gt; 1 THEN ' AND P.CODSUBUNIT = NG.CODSUBUNIT' else '' END||'
        LEFT  JOIN NPART    NP ON NP.CODPART    = I.PARTENER
        LEFT  JOIN NGEST    G  ON G.CODGEST     = I.CODGESTPROD
        LEFT  JOIN NSUBUNIT S  ON S.CODSUBUNIT  = I.CODSUBUNIT
      WHERE I.TIPDOC IN (1, 2, 3, 4, 5, 6, 7) AND I.OPERAT = 1 AND I.ANULAT = 0
        AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
        AND L.DATALIVR'||sCondData||'
      GROUP BY I.CODINTR, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC,  L.NRLIVR, L.DATALIVR, IOA.DEN_IOART, IOA.DEN_CONT, IOA.SIMB_CONT, NG.DEN_GEST, NP.DEN_PART, S.DEN_SUBUNIT, G.DEN_GEST
      UNION ALL  -- IESIRI STOC
      SELECT
        I.CODIES CodDoc, I.TIPDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC,
        coalesce(i.prefixdoc,'''') ||coalesce(i.seriadoc,'''')||coalesce(i.nrdoc::varchar,'''') ||''/''||coalesce(to_char(i.datadoc,''dd.mm.yyyy''),'''') Doc,
        coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',I.TIPDOC)),''''),
        0 ValDFTva, SUM(L1.CANT * CASE WHEN N.CODIES = I.CODIES OR COALESCE(P.PMP,0) = 0'||CASE WHEN  vTipPmp = 1 THEN ' OR I.TIPDOC =23' else '' END||' THEN NS.PRET - COALESCE(NS.ADAOS,0) ELSE P.PMP END) ValCFTva,
        -SUM(L1.CANT * CASE WHEN N.CODIES = I.CODIES OR COALESCE(P.PMP,0) = 0'||CASE WHEN  vTipPmp = 1 THEN ' OR I.TIPDOC =23' else '' END||' THEN NS.PRET - COALESCE(NS.ADAOS,0) ELSE P.PMP END) SoldFinFTva,
        (case when I.TIPDOC=14 then ''-'' when I.TIPDOC=16 then ''-'' when I.TIPDOC=23 then NSU.DEN_SUBUNIT when I.TIPDOC=24 then NG.DEN_GEST else NP.DEN_PART end) SursaDest, IOA.DEN_IOART, NG.DEN_GEST, IOA.DEN_CONT, IOA.SIMB_CONT,
        L.NRLIVR||''/''||to_char(L.DATALIVR,''dd.mm.yyyy'') RecLivr, TO_CHAR(L.DATALIVR,''DD'')::numeric Zi, TO_CHAR(I.DATADOC,''DD'')::numeric ZiDoc
      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 NIRSTOC  NS  ON NS.CODNIRSTOC  = L1.CODNIRSTOC
        INNER JOIN NIR      N   ON N.CODNIR       = NS.CODNIR'||coalesce((select wme_result from pkg_list_base_raportgestpmp_JOINTMP('','N.GEST'))::varchar,'')||'
        INNER JOIN IOA          ON IOA.CODIOART   = NS.CODIOART
        INNER JOIN NGEST    NG  ON NG.CODGEST     = N.GEST '|| coalesce((PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG','CODSUBUNIT',NULL,NULL))::varchar,'')||'
        LEFT  JOIN tmp_pmp  p   ON P.CODOBIECT    = NS.CODOBIECT'||CASE WHEN vTipPmp &lt;&gt; 1 THEN ' AND P.CODSUBUNIT = NG.CODSUBUNIT' else '' END||'
        LEFT  JOIN NPART    NP  ON NP.CODPART     = I.PARTENER
        LEFT  JOIN NGEST    G   ON G.CODGEST      = I.CODGESTPROD
        LEFT  JOIN NSUBUNIT NSU ON NSU.CODSUBUNIT = I.CODSUBUNIT
      WHERE I.TIPDOC IN (14, 16, 19, 20, 21, 22, 23, 24) AND I.OPERAT = 1 AND I.ANULAT = 0
        AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
        AND L.DATALIVR'||sCondData||'
      GROUP BY I.CODIES, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC,  L.NRLIVR, L.DATALIVR, IOA.DEN_IOART, IOA.DEN_CONT, IOA.SIMB_CONT, NG.DEN_GEST, NP.DEN_PART, NSU.DEN_SUBUNIT, G.DEN_GEST
      UNION ALL -- MARIRI DE STOC
      SELECT
        I.CODIES CodDoc, I.TIPDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC,
        coalesce(i.prefixdoc,'''') ||coalesce(i.seriadoc,'''')||coalesce(i.nrdoc::varchar,'''') ||''/''||coalesce(to_char(i.datadoc,''dd.mm.yyyy''),'''') Doc,
        coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',I.TIPDOC)),''''),
        SUM(L1.CANT * CASE WHEN N.CODIES = I.CODIES OR COALESCE(P.PMP,0) = 0 THEN (NS.PRET - COALESCE(NS.ADAOS,0)) ELSE P.PMP END) ValDFTva, 0 ValCFTva,
        SUM(L1.CANT * CASE WHEN N.CODIES = I.CODIES OR COALESCE(P.PMP,0) = 0 THEN (NS.PRET - COALESCE(NS.ADAOS,0)) ELSE P.PMP END) SoldFinFTva,
        NG.DEN_GEST SursaDest, IOA.DEN_IOART,
        NG.DEN_GEST, IOA.DEN_CONT, IOA.SIMB_CONT,
        L.NRLIVR||''/''||to_char(L.DATALIVR,''dd.mm.yyyy'') RecLivr, TO_CHAR(L.DATALIVR,''DD'')::numeric Zi, TO_CHAR(I.DATADOC,''DD'')::numeric ZiDoc
      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 NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
        INNER JOIN NIR     N  ON N.CODNIR      = NS.CODNIR'||coalesce((select wme_result from pkg_list_base_raportgestpmp_JOINTMP('','N.GEST'))::varchar,'')||'
        INNER JOIN IOA        ON IOA.CODIOART  = NS.CODIOART
        INNER JOIN NGEST   NG ON NG.CODGEST    = N.GEST '|| coalesce((PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG','CODSUBUNIT',NULL,NULL))::varchar,'')||'
        LEFT  JOIN tmp_pmp p  ON P.CODOBIECT   = NS.CODOBIECT'||CASE WHEN vTipPmp &lt;&gt; 1 THEN ' AND P.CODSUBUNIT = NG.CODSUBUNIT' else '' END||'
      WHERE I.TIPDOC = 15 AND I.OPERAT = 1 AND I.ANULAT = 0
        AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
        AND L.DATALIVR'||sCondData||'
      GROUP BY I.CODIES, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC,  L.NRLIVR, L.DATALIVR, IOA.DEN_IOART, IOA.DEN_CONT, IOA.SIMB_CONT, NG.DEN_GEST'
    ;

    --PKG_GLOBALS.SetDebugMode(TRUE);
    PERFORM pkg_globals_SetLunaTemp(getANLUCRU(), getLUNALUCRU());

    DELETE FROM tmp_pmp;

    IF PKG_PMP_AM_MISCARI_CU_PMP() &gt; 0 THEN
      PERFORM PKG_PMP_CALC_PMP2(vTipPmp);
    END IF;

    sDebug :=
      'DO language plpgsql $$
       BEGIN'||Chr(10)||
      '  PERFORM pkg_globals_SetLunaLucru('||getANLUCRU()::varchar||','||getLUNALUCRU()::varchar||');'||Chr(10)||
      '  PERFORM pkg_globals_SetLunaTemp ('||getANLUCRU()::varchar||','||getLUNALUCRU()::varchar||');'||Chr(10)||
      '  DELETE FROM tmp_pmp;'||Chr(10)||
      '  IF PKG_PMP_AM_MISCARI_CU_PMP() &gt; 0 THEN'||Chr(10)||
      '    PERFORM PKG_PMP_CALC_PMP2('||vTipPmp::varchar||');'||Chr(10)||
      '  END IF;'||Chr(10)||
      'END; $$;';

    PERFORM PKG_GLOBALS_CheckDebugMode(sDebug, aListID, aListVer);

    PERFORM PKG_LIST_BASE_UTILS_make_config_luna_ioart();
INSERT INTO x (VIEW_name, test) VALUES ('test4', 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_raportvanzari_processlist</obj_name>
  <obj_hashval>057da37b0cfe7db02a7be6cd2f22272a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportvanzari_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert      varchar;
  sSelect      varchar;
  sWhereP      varchar;
  sCurs        varchar;
  sInsertUMA   varchar;
  sSelectUMA   varchar;
  sSelectIG    varchar;
  sFiltruPart  varchar := '';
  sFromIG      varchar;
  sJoinIG      varchar;
  sWhereIG     varchar;
  sGroupIG     varchar;
  sWith        varchar;
  sJoin        varchar;
  aSitV        numeric;
  aBancaV      numeric;
  aMonedaV     numeric;
  sCondCatPret varchar;
  gSuplCols    varchar := 'NARTOBJ NAO, NART NA, NUM NUM, NGEST NG, NPART NP, NPART PROD, IOART IOA, NCLASEA NCA, NCLASEP NCP, NPERS AG, ' || 'NAGENDA SSOC, NLOCALIT LSOC, NJUDET JSOC, NAGENDA SLIV, NLOCALIT LLIV, NJUDET JLIV, TRASEULIVR TLIV, NTIPSEDII TIPSLIV,PRETM PRETIMP';
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplJoins   VARCHAR := '';
  wmeRes       boolean;
BEGIN
  --Adina 19.02.2021 - GetInfoSitValuta + PKG_LIST_BASE_UTILS_UMA_UTILS
  --Adina 11.02.2021 - corectat PKG_LIST_BASE_UTILS_GETCURSREFERINTA in loc de PKG_LIST_BASE_UTILS.GETCURSREFERINTA
  --Florin 31.08.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_RAPORTVANZARI.gSuplCols', gSuplCols, FALSE);

  sWhereP := ' AND ';
  IF current_setting('PKG_LIST_BASE_RAPORTVANZARI.vTipData', true) THEN
    sWhereP := coalesce(sWhereP,'') || 'I.DATADOC';
  ELSE
    sWhereP := coalesce(sWhereP,'') || 'I.An = ' || coalesce(getanlucru(), 0) || ' AND I.LUNA';
  END IF;

  IF  current_setting('PKG_LIST_BASE_RAPORTVANZARI.vInceput', true) = current_setting('PKG_LIST_BASE_RAPORTVANZARI.vSfarsit', true) THEN
    sWhereP := coalesce(sWhereP,'') || ' = ' || coalesce(current_setting('PKG_LIST_BASE_RAPORTVANZARI.vInceput', true),'');
  ELSE
    sWhereP := coalesce(sWhereP,'') || ' BETWEEN ' || coalesce(current_setting('PKG_LIST_BASE_RAPORTVANZARI.vInceput', true),'') || ' AND ' || coalesce(current_setting('PKG_LIST_BASE_RAPORTVANZARI.vSfarsit', true),'');
  END IF;

  IF current_setting('PKG_LIST_BASE_RAPORTVANZARI.vAllPart', true)::numeric = 1 THEN
    sFiltruPart := ' IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPART'')';
  END IF;

  IF current_setting('PKG_LIST_BASE_RAPORTVANZARI.vAllPart', true)::numeric = 2 THEN
    sFiltruPart := ' NOT IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPART'')';
  END IF;

  IF sFiltruPart IS NOT NULL AND sFiltruPart &lt;&gt; '' THEN
    sWhereP := coalesce(sWhereP,'') || '
            AND I.PARTENER::varchar' || coalesce(sFiltruPart,'');
  END IF;

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

  IF current_setting('PKG_LIST_BASE_RAPORTVANZARI.vValuta', true)::boolean AND wmeRes  --(SELECT FNC_GetInfoSitValuta.wme_result FROM FNC_GetInfoSitValuta())
  THEN
    --SELECT FNC_GetInfoSitValuta.pBancaValuta, FNC_GetInfoSitValuta.pMonedaValuta INTO aBancaV, aMonedaV FROM FNC_GetInfoSitValuta();
    sCurs := ' / PKG_LIST_BASE_UTILS_GETCURSREFERINTA(' || coalesce(aMonedaV::varchar,'0') || ',' || coalesce(aBancaV::varchar,'0') || ', to_char(i1.datadoc,''dd.mm.yyyy'') )';
  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   sInsertUMA, sSelectUMA, sJoin
  FROM PKG_LIST_BASE_UTILS_UMA_UTILS('ig.cant', 'ig.codobiect', sInsertUMA, sSelectUMA, sJoin,NULL);
  --PERFORM PKG_LIST_BASE_UTILS_UMA_UTILS('ig.cant', 'ig.codobiect', sInsertUMA, sSelectUMA, sJoin,NULL);

  IF COALESCE((CASE WHEN current_setting('PKG_LIST_BASE_RAPORTVANZARI.vTipTarget', TRUE) = '' THEN NULL
                    ELSE current_setting('PKG_LIST_BASE_RAPORTVANZARI.vTipTarget', TRUE)::NUMERIC END), 0) = 1
  THEN
    sSelectIG := '
            T.AGENT, 0 PARTENER, 0 CODLOCATIE,
            CASE T.TIPTARGET WHEN 3 THEN T.CLASASBAZA WHEN 0 THEN A.CLASASTATIST ELSE 0 END CLASAS,
            CASE T.TIPTARGET WHEN 2 THEN T.CLASABAZA  WHEN 0 THEN A.CLASA        ELSE 0 END CLASA,
            CASE T.TIPTARGET WHEN 0 THEN O.CODOBIECT                             ELSE 0 END CODOBIECT,
            T.CANTTARGET, T.VALTARGET, T.MASATARGET, T.VOLUMTARGET, T.TIPTARGET, T.NRCLIENTI, COUNT(DISTINCT CA.CODIES) CountCli,';
    sFromIG := 'TARGET T
            LEFT JOIN I1 ON T.AGENT = I1.AGENT AND I1.DATADOC BETWEEN T.DATASTART AND T.DATASTOP AND I1.CANT &lt;&gt; 0
              AND CASE T.TIPTARGET WHEN 0 THEN T.CODOBIECT ELSE I1.CODOBIECT END = I1.CODOBIECT
              AND CASE T.TIPTARGET WHEN 2 THEN T.CLASA     ELSE I1.CLASA     END = I1.CLASA
              AND CASE T.TIPTARGET WHEN 3 THEN T.CLASAS    ELSE I1.CLASAS    END = I1.CLASAS
            LEFT JOIN NARTOBJ O ON O.CODOBIECT = Coalesce(I1.CODOBIECT, T.CODOBIECT)
            LEFT JOIN NART A ON A.CODARTICOL = O.CODOBIECT';
    sJoinIG := '
            LEFT JOIN CA ON CA.CODIES = I1.CODIES AND I1.IDX = 1';
    sGroupIG := 'T.AGENT,
            CASE T.TIPTARGET WHEN 3 THEN T.CLASASBAZA WHEN 0 THEN A.CLASASTATIST ELSE 0 END,
            CASE T.TIPTARGET WHEN 2 THEN T.CLASABAZA  WHEN 0 THEN A.CLASA        ELSE 0 END,
            CASE T.TIPTARGET WHEN 0 THEN O.CODOBIECT                             ELSE 0 END,
            T.CANTTARGET, T.VALTARGET, T.MASATARGET, T.VOLUMTARGET, T.TIPTARGET, T.NRCLIENTI';
    sWith := coalesce(sWith,'') || '
        CA AS (
          SELECT xx.partener, xx.codlocatie, xx.subunitatea, Min(xx.codies) codies FROM (SELECT i.partener, i.codlocatie, i.subunitatea, i.codies, Dense_Rank() OVER(ORDER BY i.datadoc, i.codies) co
          FROM iesiri i
          WHERE i.anulat = 0 AND i.operat = 1 AND i.tipdoc::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''TIPDOC'')
            AND Coalesce(i.partener,0) &lt;&gt; 0 AND Coalesce(i.codlocatie,0) &lt;&gt; 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('i',NULL,NULL,NULL),'')
            || coalesce(CASE WHEN sFiltruPart IS NOT NULL AND sFiltruPart &lt;&gt; '' THEN '
            AND I.PARTENER::varchar' || coalesce(sFiltruPart,'') END ,'') || ') xx
            where xx.co = 1
          GROUP BY xx.partener, xx.codlocatie, xx.subunitatea),
        TARGET AS (
          SELECT
            T.AGENT, T.DATASTART, T.DATASTOP, Coalesce(T.TIPTARGET,0) TIPTARGET, Coalesce(T.NRCLIENTI,0) NRCLIENTI,
            T1.CODOBIECT, C.CLASABAZA, C.CLASA, CS.CLASASBAZA, CS.CLASAS,
            Coalesce(T1.CANT,0) CANTTARGET, Coalesce(T1.VALOARE,0) VALTARGET, Coalesce(T1.MASA,0) MASATARGET, Coalesce(T1.VOLUM,0) VOLUMTARGET
          FROM TARGETAG T
            INNER JOIN TARGETAG1 T1 ON T1.CODTARGETAG = T.CODTARGETAG
            LEFT JOIN (
             WITH recursive cl(clasabaza, codclasea, rootclasabaza) AS(
              SELECT codclasea clasabaza, codclasea, codclasea rootclasasbaza
            FROM nclasea
              UNION ALL
               SELECT n.codclasea clasabaza, n.codclasea clasa, cl.rootclasabaza
            FROM nclasea n INNER JOIN cl ON cl.codclasea = n.codparinte
            )
            SELECT rootclasabaza CLASABAZA, codclasea CLASA FROM cl
          ) C ON C.CLASABAZA = CASE T.TIPTARGET WHEN 2 THEN T1.CODCLASA ELSE 0 END
          LEFT JOIN (
            WITH recursive cl1(clasasbaza, codclaseas, rootclasasbaza) AS (
              SELECT codclaseas clasasbaza, codclaseas, codclaseas rootclasasbaza
            FROM nclaseas
              UNION ALL
               SELECT n.codclaseas clasasbaza, n.codclaseas clasas, cl1.rootclasasbaza
            FROM nclaseas n INNER JOIN cl1 ON cl1.codclaseas = n.codparinte
             )
            SELECT rootclasasbaza CLASASBAZA, codclaseas CLASAS FROM cl1
            ) CS ON CS.CLASASBAZA = CASE T.TIPTARGET WHEN 3 THEN T1.CODCLASAS ELSE 0 END
          WHERE T.TIPDOC = 17
            AND T.DATASTART &lt;= ' || COALESCE(current_setting('PKG_LIST_BASE_RAPORTVANZARI.xSfarsit', TRUE),'') || '
            AND T.DATASTOP &gt;= ' || COALESCE(current_setting('PKG_LIST_BASE_RAPORTVANZARI.xInceput', TRUE),'') || '
            AND T.ANULAT = 0 AND T.OPERAT = 1 AND T.ACTIV = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL),'') || '),';
  ELSIF COALESCE((CASE WHEN current_setting('PKG_LIST_BASE_RAPORTVANZARI.vTipTarget', TRUE) = '' THEN NULL
            ELSE current_setting('PKG_LIST_BASE_RAPORTVANZARI.vTipTarget', TRUE)::NUMERIC END), 0) = 2
  THEN
    sSelectIG := '
            0 AGENT, T.CLIENT PARTENER, 0 CODLOCATIE,
            CASE T.TIPTARGET WHEN 3 THEN T.CLASASBAZA WHEN 0 THEN A.CLASASTATIST ELSE 0 END CLASAS,
            CASE T.TIPTARGET WHEN 2 THEN T.CLASABAZA  WHEN 0 THEN A.CLASA        ELSE 0 END CLASA,
            CASE T.TIPTARGET WHEN 0 THEN O.CODOBIECT                             ELSE 0 END CODOBIECT,
            T.CANTTARGET, T.VALTARGET, T.MASATARGET, T.VOLUMTARGET, T.TIPTARGET, 1 NRCLIENTI, 1 CountCli,';
    sFromIG := 'TARGET T
            LEFT JOIN I1 ON T.CLIENT = I1.PARTENER AND I1.DATADOC BETWEEN T.DATASTART AND T.DATASTOP AND I1.CANT &lt;&gt; 0
              AND CASE T.TIPTARGET WHEN 0 THEN T.CODOBIECT ELSE I1.CODOBIECT END = I1.CODOBIECT
              AND CASE T.TIPTARGET WHEN 2 THEN T.CLASA     ELSE I1.CLASA     END = I1.CLASA
              AND CASE T.TIPTARGET WHEN 3 THEN T.CLASAS    ELSE I1.CLASAS    END = I1.CLASAS
            LEFT JOIN NARTOBJ O ON O.CODOBIECT = Coalesce(I1.CODOBIECT, T.CODOBIECT)
            LEFT JOIN NART A ON A.CODARTICOL = O.CODOBIECT';
    sJoinIG := '';
    sGroupIG := 'T.CLIENT,
            CASE T.TIPTARGET WHEN 3 THEN T.CLASASBAZA WHEN 0 THEN A.CLASASTATIST ELSE 0 END,
            CASE T.TIPTARGET WHEN 2 THEN T.CLASABAZA  WHEN 0 THEN A.CLASA        ELSE 0 END,
            CASE T.TIPTARGET WHEN 0 THEN O.CODOBIECT                             ELSE 0 END,
            T.CANTTARGET, T.VALTARGET, T.MASATARGET, T.VOLUMTARGET, T.TIPTARGET';
    sWith := COALESCE(sWith,'') || '
        TARGET AS (
          SELECT
            T.CLIENT, T.DATASTART, T.DATASTOP, Coalesce(T.TIPTARGET,0) TIPTARGET,
            T1.CODOBIECT, C.CLASABAZA, C.CLASA, CS.CLASASBAZA, CS.CLASAS,
            Coalesce(T1.CANT,0) CANTTARGET, Coalesce(T1.VALOARE,0) VALTARGET, Coalesce(T1.MASA,0) MASATARGET, Coalesce(T1.Volum,0) VOLUMTARGET
          FROM TARGETAG T
            INNER JOIN TARGETAG1 T1 ON T1.CODTARGETAG = T.CODTARGETAG
            LEFT JOIN (
            WITH recursive cl(clasabaza, codclasea, rootclasabaza) AS(
              SELECT codclasea clasabaza, codclasea, codclasea rootclasasbaza
            FROM nclasea
              UNION ALL
               SELECT n.codclasea clasabaza, n.codclasea clasa, cl.rootclasabaza
            FROM nclasea n INNER JOIN cl ON cl.codclasea = n.codparinte
            )
            SELECT rootclasabaza CLASABAZA, codclasea CLASA FROM cl
          ) C ON C.CLASABAZA = CASE T.TIPTARGET WHEN 2 THEN T1.CODCLASA ELSE 0 END
          LEFT JOIN (
            WITH recursive cl1(clasasbaza, codclaseas, rootclasasbaza) AS (
              SELECT codclaseas clasasbaza, codclaseas, codclaseas rootclasasbaza
            FROM nclaseas
              UNION ALL
               SELECT n.codclaseas clasasbaza, n.codclaseas clasas, cl1.rootclasasbaza
            FROM nclaseas n INNER JOIN cl1 ON cl1.codclaseas = n.codparinte
             )
            SELECT rootclasasbaza CLASASBAZA, codclaseas CLASAS FROM cl1
          ) CS ON CS.CLASASBAZA = CASE T.TIPTARGET WHEN 3 THEN T1.CODCLASAS ELSE 0 END
          WHERE T.TIPDOC = 65
            AND T.DATASTART &lt;= ' || COALESCE(current_setting('PKG_LIST_BASE_RAPORTVANZARI.xSfarsit', TRUE),'') || '
            AND T.DATASTOP &gt;= ' || COALESCE(current_setting('PKG_LIST_BASE_RAPORTVANZARI.xInceput', TRUE),'') || '
            AND T.ANULAT = 0 AND T.OPERAT = 1 AND T.ACTIV = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL),'') || coalesce(CASE
            WHEN sFiltruPart IS NOT NULL AND sFiltruPart &lt;&gt; ''  THEN '
            AND T.CLIENT::varchar' || coalesce(sFiltruPart,'')
     END ,'') || '),';
  ELSE
    sSelectIG := '
            I1.AGENT, I1.PARTENER, I1.CODLOCATIE,
            I1.CLASA,
            I1.CLASAS,
            I1.CODOBIECT,
            0 CANTTARGET, 0 VALTARGET, 0 MASATARGET, 0 VOLUMTARGET, 0 TIPTARGET, 0 NRCLIENTI, COUNT(DISTINCT I1.PARTENER||'' ''||I1.CODLOCATIE) CountCli,';
    sFromIG := 'I1
            LEFT JOIN NARTOBJ O ON O.CODOBIECT = I1.CODOBIECT';
    sWhereIG := '
          WHERE i1.cant &lt;&gt; 0';
    sGroupIG := 'I1.AGENT, I1.PARTENER, I1.CODLOCATIE, I1.CLASA, I1.CLASAS, I1.CODOBIECT';
  END IF;
  sCondCatPret := ' AND P.Subunitatea = ' || coalesce(current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric, 0);
  IF COALESCE((CASE WHEN current_setting('PKG_LIST_BASE_RAPORTVANZARI.vCatPret', TRUE) = '' THEN NULL
                    ELSE current_setting('PKG_LIST_BASE_RAPORTVANZARI.vCatPret', TRUE)::NUMERIC END), 0) = 0
  THEN
    sCondCatPret := coalesce(sCondCatPret,'') || ' AND p.implicit = 1 ';
  ELSE
    sCondCatPret := coalesce(sCondCatPret,'') || ' AND p.codcatpret = ' || COALESCE(current_setting('PKG_LIST_BASE_RAPORTVANZARI.vCatPret', true)::NUMERIC, 0);
  END IF;
  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(
        Art,
        UM, Cant, Val, ValCuTva, VU, ValAchiz, Masa, Volum,
        DenClasaA, CodInt, CodExt, Prod, PretVinz, PretValuta,
        Agent, NrCli,
        Client, DenClasaC, SedCli, AdrSedCli, NrUtilaje,
        TarTip,
        TarCant, TarVal, TarMasa, TarVolum, TarNrCli' || coalesce(sInsertUMA,'') || gUserFields || '
      )';
  sSelect := '
      WITH ' || COALESCE(sWith,'') || '
        I1 AS (
          SELECT
            I.CODIES, I1.CODIES1, I.DATADOC,CASE WHEN I.CURS IS NULL THEN 1 WHEN I.CURS = 0 THEN 1 ELSE I.CURS END CURS, Coalesce(I.AGENT,0) AGENT, I.PARTENER, Coalesce(I.CODLOCATIE,0) CODLOCATIE,
            I1.CODOBIECT, Coalesce(A.CLASA,0) CLASA, Coalesce(A.CLASASTATIST,0) CLASAS, I1.CANT, I1.PU, I.VALDOC - I.TVADOC VALDOC, I.VALDOC VALTDOC,
            CASE
              WHEN I1.ADDIM = -100 THEN 0
              WHEN I.TIPDOC IN (16,21) THEN (I1.PU * I1.CANT - I1.TVA) / (1+Coalesce(I1.ADDim/100,0))
              ELSE I1.PU * I1.CANT / (1+Coalesce(I1.ADDim/100,0))
            END * Coalesce(I1.COEFDISCMAJ,1) VALLIN,
            CASE
              WHEN I1.ADDIM = -100 THEN 0
              WHEN I.TIPDOC IN (16,21) THEN I1.PU * I1.CANT / (1+Coalesce(I1.ADDim/100,0))
              ELSE (I1.PU * I1.CANT + I1.TVA) / (1+Coalesce(I1.ADDim/100,0))
            END * Coalesce(I1.COEFDISCMAJ,1) VALTLIN,
            SUM(
              CASE
                WHEN I1.ADDIM = -100 THEN 0
                WHEN I.TIPDOC IN (16,21) THEN (I1.PU * I1.CANT - I1.TVA) / (1+Coalesce(I1.ADDim/100,0))
                ELSE I1.PU * I1.CANT / (1+Coalesce(I1.ADDim/100,0))
              END * Coalesce(I1.COEFDISCMAJ,1)
            ) OVER (PARTITION BY I.CODIES) VALIES,
            SUM(
              CASE
                WHEN I1.ADDIM = -100 THEN 0
                WHEN I.TIPDOC IN (16,21) THEN I1.PU * I1.CANT / (1+Coalesce(I1.ADDim/100,0))
                ELSE (I1.PU * I1.CANT + I1.TVA) / (1+Coalesce(I1.ADDim/100,0))
              END * Coalesce(I1.COEFDISCMAJ,1)
            ) OVER (PARTITION BY I.CODIES) VALTIES,
            ROW_NUMBER() OVER (PARTITION BY I.CODIES ORDER BY I1.CODIES1) IDX
          FROM IESIRI I
            INNER JOIN IESIRI1 I1 ON I1.CODIES    = I.CODIES
            INNER JOIN NARTOBJ O  ON O.CODOBIECT  = I1.CODOBIECT
            INNER JOIN NART    A  ON A.CODARTICOL = O.CODARTICOL
          WHERE I.TIPDOC::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''TIPDOC'') AND I.ANULAT = 0 AND I.OPERAT = 1 ' || coalesce(sWhereP,'')
            || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '),
        IG AS (
          SELECT ' || coalesce(sSelectIG,'') || '
            SUM(CASE WHEN Coalesce(AE1.CANT,0) &lt;&gt; 0 AND Coalesce(L1.CANT,0) &lt;&gt; 0 THEN L1.CANT*I1.CANT/AE1.CANT ELSE COALESCE(L1.CANT,I1.CANT,0) END) CANT,
            SUM(CASE WHEN Coalesce(AE1.CANT,0) &lt;&gt; 0 AND Coalesce(L1.CANT,0) &lt;&gt; 0 THEN L1.CANT*I1.CANT/AE1.CANT ELSE COALESCE(L1.CANT,I1.CANT,0) END*Coalesce(O.MASA,0)) MASA,
            SUM(CASE WHEN Coalesce(AE1.CANT,0) &lt;&gt; 0 AND Coalesce(L1.CANT,0) &lt;&gt; 0 THEN L1.CANT*I1.CANT/AE1.CANT ELSE COALESCE(L1.CANT,I1.CANT,0) END*Coalesce(O.VOLUM,0)) VOLUM,
            Coalesce(SUM(i1.pu * COALESCE(L1.CANT,I1.CANT,0)' || coalesce(sCurs,'') || '* i1.curs),0) vu,
            Coalesce(SUM(i1.vallin *CASE WHEN i1.valies  = 0 THEN 1 ELSE i1.valdoc /i1.valies  END*Coalesce(l1.cant,i1.cant)/i1.cant*i1.curs' || coalesce(sCurs,'') || '),0) val,
            Coalesce(SUM(i1.valtlin*CASE WHEN i1.valties = 0 THEN 0 ELSE i1.valtdoc/i1.valties END*Coalesce(l1.cant,i1.cant)/i1.cant*i1.curs' || coalesce(sCurs,'') || '),0) valcutva,
            Coalesce(SUM( COALESCE(LV.PRETACHIZ,NS.PRET - NS.ADAOS,0) * Coalesce(l1.cant,i1.cant)),0) valachiz
          FROM ' || coalesce(sFromIG,'') || '
            LEFT JOIN IESLINK IL  ON IL.CODIES1    = I1.CODIES1
            LEFT JOIN IESIRI1 AE1 ON AE1.CODIES1   = IL.CODLINIEAVIZ
            LEFT JOIN LIVR    L   ON L.CODIES      = Coalesce(AE1.CODIES,I1.CODIES)
            LEFT JOIN LIVR1   L1  ON L1.CODLIVR    = L.CODLIVR AND L1.CODIES1 = Coalesce(IL.CODLINIEAVIZ,I1.CODIES1)
            LEFT JOIN NIRSTOC NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
            LEFT JOIN NIR     N   ON N.CODNIR      = NS.CODNIR
            LEFT JOIN LIVRVAL LV  ON LV.CODLIVR1   = L1.CODLIVR1' || coalesce(sJoinIG,'') || coalesce(sWhereIG,'') || '
          GROUP BY ' || coalesce(sGroupIG,'') || ' )
      SELECT
        CASE
          WHEN Coalesce(NAO.CODOBIECT, 0) &lt;&gt; 0 THEN NAO.DENUMIRE
          WHEN Coalesce(NCA.CODCLASEA, 0) &lt;&gt; 0 THEN NCA.DEN_CLASEA
          WHEN Coalesce(NCS.CODCLASEAS,0) &lt;&gt; 0 THEN NCS.DEN_CLASEAS
          ELSE ''...''
        END,
        Coalesce(NUM.DEN_UM,''...''), CASE WHEN IG.CODOBIECT = 0 THEN 0 ELSE IG.CANT END, IG.VAL, IG.VALCUTVA, IG.VU, IG.VALACHIZ, IG.MASA, IG.VOLUM,
        NCA.DEN_CLASEA, NAO.CODINTERN, NAO.CODEXTERN, PROD.DEN_PART, P.LEI PRETVANZ, P.VALUTA,
        (SELECT NUMEPRENUME.WME_RESULT FROM NUMEPRENUME(NULL, AG.NUME,AG.PRENUME)) Agent, IG.CountCli NrCli,
        NP.DEN_PART Client, NCP.DEN_CLASEP DenClasaC, SED.OBS SedCli, SEDL.DEN_LOCALIT||'' ''||
        (SELECT GETADRESA.wme_result FROM GETADRESA(NULL, SED.SECTOR,SED.STRADA,SED.NR1,SED.NR2,SED.BLOC,SED.SCARA,SED.ETAJ,SED.APART,SED.CODPOSTAL)) AdrSedCli, SED.COEFUTILAJE NrUtilaje,
        CASE IG.TIPTARGET
          WHEN NULL THEN '' ''
          WHEN    3 THEN ''Pe clase statistice de articole''
          WHEN    2 THEN ''Pe clase de articole''
          WHEN    1 THEN ''Toate Articolele''
          WHEN    0 THEN ''Pe articole''
        END TarTip,
        IG.CANTTARGET TarCant, IG.VALTARGET TarVal, IG.MASATARGET TarMasa, IG.VOLUMTARGET TarVolum, IG.NRCLIENTI TarNrCli ' || coalesce(sSelect,'') || coalesce(sSelectUMA,'') || gUserAlias || '
      FROM IG
        LEFT JOIN NARTOBJ  NAO  ON NAO.CODOBIECT   = IG.CODOBIECT
        LEFT JOIN NART     NA   ON NA.CODARTICOL   = NAO.CODARTICOL
        LEFT JOIN NUM           ON NUM.CODUM       = NA.UM
        LEFT JOIN NCLASEA  NCA  ON NCA.CODCLASEA   = IG.CLASA
        LEFT JOIN NCLASEAS NCS  ON NCS.CODCLASEAS  = IG.CLASAS
        LEFT JOIN NPART    PROD ON PROD.CODPART    = NAO.CODPRODUCATOR
        LEFT JOIN NPART    NP   ON NP.CODPART      = IG.PARTENER
        LEFT JOIN NCLASEP  NCP  ON NCP.CODCLASEP   = NP.CODCLASA
        LEFT JOIN NAGENDA  SED  ON SED.CODAGENDA   = IG.CODLOCATIE
        LEFT JOIN NLOCALIT SEDL ON SEDL.CODLOCALIT = SED.CODLOCALIT
        LEFT JOIN NPERS    AG   ON AG.CODPERS      = IG.AGENT
        LEFT JOIN PRETM    P    ON P.CODOBIECT     = IG.CODOBIECT ' || coalesce(sCondCatPret,'') || coalesce(sJoin,'') || 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_rapstoc_bagadinamiccols</obj_name>
  <obj_hashval>75e86a678e0685bd3761446e43bae34f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rapstoc_bagadinamiccols()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       VARCHAR   := '';
  vCondAnLuna   VARCHAR   := '';
  vAnStart      NUMERIC   := EXTRACT (YEAR  FROM to_date(current_setting('PKG_LIST_BASE_RAPSTOC.dDataIni', true),'dd.mm.yyyy') );  --To_Char(dDataIni,'yyyy');
  vLunaStart    NUMERIC   := EXTRACT (MONTH FROM to_date(current_setting('PKG_LIST_BASE_RAPSTOC.dDataIni', true),'dd.mm.yyyy') );  --To_Char(dDataIni,'mm');
  vAnStop       NUMERIC   := EXTRACT (YEAR  FROM to_date(current_setting('PKG_LIST_BASE_RAPSTOC.dDataFin', true),'dd.mm.yyyy') );  --To_Char(dDataFin,'yyyy');
  vLunaStop     NUMERIC   := EXTRACT (MONTH FROM to_date(current_setting('PKG_LIST_BASE_RAPSTOC.dDataFin', true),'dd.mm.yyyy') );  --To_Char(dDataFin,'mm');
  vAnPreced     NUMERIC;
  vLunaPreced   NUMERIC;
  vDataIni      VARCHAR   := current_setting('PKG_LIST_BASE_RAPSTOC.dDataIni', true);  --To_Char(dDataIni,'dd.mm.yyyy');
  vDataFin      VARCHAR   := current_setting('PKG_LIST_BASE_RAPSTOC.dDataFin', true);  --To_Char(dDataFin,'dd.mm.yyyy');
  vFiltru       VARCHAR   := '';
  sPromo        VARCHAR   := '';
   selDataIni    date       := to_date(current_setting('PKG_LIST_SELECTSCAD.vDataIni' , true), 'DD.MM.YYYY');
   selDataFin    date       := to_date(current_setting('PKG_LIST_SELECTSCAD.vDataScad', true), 'DD.MM.YYYY');
   vToateGest    boolean    := current_setting('PKG_LIST_BASE_RAPSTOC.vToateGest'   , true)::boolean;
   vToateIOArt    boolean    := current_setting('PKG_LIST_BASE_RAPSTOC.vToateIOArt'  , true)::boolean;
   vPromoSeparat  boolean    := current_setting('PKG_LIST_BASE_RAPSTOC.vPromoSeparat', true)::boolean;
BEGIN
  --Adina 07.04.2021 - alstart,alstop
  --Adina 10 septembrie 2020
  IF Date_Trunc('month',selDataIni) = Date_Trunc('month',selDataFin) THEN
    vCondAnLuna := '= '||(vAnStart*12+vLunaStart)::varchar;
  ELSE
    vCondAnLuna := 'BETWEEN '||(vAnStart*12+vLunaStart)::varchar||' AND '||(vAnStop*12+vLunaStop)::varchar;
  END IF;

  SELECT newan,newluna INTO vAnPreced, vLunaPreced FROM pkg_globals_Calculeaza_Luna_Precedenta(vAnStart,vLunaStart,vAnPreced,vLunaPreced);

  if NOT vToateGest THEN
    vFiltru := vFiltru||'
        AND N.GEST::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'')';
  end if;

  if NOT vToateIOArt THEN
    vFiltru := vFiltru||'
        AND NS.CODIOART::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'')';
  end if;

  IF vPromoSeparat THEN
    sPromo := ', CASE WHEN I.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN 0 WHEN coalesce(CADOU,0) = 0 AND coalesce(PRETPROMO,0) = 0 THEN 0 ELSE 1 END PROMO';
  ELSE
    sPromo := ', 0 PROMO';
  END IF;

  DELETE FROM tmp_list_rapstoc;

  sInsert:=
  'INSERT INTO tmp_list_rapstoc( CodGest, CodObiect, CodDoc, TipDoc, Cant, Semn, Promo )
  WITH
    B AS (
      -- Initial
      SELECT
        N.GEST, NS.CODOBIECT, 0 CODDOC, 0 TIPDOC, '' Stoc initial'' DOC, to_date('''||vDataIni||''',''dd.mm.yyyy'') DATADOC, NL.REST CANT, 1 SEMN, 0 PROMO
      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 '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT',NULL,NULL)||'
        INNER JOIN IOART1  IOA ON IOA.CODIOART  = NS.CODIOART AND '||(vAnStop*12+vLunaStop)::varchar||' BETWEEN IOA.ALStart and IOA.ALStop  AND IOA.mg &lt;&gt; 5
      WHERE nl.an = '||vANPreced::varchar||' AND nl.luna = '||vLunaPreced::varchar||vFiltru||'
      UNION ALL -- NIR Intrari
      SELECT
        N.GEST, NS.CODOBIECT,
        CASE WHEN I.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN 0 ELSE I.CODINTR END CODDOC,
        CASE WHEN I.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN 0 ELSE I.TIPDOC END TIPDOC,
        CASE WHEN I.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN '' Stoc initial'' ELSE I.PREFIXDOC||I.NRDOC||''/''||I.DATADOC END DOC,
        CASE WHEN I.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN to_date('''||vDataIni||''',''dd.mm.yyyy'') ELSE I.DATADOC END DATADOC,
        NS.CANTNIR CANTINT, 1 SEMN, 0 PROMO
      FROM NIRSTOC NS
        INNER JOIN NIR     N   ON N.CODNIR     = NS.CODNIR
        INNER JOIN IOART1  IOA ON IOA.CODIOART = NS.CODIOART AND '||(vAnStop*12+vLunaStop)::varchar||' BETWEEN IOA.ALStart and IOA.ALStop  AND IOA.mg &lt;&gt; 5
        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 '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL)||'
        AND (I.AN *12 + I.LUNA) '||vCondAnLuna||' AND I.DATADOC &lt;= to_date('''||vDataFin||''',''dd.mm.yyyy'') '||vFiltru||'
      UNION ALL -- NIR-uri din MISCARI INTERNE
      SELECT
        N.GEST, NS.CODOBIECT,
        CASE WHEN T.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN 0 ELSE T.CODTRANSF END CODDOC,
        CASE WHEN T.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN 0 ELSE T.TIPDOC END TIPDOC,
        CASE WHEN T.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN '' Stoc initial'' ELSE T.PREFIXDOC||T.NRDOC||''/''||T.DATADOC END DOC,
        CASE WHEN T.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN to_date('''||vDataIni||''',''dd.mm.yyyy'') ELSE T.DATADOC END DATADOC,
        NS.CANTNIR CANTINT,  1 SEMN, 0 PROMO
      FROM NIRSTOC NS
        INNER JOIN NIR    N   ON N.CODNIR     = NS.CODNIR
        INNER JOIN IOART1 IOA ON IOA.CODIOART = NS.CODIOART AND '||(vAnStop*12+vLunaStop)::varchar||' BETWEEN IOA.ALStart and IOA.ALStop  AND IOA.mg &lt;&gt; 5
        INNER JOIN TRANSF T   ON T.CODTRANSF  = N.CODTRANSF
      WHERE N.TIPNIR IN (12, 13) AND N.ANULAT = 0 AND N.OPERAT = 1 '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL)||'
        AND (T.AN *12 + T.LUNA) '||vCondAnLuna||' AND T.DATADOC &lt;= to_date('''||vDataFin||''',''dd.mm.yyyy'')'||vFiltru||'
      UNION ALL -- RETURURI
      SELECT
        N.GEST, NS.CODOBIECT,
        CASE WHEN I.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN 0 ELSE I.CODINTR END CODDOC,
        CASE WHEN I.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN 0 ELSE I.TIPDOC END TIPDOC,
        CASE WHEN I.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN '' Stoc initial'' ELSE I.PREFIXDOC||I.NRDOC||''/''||I.DATADOC END DOC,
        CASE WHEN I.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN to_date('''||vDataIni||''',''dd.mm.yyyy'') ELSE I.DATADOC END DATADOC,
        -L1.CANT CANTINT,  1 SEMN, 0 PROMO
      FROM LIVR1 L1
        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 '||(vAnStop*12+vLunaStop)::varchar||' BETWEEN IOA.ALStart and IOA.ALStop  AND IOA.mg &lt;&gt; 5
        INNER JOIN LIVR    L   ON L.CODLIVR     = L1.CODLIVR
        INNER JOIN INTRARI I   ON I.CODINTR     = L.CODINTR
      WHERE L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7) AND L.OPERAT = 1 AND L.ANULAT = 0 '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL)||'
        AND (I.AN *12 + I.LUNA) '||vCondAnLuna||' AND I.DATADOC &lt;= to_date('''||vDataFin||''',''dd.mm.yyyy'')'||vFiltru||'
      UNION ALL -- IESIRI
      SELECT
        N.GEST, NS.CODOBIECT,
        CASE WHEN I.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN 0 ELSE I.CODIES END CODDOC,
        CASE WHEN I.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN 0 ELSE I.TIPDOC END TIPDOC,
        CASE WHEN I.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN '' Stoc initial'' ELSE I.PREFIXDOC||I.NRDOC||''/''||I.DATADOC END DOC,
        CASE WHEN I.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN to_date('''||vDataIni||''',''dd.mm.yyyy'') ELSE I.DATADOC END DATADOC,
        CASE WHEN I.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN -L1.CANT ELSE L1.CANT END CANT,
        CASE WHEN I.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN 1 ELSE -1 END semn'||sPromo||'
      FROM LIVR1 L1
        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 '||(vAnStop*12+vLunaStop)::varchar||' BETWEEN IOA.ALStart and IOA.ALStop  AND IOA.mg &lt;&gt; 5
        INNER JOIN LIVR    L   ON L.CODLIVR     = L1.CODLIVR
        INNER JOIN IESIRI  I   ON I.CODIES      = L.CODIES
        INNER JOIN IESIRI1 I1  ON I1.CODIES1    = L1.CODIES1
      WHERE L.TIPLIVR IN (14, 16, 19, 20, 21, 22, 23, 24) AND L.OPERAT = 1 AND L.ANULAT = 0 '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL)||'
        AND (I.AN *12 + I.LUNA) '||vCondAnLuna||' AND I.DATADOC &lt;= to_date('''||vDataFin||''',''dd.mm.yyyy'')'||vFiltru||'
      UNION ALL -- MISCARI INTERNE
      SELECT
        N.GEST, NS.CODOBIECT,
        CASE WHEN T.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN 0 ELSE T.CODTRANSF END CODDOC,
        CASE WHEN T.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN 0 ELSE T.TIPDOC END TIPDOC,
        CASE WHEN T.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN '' Stoc initial'' ELSE T.PREFIXDOC||T.NRDOC||''/''||T.DATADOC END DOC,
        CASE WHEN T.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN to_date('''||vDataIni||''',''dd.mm.yyyy'') ELSE T.DATADOC END DATADOC,
        CASE WHEN T.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN -L1.CANT ELSE L1.CANT END CANT,
        CASE WHEN T.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN 1 ELSE -1 END semn, 0 PROMO
      FROM LIVR1 L1
        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 '||(vAnStop*12+vLunaStop)::varchar||' BETWEEN IOA.ALStart and IOA.ALStop  AND IOA.mg &lt;&gt; 5
        INNER JOIN LIVR    L   ON L.CODLIVR     = L1.CODLIVR
        INNER JOIN TRANSF  T   ON T.CODTRANSF   = L.CODTRANSF
      WHERE L.TIPLIVR IN (12, 13) AND L.OPERAT = 1 AND L.ANULAT = 0 '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL)||'
        AND (T.AN *12 + T.LUNA) '||vCondAnLuna||' AND T.DATADOC &lt;= to_date('''||vDataFin||''',''dd.mm.yyyy'')'||vFiltru||'
      UNION ALL -- MARIRI DE STOC
      SELECT
        N.GEST, NS.CODOBIECT,
        CASE WHEN I.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN 0 ELSE I.CODIES END CODDOC,
        CASE WHEN I.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN 0 ELSE I.TIPDOC END TIPDOC,
        CASE WHEN I.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN '' Stoc initial'' ELSE I.PREFIXDOC||I.NRDOC||''/''||I.DATADOC END DOC,
        CASE WHEN I.DATADOC &lt; to_date('''||vDataIni||''',''dd.mm.yyyy'') THEN to_date('''||vDataIni||''',''dd.mm.yyyy'') ELSE I.DATADOC END DATADOC,
        L1.CANT, 1 SEMN, 0 PROMO
      FROM LIVR1 L1
        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 '||(vAnStop*12+vLunaStop)::varchar||' BETWEEN IOA.ALStart and IOA.ALStop  AND IOA.mg &lt;&gt; 5
        INNER JOIN LIVR    L   ON L.CODLIVR     = L1.CODLIVR
        INNER JOIN IESIRI  I   ON I.CODIES      = L.CODIES
      WHERE L.TIPLIVR = 15 AND L.OPERAT = 1 AND L.ANULAT = 0 '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL)||'
        AND (I.AN *12 + I.LUNA) '||vCondAnLuna||' AND I.DATADOC &lt;= to_date('''||vDataFin||''',''dd.mm.yyyy'')'||vFiltru||'
    )
  SELECT gest, codobiect, coddoc, tipdoc, sum(cant), (case when tipdoc=0 then 1 else semn end), promo
  FROM b
  GROUP BY gest, codobiect, coddoc, tipdoc, semn, promo';

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, 0, 0);
  DELETE FROM tmp_list_rapstoc WHERE cant = 0;

  DELETE FROM tmp_dinamic_cols;
  INSERT INTO tmp_dinamic_cols(FieldName, Display, INDEXLOCAL)
  SELECT
    'C'||(Row_Number() OVER (ORDER BY O.DENUMIRE))::varchar,
    SubStr(O.DENUMIRE, 1,5)||'/'||SubStr(O.DENUMIRE, 6,5)||'/'||SubStr(O.DENUMIRE,11,5)||'/'||SubStr(O.DENUMIRE,16,5)||'/'||
    SubStr(O.DENUMIRE,21,5)||'/'||SubStr(O.DENUMIRE,26,5)||'/'||SubStr(O.DENUMIRE,31,5)||'/'||SubStr(O.DENUMIRE,36,5)||'/'||O.CODEXTERN::varchar,
    O.CODOBIECT
  FROM (
    SELECT DISTINCT CODOBIECT
    FROM tmp_list_rapstoc
    WHERE coddoc &lt;&gt; 0  --STEF -- EXCLUD STOCURI INITIALE FIINDCA SUNT PREA MULTE SI CRAPA LISTA
  ) X INNER JOIN NARTOBJ O ON O.CODOBIECT = X.CODOBIECT;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest_faramiscari</obj_name>
  <obj_hashval>4d40ee35d1dd61380f472f665336674c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest_faramiscari()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  -- BogdanL 28.07.2020
  return current_setting('PKG_LIST_BASE_REALGEST.FaraMiscari', true)::numeric = 1;
  EXCEPTION WHEN undefined_object then
   return NULL;
END;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest_getallcc</obj_name>
  <obj_hashval>2731edbf69f739cb06e16b631b2cf9dd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest_getallcc()
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
begin
  --BogdanL 29.07.2020
  return current_setting('PKG_LIST_BASE_REALGEST.vAllCC', true)::numeric = 1;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest_ver_col_analiza</obj_name>
  <obj_hashval>f68ce239dabe5fb64e28ccb019e6186e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest_ver_col_analiza(tmpname character varying, nrmax numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vExista  numeric;
  sColList varchar;
  sSep     varchar;
begin
  --BogdanL 27.07.2020
  sColList := null;
  sSep     := '';
  IF  COALESCE(nrmax, 0) &gt; 0 THEN
    FOR i IN 1..nrmax LOOP
       SELECT Count(1) INTO vExista FROM information_schema.columns T
       WHERE  COLUMN_NAME = 'na'||to_char(i,'fm9999') AND  TABLE_NAME = lower(tmpName);

      IF vExista = 0 THEN
        sColList := sColList||sSep||'NA'||to_char(i,'fm9999')||' VARCHAR2(250)';
        sSep     := ', ';
      END IF;
    END LOOP;

    IF sColList IS NOT NULL THEN
      EXECUTE 'ALTER TABLE ' || coalesce(tmpName,'') || ' ADD (' || coalesce(sColList,'') || ')';
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest2_processlist</obj_name>
  <obj_hashval>f04e6f4ee41cb63242e38bee36170f6b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest2_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;
  sSel        varchar;
  sFrom67     varchar;
  sFromAlte   varchar;
  aSubunitate numeric;
  vCondMisc varchar;
  sSold       varchar;
  sPer        varchar;
  CondLunaIni varchar;
  sDinIns     varchar;
  sDinSel     varchar;
  sDinWith    varchar;
  vAnStart    numeric := Trunc((pkg_list_base_realgest_GetAnLunaIni() - 1)  / 12);
  vLunaStart  numeric := pkg_list_base_realgest_GetAnLunaIni() - vAnStart * 12;
  sDoc        varchar;
  sSelDoc     varchar;
  sSelWithDoc varchar;
  sSelNullDoc varchar;
  sGrupDoc    varchar;
  vWith       varchar;
  vAnLunaIni  NUMERIC(5) := pkg_list_base_realgest_GetAnLunaIni();
  vAnLunaFin  NUMERIC(5) := pkg_list_base_realgest_GetAnLunaFin();
  vNrLuni     NUMERIC(5) := vAnLunaFin - vAnLunaIni + 1 ;
BEGIN
  --Florin 29.11.2024 - fixat 64142
  --Florin 28.11.2024 - fixat 64140
  --Florin 04.11.2024 - sinc. Oracle
  --Florin 01.11.2024 - sinc. Oracle
  --Florin 03.04.2023 - fixat 57821
  --Florin 20.02.2023 - fixat 57274, 57276
  --Florin 25.01.2023 - sinc. Oracle
  --BogdanL 29.07.2020
  --Florin 14.04.2021 - sincronizat Oracle (39797)
  gSuplCols := 'ncont cont, ncont sint, nconts conts, nconts sints, ngest g';

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

  IF  pkg_list_base_realgest_GetAnLunaIni() = pkg_list_base_realgest_GetAnLunaFin() THEN
    sPer := '= ' || pkg_list_base_realgest_GetAnLunaFin();
  ELSE
    sPer := 'BETWEEN ' || pkg_list_base_realgest_GetAnLunaIni() || ' AND ' || pkg_list_base_realgest_GetAnLunaFin();
  END IF;
  sDoc        := '';
  sSelNullDoc := '';
  sSelDoc     := '';
  sSelWithDoc := '';
  sGrupDoc    := '';

  IF  PKG_LIST_BASE_REALGEST_GetCuDoc() &gt; 0 THEN
    sDoc        := ',ObsDoc,Document_RG';
    sSelWithDoc := ',PKG_LIST_UTILFISACONT_GetObsDocJurnal(j.codjurnal) ObsDoc,j.document as Document_RG';
    sSelDoc     := ',x.ObsDoc,x.Document_RG as Document_RG';
    sSelNullDoc := ','' '' ObsDoc,'' '' Document_RG';
    sGrupDoc    := ',fnc_array_to_vc3200 (ARRAY_AGG (ObsDoc)) ObsDoc,fnc_array_to_vc3200 (ARRAY_AGG(Document_RG)) Document_RG';
  END IF;
  vCondMisc := '  WHERE X.Misc &gt; 0 ';
  IF pkg_list_base_realgest_GetFaraMiscari() THEN
    vCondMisc := '';
  END IF;

  sSold       := '';
  CondLunaIni := '';

  DELETE FROM tmp_ncontsold;
  DELETE FROM tmp_ncontrul;

  IF (pkg_list_base_realgest_GetCuConturi()) AND ( vLunaStart = 1)
      OR
     (pkg_list_base_realgest_GetAnLunaIni() = current_setting('PKG_GLOBALS.ANINITIAL', true)::numeric * 12 + current_setting('PKG_GLOBALS.LUNAINITIALA', true)::numeric)
  THEN
    INSERT INTO tmp_ncontsold (codcontsold, codcont, soldid, soldic, soldvid, soldvic, an, luna)
      SELECT codcontsold, codcont, soldid, soldic, soldvid, soldvic, an, luna
      FROM ncontsold
      WHERE an = vAnStart AND  luna = 1;
    IF  aSubunitate = 1 THEN
      INSERT INTO tmp_ncontrul(codcontrul, codcont, rulajpd, rulajpc)
      with c1 AS
        (SELECT codcont,
            CASE WHEN  anstart * 12 + lunastart &lt;= pkg_list_base_realgest_GetAnLunaIni() THEN vAnStart   ELSE anstart   END  AN,
            case WHEN  anstart * 12 + lunastart &lt;= pkg_list_base_realgest_GetAnLunaIni() THEN vLunaStart ELSE lunastart END  LUNA
          FROM (
              SELECT  DISTINCT codcont,
                      MIN(AnStart)   OVER (  ORDER BY AnStart , LunaStart )  ANSTART,
                      MIN(LunaStart) OVER (  ORDER BY AnStart , LunaStart )  LUNASTART
              FROM ncont1
              WHERE  AnStart * 12 + LunaStart &lt;= pkg_list_base_realgest_GetAnLunaFin()
             ) A_PG
          )
      SELECT rul.codcontrul, rul.codcont, rul.rulajpd, rul.rulajpc
      FROM c1
      INNER JOIN ncontrul rul ON  rul.codcont = c1.codcont AND  rul.an = c1.an AND  rul.luna = c1.luna;
    ELSE
      INSERT INTO tmp_ncontrul(codcontrul, codcont, rulajpd, rulajpc)
      with c1 AS
        (SELECT codcont,
            case  WHEN  anstart * 12 + lunastart &lt;= pkg_list_base_realgest_GetAnLunaIni() THEN vAnStart   ELSE anstart   END  AN,
            CASE  WHEN  anstart * 12 + lunastart &lt;= pkg_list_base_realgest_GetAnLunaIni() THEN vLunaStart ELSE lunastart END  LUNA
        FROM (
          SELECT  DISTINCT codcont,
                MIN(AnStart)   OVER (  ORDER BY AnStart , LunaStart )  ANSTART,
                MIN(LunaStart) OVER (  ORDER BY AnStart , LunaStart )  LUNASTART
          FROM ncont1
          WHERE AnStart * 12 + LunaStart &lt;= pkg_list_base_realgest_GetAnLunaFin()
        ) B_PG
        )
      SELECT rul.codcontrul, rul.codcont, ruls.rulajpd, ruls.rulajpc
      FROM c1
        INNER JOIN ncontrul    rul  ON  rul.codcont     = c1.codcont AND  rul.an = c1.an AND  rul.luna = c1.luna
        INNER JOIN ncontrulsub ruls ON  ruls.codcontrul = rul.codcontrul
      WHERE ruls.subunitatea = aSubunitate;
    END IF;
    CondLunaIni := ' LEFT JOIN tmp_ncontsold sold on sold.codcont = s.codcont
                     LEFT JOIN tmp_ncontrul  rul  on rul.codcont  = s.codcont';
    sSold       := ' + COALESCE(sold.SoldID,0) - COALESCE(sold.SoldIC,0) + COALESCE(rul.rulajpd,0) - COALESCE(rul.rulajpc,0)';
  END IF;

  PERFORM PKG_GLOBALS_SetSeparator(',');

  IF pkg_list_base_realgest_GetDetLunara() and pkg_list_base_realgest_getdetccost() THEN
    if pkg_list_base_realgest_getallcc() then
      if pkg_list_base_realgest_getccinactive() then
        FOR vRec IN (
           with recursive vRec(fieldname, LEVEL, anluna) as (
            SELECT 'D'||1 fieldname, 1 AS LEVEL, pkg_list_base_realgest_GetAnLunaIni() anluna
            UNION ALL
             SELECT 'D'||level fieldname, LEVEL+ 1 AS LEVEL, pkg_list_base_realgest_GetAnLunaIni()+LEVEL-1 anluna
           FROM vrec v where v.LEVEL &lt; 1
        )
      select c.fieldname||'_'||v.fieldname field, c.codcentru, v.anluna
      FROM (
        SELECT 'C'||to_char(CODCENTRU) fieldname, codcentru
           FROM CENTRECOST
           WHERE CODCENTRU &gt; 0
           UNION ALL
           SELECT 'C0' fieldname, 0 CODCENTRU
           ORDER BY CODCENTRU
          ) c, vrec v
        )
        LOOP
          sDinIns  := sDinIns ||','||vRec.field;
          sDinSel  := sDinSel ||',x.'||vRec.field;
          sDinWith := sDinWith||',SUM(CASE WHEN COALESCE(codcentru,0)='||vRec.CODCENTRU||' AND ANLUNA = '||vRec.ANLUNA||' THEN COALESCE(valoare,0) C ELSE 0 END) '||vRec.field;
        END LOOP;
      else
        FOR vRec IN (
           with recursive vRec(fieldname, LEVEL, anluna) as (
            SELECT 'D'||1 fieldname, 1 AS LEVEL, pkg_list_base_realgest_GetAnLunaIni() anluna
            UNION ALL
             SELECT 'D'||level fieldname, LEVEL+ 1 AS LEVEL, pkg_list_base_realgest_GetAnLunaIni()+LEVEL-1 anluna
           FROM vrec v where v.LEVEL &lt; 1
        )
          select c.fieldname||'_'||v.fieldname field, c.codcentru, v.anluna
          FROM
          (
          SELECT 'C'||to_char(CODCENTRU) fieldname, codcentru
           FROM CENTRECOST
           WHERE CODCENTRU &gt; 0
           UNION ALL
           SELECT 'C0' fieldname, 0 CODCENTRU
           ORDER BY CODCENTRU
          ) c, vrec v
        )
        LOOP
          sDinIns  := sDinIns ||','||vRec.field;
          sDinSel  := sDinSel ||',x.'||vRec.field;
          sDinWith := sDinWith||',SUM(CASE WHEN COALESCE(codcentru,0)='||vRec.CODCENTRU||' AND ANLUNA = '||vRec.ANLUNA||' THEN COALESCE(valoare,0) ELSE 0 END) '||vRec.field;
        END LOOP;
      end if;
    ELSE
      if pkg_list_base_realgest_getccinactive() then
        FOR vRec IN (
           with recursive vRec(fieldname, LEVEL, anluna) as (
            SELECT 'D'||1 fieldname, 1 AS LEVEL, pkg_list_base_realgest_GetAnLunaIni() anluna
            UNION ALL
             SELECT 'D'||level fieldname, LEVEL+ 1 AS LEVEL, pkg_list_base_realgest_GetAnLunaIni()+LEVEL-1 anluna
           FROM vrec v where v.LEVEL &lt; 1
        )
        select c.fieldname||'_'||v.fieldname field, c.codcentru, v.anluna
          FROM
        (
          SELECT 'C'||to_char(CODCENTRU) fieldname, codcentru
           FROM CENTRECOST
           WHERE CODCENTRU &gt; 0
           UNION ALL
           SELECT 'C0' fieldname, 0 CODCENTRU
           ORDER BY CODCENTRU
          ) c, vrec v
        )
        LOOP
          sDinIns  := sDinIns ||','||vRec.field;
          sDinSel  := sDinSel ||',x.'||vRec.field;
          sDinWith := sDinWith||',SUM(CASE WHEN codcentru='||vRec.CODCENTRU||' AND ANLUNA = '||vRec.ANLUNA||' THEN COALESCE(valoare,0) ELSE 0 END) '||vRec.field;
        END LOOP;
      ELSE
        FOR vRec IN (
          with recursive vRec(fieldname, LEVEL, anluna) as (
            SELECT 'D'||1 fieldname, 1 AS LEVEL, pkg_list_base_realgest_GetAnLunaIni() anluna
            UNION ALL
             SELECT 'D'||level fieldname, LEVEL+ 1 AS LEVEL, pkg_list_base_realgest_GetAnLunaIni()+LEVEL-1 anluna
           FROM vrec v where v.LEVEL &lt; 1
        )
          SELECT c.fieldname||'_'||v.fieldname field, c.codcentru, v.anluna
          FROM
          (
          SELECT 'C'||to_char(CODCENTRU) fieldname, codcentru
           FROM CENTRECOST
           WHERE CODCENTRU &gt; 0
           UNION ALL
           SELECT 'C0' fieldname, 0 CODCENTRU
           ORDER BY CODCENTRU
          ) c, vrec v
        )
        LOOP
          sDinIns  := sDinIns ||','||vRec.field;
          sDinSel  := sDinSel ||',x.'||vRec.field;
          sDinWith := sDinWith||',SUM(CASE WHEN codcentru='||vRec.CODCENTRU||' AND ANLUNA = '||vRec.ANLUNA||' THEN COALESCE(valoare,0) ELSE 0 END) '||vRec.field;
        END LOOP;
      END IF;
    END IF;
  ELSE
  IF (PKG_LIST_BASE_REALGEST_GetDetCCost()) THEN
    IF (PKG_LIST_BASE_REALGEST_GetAllCC()) THEN
      IF (pkg_list_base_realgest_getccinactive()) THEN
        FOR vRec IN (
            SELECT To_Char(row_number() over(), 'fm999') NR, CODCENTRU
            FROM CENTRECOST
            WHERE CODCENTRU &gt; 0
            UNION ALL
            SELECT '0' NR, 0 CODCENTRU
            ORDER BY CODCENTRU
        )
        LOOP
          sDinIns  := coalesce(sDinIns ,'') || ',C'   || coalesce(vRec.Nr::varchar ,'');
          sDinSel  := coalesce(sDinSel ,'') || ',x.C' || coalesce(vRec.Nr::varchar ,'');
          sDinWith := COALESCE(sDinWith, '') ||',SUM(case when COALESCE(codcentru,0) = '||vRec.CODCENTRU||' then coalesce(valoare,0)end) C'||vRec.Nr;
        END LOOP;
      ELSE
        FOR vRec IN (
          SELECT To_Char(row_number() over(), 'fm999') NR, CODCENTRU
          FROM CENTRECOST
          WHERE CODCENTRU &gt; 0
          UNION ALL
          SELECT '0' NR, 0 CODCENTRU
          ORDER BY CODCENTRU
        )
        LOOP
          sDinIns  := coalesce(sDinIns ,'') || ',C'   || coalesce(vRec.Nr::varchar ,'');
          sDinSel  := coalesce(sDinSel ,'') || ',x.C' || coalesce(vRec.Nr::varchar ,'');
          sDinWith := coalesce(sDinWith,'') || ',SUM(case when codcentru = ' || vRec.CODCENTRU::varchar || ' then coalesce(valoare,0) else 0 end ) C'
                      || coalesce(vRec.Nr::varchar ,'');
        END LOOP;
      END IF;
    ELSE
      IF (pkg_list_base_realgest_getccinactive()) THEN
        FOR vRec IN (
            SELECT To_Char(row_number() over(), 'fm999') NR, CODCENTRU
            FROM CENTRECOST
            WHERE CODCENTRU &gt; 0 AND CODCENTRU IN (SELECT VALOARE :: NUMERIC FROM TMP_MANEVRA_LISTE WHERE Upper(FILTRU) = 'CODCENTRU')
            ORDER BY CODCENTRU
              )
        LOOP
          sDinIns  := coalesce(sDinIns ,'') || ',C'   || coalesce(vRec.Nr::varchar ,'');
          sDinSel  := coalesce(sDinSel ,'') || ',x.C' || coalesce(vRec.Nr::varchar ,'');
          sDinWith := coalesce(sDinWith,'') || ',SUM( case when codcentru = ' || vRec.CODCENTRU::varchar || ' then coalesce(valoare,0) else 0 end) C'
                                              || coalesce(vRec.Nr::varchar ,'');
        END LOOP;
      ELSE
        FOR vRec IN (
            SELECT To_Char(row_number() over(), 'fm999') NR, CODCENTRU
            FROM CENTRECOST
            WHERE
                CODCENTRU &gt; 0 AND
                CODCENTRU IN (SELECT VALOARE::NUMERIC FROM TMP_MANEVRA_LISTE WHERE Upper(FILTRU) = 'CODCENTRU') AND COALESCE(INACTIV, 0) = 0
            ORDER BY CODCENTRU
            )
        LOOP
          sDinIns  := coalesce(sDinIns ,'') || ',C'   || coalesce(vRec.Nr::varchar ,'');
          sDinSel  := coalesce(sDinSel ,'') || ',x.C' || coalesce(vRec.Nr::varchar ,'');
          sDinWith := coalesce(sDinWith,'') || ',SUM( case when codcentru = ' || vRec.CODCENTRU::varchar || ' then COALESCE(valoare,0) else 0 end) C'
                                                                  || coalesce(vRec.Nr::varchar ,'');
        END LOOP;
      END IF;
    END IF;
  ELSE
    IF (PKG_LIST_BASE_REALGEST_GetDetLunara()) then
        with recursive vRec as (
            select  1 as level
            union all
              select v.level+1
            from vRec v where level &lt; pkg_list_base_realgest_GetAnLunaFin() - pkg_list_base_realgest_GetAnLunaIni() + 1
        )
        select
          STRING_AGG('D'   || level,','),
          STRING_AGG('x.D' || level,','),
          STRING_AGG('SUM(case when anluna = ' || coalesce((pkg_list_base_realgest_GetAnLunaIni() + LEVEL - 1)::varchar,'') || ' then coalesce(valoare,0) else 0 end) D' || level,',')
          INTO
              sDinIns,
              sDinSel,
              sDinWith
         from vRec ;

      sDinIns  := ',' || coalesce(sDinIns ,'');
      sDinSel  := ',' || coalesce(sDinSel ,'');
      sDinWith := ',' || coalesce(sDinWith,'');
    END IF;
  END IF;
END IF;

  sDinWith := coalesce(sDinWith,'') || coalesce(sGrupDoc,'');

  sInsert := 'INSERT INTO ' || tmpName || '(
              SimbCont, SimbSint, DenCont, DenSint, Valoare, Gest, Den_subunit, Tip '|| coalesce(sDoc,'') || coalesce(sDinIns,'') || gUserFields||')';

  sFrom67 := '
      SELECT
        s.codcont, s.codsint, s.codconts, s.codsints, nvl(j.valoare, 0) valoare, j.gest,
        CASE WHEN NVL(j.codcentru,0) = 0 THEN Nvl(s.codcentru,0) ELSE j.codcentru END codcentru, j.an*12+j.luna anluna, (case when j.valoare isNULL then 0 when j.valoare = 0 then 0 else 1 end) Misc, SUB.DEN_SUBUNIT'||COALESCE(sSelWithDoc, '')||'
      FROM Sintetice s LEFT JOIN jurnal j ON s.tipcont IN (0,2) AND s.codcont = j.contd AND j.tipdoc &lt;&gt; 32 '||coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'J', null, null, (PKG_LIST_BASE_REALGEST_getSubunit()))),'')||' AND J.AN*12+J.LUNA '||sPer||'
      LEFT JOIN NSUBUNIT SUB ON SUB.CODSUBUNIT = J.SUBUNITATEA
      UNION ALL
      SELECT
        s.codcont, s.codsint, s.codconts, s.codsints, nvl(-j.valoare, 0) valoare, j.gest,
        CASE WHEN NVL(j.codcentru,0) = 0 THEN Nvl(s.codcentru,0) ELSE j.codcentru END codcentru, j.an*12+j.luna anluna, (case when j.valoare isNULL then 0 when j.valoare = 0 then 0 else 1 end) Misc, SUB.DEN_SUBUNIT'||COALESCE(sSelWithDoc, '')||'
      FROM Sintetice s LEFT JOIN jurnal j ON s.tipcont IN (1,2) AND s.codcont = j.contc AND j.tipdoc &lt;&gt; 32 '||coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'J', null, null, (PKG_LIST_BASE_REALGEST_getSubunit()))),'')||' AND J.AN*12+J.LUNA '||sPer||'
        LEFT JOIN NSUBUNIT SUB ON SUB.CODSUBUNIT = J.SUBUNITATEA';

  sFromAlte := '
      SELECT
        s.codcont, s.codsint, s.codconts, s.codsints, NVL(j.valoare,0)*(case when s.tipcont = 1 then -1 else 1 end) valoare, 0 gest,
        CASE WHEN NVL(j.codcentru,0) = 0 THEN Nvl(s.codcentru,0) ELSE j.codcentru END codcentru, j.an*12+j.luna anluna, (case when j.valoare isNULL then 0 when j.valoare = 0 then 0 else 1 end) Misc, SUB.DEN_SUBUNIT'||COALESCE(sSelWithDoc, '')||'
      FROM sintetice s LEFT JOIN JURNAL J ON J.Contd = S.CodCont
        LEFT JOIN NSUBUNIT SUB ON SUB.CODSUBUNIT = J.SUBUNITATEA
      UNION ALL
      SELECT
        s.codcont, s.codsint, s.codconts, s.codsints, Nvl(j.valoare,0)*(case when s.tipcont = 1 then 1 else -1 end) valoare, 0 gest,
        CASE WHEN NVL(j.codcentru,0) = 0 THEN Nvl(s.codcentru,0) ELSE j.codcentru END codcentru, j.an*12+j.luna anluna, (case when j.valoare isNULL then 0 when j.valoare = 0 then 0 else 1 end) Misc, SUB.DEN_SUBUNIT'||COALESCE(sSelWithDoc, '')||'
      FROM sintetice s LEFT JOIN JURNAL J ON J.Contc = S.CodCont
      LEFT JOIN NSUBUNIT SUB ON SUB.CODSUBUNIT = J.SUBUNITATEA
      UNION ALL
      SELECT
        s.codcont, s.codsint, s.codconts, s.codsints, (nvl(sold.SoldID,0) - nvl(sold.SoldIC,0) + nvl(rul.rulajpd,0) - nvl(rul.rulajpc,0))*(case when s.tipcont = 1 then -1 else 1 end) valoare, 0 gest,
        Nvl(s.codcentru,0) codcentru, '||coalesce(pkg_list_base_realgest_GetAnLunaIni()::varchar,'')||' anluna, 0 Misc, ''...nedefinit...'' den_subunit '||COALESCE(sSelNullDoc, '')||'
      FROM sintetice s
        LEFT JOIN tmp_ncontsold sold on sold.codcont = s.codcont
        LEFT JOIN tmp_ncontrul rul on rul.codcont = s.codcont';

  sSel := '
    ) a_pg
    GROUP BY codcont, codsint, codconts, codsints, gest, den_subunit)
  SELECT cont.simbol, sint.simbol, cont.den_cont, sint.den_cont, x.valoare, g.den_gest, x.den_subunit, (case when cont.tipcont = 0 then ''Activ'' when cont.tipcont =1 then ''Pasiv'' when cont.tipcont =2 then ''Bifunctional'' end ) '||COALESCE(sSelDoc, '')||COALESCE(sDinSel, '')||gUserAlias||'
  FROM x
          LEFT JOIN ncont  cont  ON cont.codcont   = x.codcont
          LEFT JOIN ncont  sint  ON sint.codcont   = x.codsint
          LEFT JOIN nconts conts ON conts.codconts = x.codconts
          LEFT JOIN nconts sints ON sints.codconts = x.codsints
          LEFT JOIN ngest  g     ON g.codgest      = x.gest' || gSuplJoins;
   vWith := pkg_list_base_realgest2_swith('= 6', sDinWith);
   PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(vWith,'') || coalesce(sFrom67,'') || coalesce(sSel,'') || coalesce(vCondMisc,''), aListID, aListVer);

  vWith := pkg_list_base_realgest2_swith('= 7', sDinWith);
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(vWith,'') || coalesce(sFrom67,'') || coalesce(sSel,'') || coalesce(vCondMisc,''), aListID, aListVer);

  IF (PKG_LIST_BASE_REALGEST_GetExtra()) THEN
    vWith := pkg_list_base_realgest2_swith('= 8', sDinWith);
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(vWith,'') || coalesce(sFrom67,'') || coalesce(sSel,'') || coalesce(vCondMisc,''), aListID, aListVer);
    vWith := pkg_list_base_realgest2_swith('= 9', sDinWith);
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(vWith,'') || coalesce(sFrom67,'') || coalesce(sSel,'') || coalesce(vCondMisc,''), aListID, aListVer);
  END IF;
  IF (pkg_list_base_realgest_GetCuConturi()) THEN
    vWith := pkg_list_base_realgest2_swith('NOT in (6,7,8,9)', sDinWith);
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(vWith,'') || coalesce(sFromAlte,'') || coalesce(sSel,'') || coalesce(vCondMisc,''), aListID, aListVer);
  END IF;
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest3_processlist</obj_name>
  <obj_hashval>895e5849688e90f0d468022109e4a6cb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest3_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;
  sInsertDC   varchar;
  sSelectDC   varchar := '';
  sJoinDC     varchar := '';
  i           numeric;
  p_Plan      numeric;
  p_LunaIni   numeric;
  p_LunaFin   numeric;
  p_Subunit   numeric;
BEGIN
  --Adina 09.03.2021 - prc_al_check + 1 for
  --BogdanL 28.07.2020
  gSuplCols := 'NGEST NG, NSUBUNIT NSUBUNIT, NCONT CONTD, NCONT CONTC, CENTRECOST CC, NCLASEG CLSG, NCONTS CS, ANALIZANOD ANOD, ANALIZA ANALIZ, DESCRIPTORI1 ADESC1, DESCRIPTORI ADESC,'||
               'NARTOBJ OBJ, NART ART, NARTCLI ARTCLI, NCLASEA CLSA, NCLASEAS CLSAS, PRETM PRET, NMONEDE MONLINK, NMONEDE MONDOC, NARTOBJTRAD TRAD, NPART P, NUM NUM,'||
               'NAGENDA SED,NPARTCODFISC CIF,NCLASEP CLSP, tmp_lst_jurnal1 J';

  call pkg_list_struct_startsuplcols();

  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'  , 'PD'        , 'PD.CODPART = P.CODPART',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI1'   , 'IES1'      , 'J.CODDOC1 = IES1.CODIES1 AND J.TIPDOC IN (14,15,19,20,21,22,23,24,26)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI1EXT', 'IES1EXT'   , 'IES1EXT.CODIES1 = IES1.CODIES1'          ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRIEXT' , 'IESEXT'    , 'IESEXT.CODIES = IES1.CODIES'             ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NC1'       , 'NC1'       , 'J.CODDOC1 = NC1.CODNC1 AND J.TIPDOC = 35',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NC1EXT'    , 'NC1EXT'    , 'NC1EXT.CODNC1 = NC1.CODNC1'              ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCEXT'     , 'NCEXT'     , 'NCEXT.CODNC = NC1.CODNC'                 ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TREZOR1'   , 'TREZOR1'   , 'J.CODDOC1 = TREZOR1.CODTREZOR1 AND J.TIPDOC IN (29,30,31,33)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'TREZOR1EXT', 'TREZOR1EXT', 'TREZOR1EXT.CODTREZOR1 = TREZOR1.CODTREZOR1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TREZOREXT' , 'TREZOREXT' , 'TREZOREXT.CODTREZOR = TREZOR1.CODTREZOR'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARI1'  , 'INTR1'     , 'J.CODDOC1 = INTR1.CODINTR1 AND J.TIPDOC IN (1,2,3,4,5,6,7,9)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARI1F' , 'INTR1EXT'  , 'INTR1EXT.CODINTR1 = INTR1.CODINTR1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARIF'  , 'INTREXT'   , 'INTREXT.CODINTR = INTR1.CODINTR'   ,NULL);

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

  CALL PRC_AL_CHECK('npers1');

  p_Plan    := PKG_LIST_BASE_REALGEST_GetPlan();
  p_LunaIni := PKG_LIST_BASE_REALGEST_GetAnLunaIni();
  p_LunaFin := PKG_LIST_BASE_REALGEST_GetAnLunaFin();
  p_Subunit := PKG_LIST_BASE_REALGEST_GetSubunit();

  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((SELECT pkg_list_base_utils_NIVELE_ANALIZA.WME_RESULT FROM pkg_list_base_utils_NIVELE_ANALIZA(NULL,NULL)), 0));

  IF  COALESCE((SELECT pkg_list_base_utils_NIVELE_ANALIZA.WME_RESULT FROM pkg_list_base_utils_NIVELE_ANALIZA(NULL,NULL)), 0) &gt; 0 THEN
    sJoinDC := ' LEFT JOIN (
            SELECT       CodAnalizaNod';
    FOR i IN 1..(SELECT pkg_list_base_utils_NIVELE_ANALIZA.WME_RESULT FROM pkg_list_base_utils_NIVELE_ANALIZA(NULL,NULL))::integer LOOP
      sInsertDC := COALESCE(sInsertDC,'')||', NA'   ||i::varchar;
      sSelectDC := COALESCE(sSelectDC,'')||', DC.NA'||i::varchar;
      sJoinDC := sJoinDC ||',
        Max(CASE WHEN nivel = '||i::varchar||' THEN valoare ELSE NULL end) NA'||i::varchar;
    END LOOP;
    sJoinDC := coalesce(sJoinDC,'') || ' FROM TMP_TREE_ANALIZANOD
                  GROUP BY CodAnalizaNod
                 ) DC ON DC.CodAnalizaNod = j.CodAnalizaNod ';
  END IF;

  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || ' (
              NAV_CodDoc, NAV_CodDoc1, NAV_TipDoc,
              Doc, DataDoc,
              SimbCont,
              ValChelt,
              ValVenit,
              ValReal,
              CheltVal,
              VenitVal,
              RealVal,
              DenGest, DenAct, Obs, SimbCont_psec, NameCont_psec, An, Luna, CentruCost,
              DENCONT, TipAloc, TipChelt,
              ObsDoc,
              Partener, DATACREARE, ARTICOL, DocLegatura, Cant, Pret, CONT, CORESP,
              EXPLICATII, Subunitatea, TIPDOC, ObsLinie,
              IFRS, IFRSV, C_IFRS, V_IFRS, C_IFRSV, V_IFRSV, Doc_TVA, Doc_Val,
              Doc_Curs ' || coalesce(sInsertDC,'') || gUserFields || ')
          SELECT
          CASE WHEN j.tipdoc = 35 AND PKG_GLOBALS_GET_DREPT_SALARIZARE() = 0 AND NC.JurnalTVA = 5 THEN 0 ELSE j.coddoc END,
          CASE WHEN j.tipdoc = 35 AND PKG_GLOBALS_GET_DREPT_SALARIZARE() = 0 AND NC.JurnalTVA = 5 THEN 0 WHEN j.TipDoc IN (29,30,31,33) THEN j.indexlocal ELSE 0 END,
          CASE WHEN j.tipdoc = 35 AND PKG_GLOBALS_GET_DREPT_SALARIZARE() = 0 AND NC.JurnalTVA = 5 THEN 0 ELSE j.tipdoc END,
          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,
          CASE when contc.clasa in (6, 7) then j.valoare  else 0 END,
          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,
          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,
          NG.den_gest DenGest, ACT.Den_Activit, J.Obs, cs.simbol, cs.name, J.An, J.Luna, CC.Denumire,
          CASE WHEN contd.clasa IN (6, 7) THEN contd.den_cont ELSE contc.den_cont END,
          CASE WHEN COALESCE(CC.CodCentru,0) &lt;&gt; 0 THEN
            (Case  When COALESCE(CC.TipAloc,0)=0 then ''Alocabil in calcul pret''
                When COALESCE(CC.TipAloc,0)=1 then ''Nealocabil in calcul pret''
                When COALESCE(CC.TipAloc,0)=2 then ''Fara inregistrari clasa 9'' end)
          END,
          CASE
              WHEN CC.TipChelt =  1 then ''Activitate de baza''
              WHEN CC.TipChelt =  2 then ''Cheltuieli indirecte - regie fixa''
              WHEN CC.TipChelt =  3 then ''Cheltuieli indirecte - regie variabila''
              WHEN CC.TipChelt = 11 then ''Cheltuieli auxiliare''
              WHEN CC.TipChelt = 12 then ''Cheltuieli generale de administratie''
              WHEN CC.TipChelt = 13 then ''Cheltuieli de desfacere''
              WHEN CC.TipChelt = 14 then ''Cheltuieli indirecte comune''
          END,' || coalesce(CASE  WHEN (PKG_LIST_BASE_REALGEST_FaraMiscari()) THEN
                        'CASE WHEN j.TipDoc IN (29,30,31,33) then pkg_list_base_utils_getobsdoc(j.indexlocal, j.tipdoc)
                              ELSE pkg_list_base_utils_getobsdoc(j.coddoc, j.tipdoc) END'
                     ELSE 'NULL'
                     END ::varchar ,'') || ' ObsDoc,
          P.Den_Part, j.DATACREARE, j.ARTICOL, j.DocLegatura, j.Cant, j.Pret, contd.simbol, contc.simbol,
          j.obs, nsubunit.den_subunit,
          (select PKG_LIST_BASE_UTILS_DECODE_TIPDOC.wme_result from PKG_LIST_BASE_UTILS_DECODE_TIPDOC(null,j.TIPDOC)),
          j.ObsLinie,
          CASE WHEN contd.clasa in (6, 7) THEN 1 ELSE -1 END * j.valoare_ifrs,
          CASE WHEN contd.clasa in (6, 7) THEN 1 ELSE -1 END * j.valoarev_ifrs,
          CASE when contd.clasa in (6, 7) then CASE WHEN contd.clasa in (6, 7) THEN 1 ELSE -1 END * COALESCE(j.valoare_ifrs ,0) else 0 END,
          CASE when contc.clasa in (6, 7) then CASE WHEN contd.clasa in (6, 7) THEN 1 ELSE -1 END * COALESCE(j.valoare_ifrs ,0) else 0 END,
          CASE when contd.clasa in (6, 7) then CASE WHEN contd.clasa in (6, 7) THEN 1 ELSE -1 END * COALESCE(j.valoarev_ifrs,0) else 0 END,
          CASE when contc.clasa in (6, 7) then CASE WHEN contd.clasa in (6, 7) THEN 1 ELSE -1 END * COALESCE(j.valoarev_ifrs,0) else 0 END,
          j.TVADoc, j.ValDoc,
          (case when COALESCE(j.Curs,0) = 0 then 1 else COALESCE(j.curs,0) end) ' || coalesce(sSelectDC,'') || gUserAlias || '
      FROM tmp_lst_jurnal1 J
          INNER JOIN NCONT        CONTC   ON j.codcontc                 = contc.codcont
          INNER JOIN NCONT        CONTD   ON j.codcontd                 = contd.codcont
          LEFT  JOIN NPART        P       ON P.CODPART                  = J.CODPART
          LEFT  JOIN NARTOBJ      OBJ     ON J.CODOBIECT                = OBJ.CODOBIECT
          LEFT  JOIN NART         ART     ON ART.CODARTICOL             = OBJ.CODARTICOL
          LEFT  JOIN NUM          NUM     ON ART.UM                     = NUM.CODUM
          LEFT  JOIN NARTCLI      ARTCLI  ON ARTCLI.CODOBIECT           = OBJ.CODOBIECT AND ARTCLI.CODPART = J.CODPART
          LEFT  JOIN NCLASEA      CLSA    ON CLSA.CODCLASEA             = ART.CLASA
          LEFT  JOIN NCLASEAS     CLSAS   ON CLSAS.CODCLASEAS           = ART.CLASASTATIST
          LEFT  JOIN PRETM        PRET    ON PRET.CODOBIECT             = OBJ.CODOBIECT AND PRET.SUBUNITATEA = J.SUBUNITATEA AND PRET.IMPLICIT = 1
          LEFT  JOIN NMONEDE      MONLINK ON COALESCE(J.CODMONEDA,0)    = MONLINK.CODMONEDA
          LEFT  JOIN NMONEDE      MONDOC  ON COALESCE(J.CODMONEDADOC,0) = MONDOC.CODMONEDA
          LEFT  JOIN NARTOBJTRAD  TRAD    ON TRAD.CODOBIECT             = OBJ.CODOBIECT AND TRAD.CODLIMBA = COALESCE((fnc_GetValConstantaLucru(''LimbaDenArt''))::numeric, 0)
          LEFT  JOIN NC                   ON NC.CODNC                   = J.CODDOC AND J.TIPDOC = 35
          LEFT  JOIN NGEST        NG      ON COALESCE(j.gest, 0)        = ng.codgest
          LEFT  JOIN NACTIVIT     ACT     ON ng.codactivit              = act.codactivit
          LEFT  JOIN CENTRECOST   CC      ON j.codcentru                = cc.codcentru
          LEFT  JOIN NSUBUNIT             ON j.subunitatea              = nsubunit.codsubunit
          LEFT  JOIN NCLASEG      CLSG    ON NG.codclasa                = clsg.codclaseg
          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 ANALIZANOD   ANOD    ON anod.codanalizanod         = j.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
          LEFT  JOIN NAGENDA      SED     ON SED.CODAGENDA              = J.CODAGENDA
          LEFT  JOIN NPARTCODFISC CIF     ON CIF.COD_CODFISCAL          = J.COD_CODFISCAL
          LEFT  JOIN NCLASEP      CLSP    ON CLSP.CODCLASEP             = P.CODCLASA' || coalesce(sJoinDC,'') || coalesce(gSuplJoins,'') || '
      WHERE J.AN*12 + J.LUNA BETWEEN ' || p_LunaIni || ' AND ' || p_LunaFin || '
        AND (J.TipDoc &lt;&gt; 32 OR (J.TipDoc = 32 AND J.CodDoc = 1)) '
          || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'J',NULL,NULL, p_Subunit)),'');

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_reclamatii_setjoinuri</obj_name>
  <obj_hashval>2feb76e5859cb3b522c175b809b56b46</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_reclamatii_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 15.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec (current_setting ('PKG_LIST_BASE_RECLAMATII.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_reganalitic_processlist</obj_name>
  <obj_hashval>9a87c310d5fdb6ecf43122deb0a96901</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_reganalitic_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert   VARCHAR(10000);
  sSelect   VARCHAR(30000);
  p_Plan    NUMERIC(1);
  p_LunaIni NUMERIC(5);
  p_LunaFin NUMERIC(5);
  p_Subunit NUMERIC(20);
  p_Index   BOOLEAN;
  Niv       NUMERIC(10);
  gSuplCols     varchar := 'TMP_LST_JURNAL1 T, NPART P,NAGENDA SED,NPARTCODFISC CIF,NCLASEP CLSP,NARTOBJ OBJ, ANALIZANOD ANOD,ANALIZA ANALIZ,DESCRIPTORI1 ADESC1,DESCRIPTORI ADESC';
  gUserFields   VARCHAR := '';
  gUserAlias    VARCHAR := '';
  gNullAlias    VARCHAR := '';
  gSuplJoins    VARCHAR := '';
BEGIN
  --Florin 09.11.2023
  CALL pkg_list_struct_StartSuplCols();
  CALL pkg_list_struct_AddSuplTabs(gSuplCols, 'NPARTDET',   'PD',   'PD.CODPART = P.CODPART');
  CALL pkg_list_struct_AddSuplTabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = OBJ.CODOBIECT');
  CALL pkg_list_struct_AddSuplTabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = OBJ.CODOBIECT');
  CALL pkg_list_struct_AddSuplTabs(gSuplCols, 'NCONT1', 'C1D', 'C1D.CODCONT1 = 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');
  CALL pkg_list_struct_AddSuplTabs(gSuplCols, 'NCONT1', 'C1C', 'C1C.CODCONT1 = 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');
  CALL pkg_list_struct_AddSuplTabs(gSuplCols, 'NCONTS', 'CSC', 'CSC.CODCONTS = C1C.CONTSECUNDAR');
  CALL pkg_list_struct_AddSuplTabs(gSuplCols, 'TMP_UTILIZATOR', 'UT', 'UT.CODUTILIZATOR = T.USERID');
  CALL pkg_list_struct_GetSuplCols(aLISTID,alistver,gUserFields,gUserAlias,gNullAlias,gSuplJoins,gSuplCols);

  p_Plan    := (SELECT wme_result FROM pkg_list_base_regjurnal_p_Plan(NULL, NULL));
  p_LunaIni := (SELECT wme_result FROM pkg_list_base_regjurnal_p_LunaIni(NULL, NULL));
  p_LunaFin := (SELECT wme_result FROM pkg_list_base_regjurnal_p_LunaFin(NULL, NULL));
  p_Index   := pkg_list_base_regjurnal_isIndex();

  p_Subunit := CASE WHEN pkg_list_base_regjurnal_SubCurenta() = 1 THEN GETSUBUNITATE() ELSE 1 END;
  PERFORM pkg_list_utilfisacont_UMPLE_TMP_LST_JURNAL1(p_Plan, p_LunaIni, p_LunaFin, p_Subunit, aLISTID);

  sInsert :=
  'INSERT INTO '||TMPNAME||'(
     NAV_CodDoc,
     NAV_TipDoc,
     CodAnalizaNod,
     NodParinte,
     Nivel,
     Partener,
     DOC,
     DATADOC,
     ARTICOL,
     DocLegatura,
     Cant,
     Pret,
     VALOARE,
     CONT,
     CORESP,
     DATACREARE,
     SUBUNITATEA,
     EXPLICATII,
     GESTIUNE,
     ORDINE,
     CENTRUCOST,
     CENTRUCOSTSIMB,
     TIPDOC,
     IDXNOD,
     NOD,
     ANALIZA,
     COPII
    '||gUserFields||')';
  sSelect := '
  select
    t.coddoc,
    t.tipdoc,
    analiz.codanaliza,
    case when v.nivel = 1 then -1 else v.NodParinte end,
    v.Nivel,
    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,
    PKG_LIST_BASE_UTILS_DECODE_TIPDOC(t.TIPDOC),
    v.simbol,
    LPAD(
    case
      when v.NIVEL=1 then ''• ''
      when v.NIVEL=2 then ''- ''
      when v.NIVEL=3 then ''~ ''
      when v.NIVEL=4 then ''&lt; ''
      when v.NIVEL=5 then ''&gt; ''
      when v.NIVEL=5 then ''^ ''
      else ''*''
    end||adesc1.valoare,
    V.NIVEL*5+LENGTH(adesc1.valoare),'' ''
    ),
    ANALIZ.DEN_ANALIZA,
    (SELECT COUNT(*) FROM V_NoduriAnaliza VV WHERE VV.NODPARINTE = V.CODANALIZANOD) '||gUserAlias||'
  from V_NoduriAnaliza v
       left join tmp_lst_jurnal1 t on v.codanalizanod = t.codanalizanod
       left join ncont CD on CD.codcont = t.codcontd
       left join ncont CC on CC.codcont = t.codcontc
       left join nsubunit s on t.subunitatea = s.codsubunit
       LEFT  JOIN ngest ng on ng.codgest = NVL(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 = v.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'||
  gSuplJoins||'
  where v.codanalizanod &gt; 0';

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

  execute 'insert into '||tmpname||'(CodAnalizaNod,CODANALIZA,Nivel,IDXNOD,NOD,ANALIZA,COPII)
           select distinct -1, CodAnaliza, 0, ''00'', analiza, analiza, 1
           from '||tmpname;

  execute 'select max(nivel) from '||TMPNAME into Niv;
  if Niv &gt; 1 then
    for i in REVERSE 1 .. Niv LOOP
      execute 'UPDATE '||TMPNAME||' T SET VALOARE = COALESCE(VALOARE,0) + (SELECT SUM(TT.VALOARE) FROM '||TMPNAME||' TT WHERE TT.NODPARINTE = T.CODANALIZANOD AND TT.CODANALIZA = T.CODANALIZA) WHERE T.COPII &gt; 0 AND T.NIVEL = '||TO_CHAR(I);
    end loop;
  end if;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regcasabanca_processlist</obj_name>
  <obj_hashval>e33e60ddb71f3e130a1774ea2a0e48d1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regcasabanca_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert      varchar;
  sSelect      varchar;
  sSelReg      varchar;
  sDocument    varchar;
  sCursRef     varchar := '1 curs_ref';
  vCodMOneda   NUMERIC;
  dataIni      date := fnc_current_setting_date('PKG_LIST_CASABANKA.p_DataIni');
  dataFin      date := fnc_current_setting_date('PKG_LIST_CASABANKA.p_DataFin');
  sdataIni     varchar := 'To_DATE(''' || To_Char(dataIni    , 'dd.mm.yyyy') || ''',''dd.mm.yyyy'')';
  sdataIniSP   varchar := 'To_DATE(''' || To_Char(dataIni + 1, 'dd.mm.yyyy') || ''',''dd.mm.yyyy'')';
  sdataFin     varchar := 'To_DATE(''' || To_Char(dataFin    , 'dd.mm.yyyy') || ''',''dd.mm.yyyy'')';
  vTipDoc      varchar := current_setting('PKG_LIST_CASABANKA.p_tipDoc', true);
  vAnIni       numeric := To_Char(dataIni, 'yyyy')::numeric;
  vLunaIni     numeric := To_Char(dataIni, 'mm')::numeric;
  vAnLunaIni   numeric := vAnIni * 12 + vLunaIni;
  vAnFin       numeric := To_Char(dataFin, 'yyyy')::numeric;
  vLunaFin     numeric := To_Char(dataFin, 'mm')::numeric;
  vAnLunaFin   numeric := vAnFin * 12 + vLunaFin;
  vAmReg       NUMERIC;
  vAnLunaLucru numeric := getanlunalucru();
  aSitV        numeric;
  aBancaV      numeric;
  aMonedaV     numeric;
  sColSold     varchar := 'soldlei';
  sIniOrd      varchar := CASE WHEN Extract(DAY FROM dataIni) = 1 THEN '1' ELSE '0' END ;
  vDenSubunit  varchar;
  vCount       numeric;
  vValI        numeric;
  vValP        numeric;
  vSold_Col    numeric;
  vSoldLei_Col numeric;
  gSuplCols    varchar := 'tmp_lst_rb rb, nbankcont nbc, nbank nb, npers ag, ncont nc, ncont1 nc1, nconts cs, npart part, npers pers, ngest ng';
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplJoins   VARCHAR := '';
  wmeRes       boolean;
BEGIN
  --Florin 03.12.2025 - fixat 67468
  --Florin 10.11.2025 - sinc. Oracle
  --Florin 08.10.2025 - fixat 66905
  --Florin 09.02.2023 - fixat 57086
  --Florin 07.02.2023 - sinc. Oracle
  --Bogdan 21.02.2022 - sincronizat 53160 Listele Registru casa - lei, Registru banca - lei adaugat coloana TaxCode Saf-T
  --Florin 25.11.2021 - fixat 52137
  --Adina 12.07.2021 - pus numeric la linia 161 la C.VALOARE::numeric
  --Adina 09.07.2021 - sinc.Oracle - modif.la sincronizarea lui Stef din 06.07.2021
  --Adina 11.02.2021 - add wmeRes + corectat PKG_LIST_BASE_UTILS_GETCURSREFERINTA in loc de PKG_LIST_BASE_UTILS.GETCURSREFERINTA
  --Florin 06.08.2020
  --Florin 20.08.2020 - adaugat filtrare pe subunitate
  --Florin 25.08.2020 - fixat tichete
  --Florin 19.11.2020 - sters PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG cu 3 parametri
  --Adina 24.11.2020 tichet 41227
  --Adina 18.12.2020 pus fnc_GET_CONT_CONTABIL_OBLIG
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET', 'PD'  , 'PD.CODPART = PART.CODPART' , NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPERS'   , 'OPER', 'OPER.LOGONNAME = RB.USERID', 1);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_REGCASABANCA.gSuplCols', gSuplCols, false);

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

  IF wmeRes  --(SELECT pkg_list_base_utils_GetInfoSitValuta.WME_RESULT FROM pkg_list_base_utils_GetInfoSitValuta(NULL,aSitV, aBancaV, aMonedaV))
  THEN
    sCursRef := '(select wme_result from  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null, ' || coalesce(aMonedaV, 0)::varchar || ',' || coalesce(aBancaV, 0)::varchar || ', to_char(rb.datadoc,''dd.mm.yyyy'') )) curs_ref ';
  END IF;

  SELECT DISTINCT nbc.codmoneda
  INTO vCodMoneda
  FROM TMP_MANEVRA_LISTE tmp
  INNER JOIN nbankcont nbc ON  tmp.VALOARE = nbc.codbankcont::varchar
  WHERE FILTRU = 'CODBANKCONT';

  IF vCodMoneda &lt;&gt; 0 THEN
    SELECT Count(1)
    INTO vAmReg
    FROM reg
    WHERE tipreg = 45
      AND (an * 12 + luna) BETWEEN vAnLunaIni AND vAnLunaFin
      AND datadoc BETWEEN dataini AND datafin
      AND codmoneda = vCodMoneda;

    sColSold := 'soldvaluta';
  END IF;

  IF  vAmReg &gt; 0 THEN
    sSelReg := '
      UNION ALL
      SELECT
        r.codreg coddoc, NULL coddoc1, r.tipreg tipdoc, r.datadoc datareg, NULL doccumul, NULL prefixdoc, NULL seriedoc, NULL nri, r.nrdoc, r.datadoc, NULL AGENT,
        ''Regularizare valuta'' explicatii, NULL den_part, 0 cont, NULL obs,
        -1 tiptranz, 0 val, 0 valdoc, r.curs, x.CodBankCont codbanca, 0 sold_col,
        CASE bc.credit WHEN 1 THEN -1 ELSE 1 END * ((x.SoldValuta * r.Curs - x.SoldLei) - Coalesce( lag (x.SoldValuta * r.Curs - x.SoldLei,1) OVER (PARTITION BY X.CODBANKCONT ORDER BY r.datadoc),0)) soldlei_col,
        9 ordine, bc.subunitatea, 0 idxloc, r.an * 12 + r.luna anluna, NULL codpart, NULL codpers, NULL codgest, NULL userid, null taxcode_saft
      FROM
        ( SELECT CODBANKCONT, CODREG, SUM(SOLDLEI) SOLDLEI, SUM(SOLDVALUTA) SOLDVALUTA
          FROM (
            SELECT T.CODBANCA CODBANKCONT, R.CODREG,
              SUM((CASE t1.tiptranz WHEN 1 THEN 1 ELSE -1 END * T1.VALDOC - Coalesce(T1.COMISION,0)) * T1.CURS * CASE bc.credit WHEN 1 THEN -1 ELSE 1 END) SOLDLEI,
              SUM((CASE t1.tiptranz WHEN 1 THEN 1 ELSE -1 END * T1.VALDOC - Coalesce(T1.COMISION,0)) * CASE bc.credit WHEN 1 THEN -1 ELSE 1 END) SOLDVALUTA
            FROM  TREZOR T
              INNER JOIN trezor1   t1 ON t1.codtrezor   = t.codtrezor
              INNER JOIN nbankcont bc ON bc.codbankcont = t.codbanca
              INNER JOIN reg       r  ON r.codmoneda    = bc.codmoneda
            WHERE R.TipReg = 45
              AND Coalesce(bc.farareg, 0) = 0
              AND r.datadoc BETWEEN '||sdataini|| ' AND '||sdatafin||'
              AND r.an * 12 + r.luna between '||To_Char(vAnLunaIni, 'fm00000')||' AND '||To_Char(vAnLunaFin, 'fm00000')||'
              AND t.tipdoc = '||vTipDoc::varchar||' AND t.operat = 1 AND Coalesce(t1.anulat, 0) = 0
              AND t.an * 12 + t.luna &gt;= '||To_Char(vAnLunaIni, 'fm00000')||'
              AND t.an * 12 + t.luna &lt;= r.an * 12 + r.luna
              AND t.datadoc &lt;= r.datadoc
              AND Coalesce(t1.tiptranz,-1) IN (0,1)
              AND bc.codmoneda &lt;&gt; 0
              AND t.codbanca::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'')
            GROUP BY T.CODBANCA, R.CODREG
            UNION ALL
            SELECT BCS.CODBANKCONT, R.CODREG, Coalesce(bcs.SOLDLEI,0) SOLDLEI,  Coalesce(bcs.SOLDVALUTA,0) SOLDVALUTA
            FROM NBANKSOLDLUNA BCS
              INNER JOIN nbankcont bc ON bc.codbankcont = bcs.codbankcont
              INNER JOIN reg       r  ON r.codmoneda    = bc.codmoneda
            WHERE bc.codmoneda &lt;&gt; 0
              AND R.TipReg = 45
              AND Coalesce(bc.farareg, 0) = 0
              AND r.datadoc BETWEEN '||sdataini|| ' AND '||sdatafin||'
              AND r.an * 12 + r.luna between '||To_Char(vAnLunaIni, 'fm00000')||' AND '||To_Char(vAnLunaFin, 'fm00000')||'
              AND bcs.an * 12 + bcs.luna = '||TO_CHAR(vAnLunaIni-1, 'fm00000')||'
              AND bcs.codbankcont::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'')
          ) a_pg
          GROUP BY CODBANKCONT, CODREG
        ) X
        INNER JOIN REG       R  ON R.CODREG       = X.CODREG
        INNER JOIN NBANKCONT BC ON BC.CODBANKCONT = X.CODBANKCONT
      WHERE SOLDLEI &lt;&gt; SOLDVALUTA * R.CURS';
  END IF;
  sInsert := 'INSERT INTO ' || tmpName || '(
      NAV_CodDoc, NAV_CodDoc1, NAV_TipDoc, DATAREG, DOCCUMUL, PREFIXDOC, SERIEDOC, NRI, NRDOC, DATADOC, AGENT,
      EXPLICATII, DEN_PART, SEMNIFICATIE, CONTSEC, OBS,
      INCASARE, PLATA,
      VALDOC, VALDOCLEI, SOLD_COL, SOLDLEI_COL,
      ORDINE, IDXLOC, SIMB_BANCA, DEN_CONT, NRCONT, SUBUNITATEA, CONTREPR, TIPTRANZ,
      CURS, TAXCODE_SAFT, CURS_REF' || gUserFields || ') ';
  sDocument := '
                 CASE
                   WHEN o.semnificatie IN (310,410) THEN ''in avans ''
                   WHEN int.codintr IS NOT NULL THEN int.prefixdoc|| ''/''||int.nrdoc||''/''|| To_char(int.datadoc,''dd.mm.yyyy'')
                   WHEN ies.codies  IS NOT NULL THEN ies.prefixdoc|| ''/''||ies.nrdoc||''/''|| To_char(ies.datadoc,''dd.mm.yyyy'')
                 END ';
  sSelect := '
  WITH
    CC AS (
      SELECT
        T1.CODCONTDED, T1.CODCONTCOLE,
        Greatest(C.ALSTART, T1.ALSTART) ALSTART, LEAST(C.ALSTOP, T1.ALSTOP) ALSTOP
      FROM (
        SELECT CV.VALOARE, CL.ALSTART, CL.ALSTOP
        FROM CONST1 C1
          LEFT JOIN CATEGCONST CT ON CT.CODCATEG     = C1.CODCATEG
          LEFT JOIN CONSTLUNA  CL ON CL.CODCONST1    = C1.CODCONST1
          LEFT JOIN CONSTVAL   CV ON CV.CODCONSTLUNA = CL.CODCONSTLUNA
        WHERE Upper(C1.simbol) = Upper(''TIPTVAImplicit'')
      ) C INNER JOIN NTVA1 T1 ON T1.CODTVA::varchar = C.VALOARE AND T1.ALSTART &lt;= C.ALSTOP AND T1.ALSTOP &gt;= C.ALSTART
    ),
    RB AS (
      SELECT coddoc, coddoc1, tipdoc, datareg, doccumul, prefixdoc, seriedoc, nri, nrdoc, datadoc, agent, explicatii, den_part, cont, obs,
        tiptranz, val, valdoc, curs, codbanca, sold_col, soldlei_col, ordine, subunitatea, idxloc, anluna, codpart, codpers, codgest, userid, taxcode_saft
      FROM (
        SELECT
          coddoc, coddoc1, tipdoc, datareg, doccumul, prefixdoc, seriedoc, nri, nrdoc, datadoc, agent, obs,
          CASE
            WHEN tiptranz = 0 AND obiecttranz = 0 THEN ''Plata furnizor ''
            WHEN tiptranz = 0 AND obiecttranz = 1 THEN ''Plata retur ''
            WHEN tiptranz = 0 AND obiecttranz = 2 THEN ''Plata angajat ''
            WHEN tiptranz = 0 AND obiecttranz = 3 THEN ''Plata viramente interne ''
            WHEN tiptranz = 0 AND obiecttranz = 4 THEN ''Plata direct pe cheltuieli ''
            WHEN tiptranz = 0 AND obiecttranz = 5 THEN ''Plata datorii / taxe / impozite ''
            WHEN tiptranz = 1 AND obiecttranz = 0 THEN ''Incasare client ''
            WHEN tiptranz = 1 AND obiecttranz = 1 THEN ''Incasare retur ''
            WHEN tiptranz = 1 AND obiecttranz = 2 THEN ''Incasare angajat ''
            WHEN tiptranz = 1 AND obiecttranz = 3 THEN ''Incasare viramente interne ''
            WHEN tiptranz = 1 AND obiecttranz = 4 THEN ''Incasare direct pe venituri ''
            WHEN tiptranz = 1 AND obiecttranz = 5 THEN ''Incasare imprumuturi / subventii ''
            WHEN tiptranz = 1 AND obiecttranz = 6 THEN ''Incasare dobanda ''
            WHEN tiptranz = 2                     THEN ''Plata SPLIT TVA ''
          END || coalesce(den_part, '''')|| '' '' || coalesce(string_agg(DISTINCT DOC, ''''), '''') explicatii,
          case when tiptranz = 1 then 2 else 3 end ordine,
          Coalesce(cont,0) cont, tiptranz, sum(val) val, Coalesce(valdoc,0) valdoc, den_part, codbanca, curs,
          sum(sold_col) sold_col, sum(soldlei_col) soldlei_col, subunitatea, idxloc, anluna, codpart, codpers, codgest, userid, taxcode_saft
        FROM (
          WITH REZ AS (
          SELECT
            t.codtrezor coddoc, t1.codtrezor1 coddoc1, t.tipdoc, t.datadoc datareg, t.numedoc doccumul, t1.doc prefixdoc, t1.seriedoc, t1.nri, t1.nrdoc, t1.datadoc, Coalesce(NullIF(t1.agent,0),t.agent) agent, t1.obs, t1.obiecttranz,
            CAST(' || coalesce(sDocument,'') || ' AS VARCHAR(100)) doc,
            --nc.codcont cont,
            CASE WHEN t1.platatva = 1 THEN 2 ELSE t1.tiptranz END tiptranz,
            CASE
              -- cica in cazul t1.obiecttranz = 3 am o singura obligatie asociata, nu are TVA si am gasit bube date de diferente de curs
              -- stef 05.03.2014 am gasit si mai multe linii din preluare pt cazul de mai sus si atunci imi bag picioarele ca iese nasol suma
              WHEN t1.obiecttranz = 3 AND COUNT(1) OVER (PARTITION BY t1.codtrezor1) = 1 THEN t1.valdoc
              WHEN Coalesce(t1.platatva,0) = 1                                           THEN Coalesce(o.dincaretva,0)
              ELSE (Coalesce(o.valoare,0) - Coalesce(g.tva,0)) * CASE WHEN g.moneda = '||vCodMoneda::varchar||' THEN 1 ELSE Coalesce(NullIF(g.curs,0),1) / Coalesce(NullIF(t1.curs,0),1) END
            END val,
            t1.valdoc,
            CASE t1.obiecttranz
              WHEN 3 THEN nb.denumire||'' ''||nbc.nrcont
              WHEN 2 THEN pers.nume  ||'' ''||pers.prenume
              WHEN 1 THEN part.den_part
              WHEN 0 THEN part.den_part
              ELSE ''XXXXX''   --nc.simbol
            END den_part,
            t.codbanca, Coalesce(NullIF(t1.curs,0),1) curs,
            CASE
              WHEN t1.obiecttranz = 3 AND COUNT(1) OVER (PARTITION BY t1.codtrezor1) = 1 THEN t1.valdoc
              WHEN Coalesce(t1.platatva,0) = 1                                           THEN Coalesce(o.dincaretva,0)
              ELSE (Coalesce(o.valoare,0) - Coalesce(g.tva,0)) * CASE WHEN g.moneda = ' || coalesce(vCodMoneda , 0) || ' THEN 1 ELSE Coalesce(NullIF(g.curs,0),1) / Coalesce(NullIF(t1.curs,0),1) END
            END * CASE t1.tiptranz WHEN 1 THEN 1 ELSE -1 END sold_col,
            CASE
              WHEN t1.obiecttranz = 3 AND COUNT(1) OVER (PARTITION BY t1.codtrezor1) = 1 THEN t1.valdoc * Coalesce(NullIF(t1.curs,0),1)
              WHEN Coalesce(t1.platatva,0) = 1                                           THEN Coalesce(o.dincaretva,0)
              ELSE (Coalesce(o.valoare,0) - Coalesce(g.tva,0)) * CASE WHEN g.moneda = '||vCodMoneda::varchar||' THEN Coalesce(NullIF(t1.curs,0),1) ELSE Coalesce(NullIF(g.curs,0),1) END
            END * CASE t1.tiptranz WHEN 1 THEN 1 ELSE -1 END soldlei_col,
            t.subunitatea, t1.indexlocal * 10 + 1 idxloc, t.an*12+t.luna anluna, part.codpart, pers.codpers, o.codgest, t.userid,
            (
              SELECT fnc_array_to_vc3200(ARRAY_AGG(TXD.TAXCODE::varchar ORDER BY TXD.CODDOC1)) AS taxcode_saft
              FROM TAXDECL TXD
              WHERE TXD.TIPDOC = T.TIPDOC AND TXD.CODDOC = T1.CODTREZOR1
            ) AS taxcode_saft
            ,CASE
               WHEN o.semnificatie IN (300,320) AND Coalesce(os.semnificatie, 0) = 500 THEN (SELECT PKG_TREZOR_CODCONTCEC.wme_result FROM PKG_TREZOR_CODCONTCEC(NULL, TS.CodBanca, OS.Semnificatie, TS1.Tipdecont, T.an, T.luna))
               WHEN o.semnificatie IN (400,420) AND Coalesce(os.semnificatie, 0) = 600 THEN (SELECT PKG_TREZOR_CODCONTCEC.wme_result FROM PKG_TREZOR_CODCONTCEC(NULL, TS.CodBanca, OS.Semnificatie, TS1.Tipdecont, 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 aacodcont
          FROM trezor t
              LEFT JOIN trezor1 t1    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 npart part    ON part.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 nbc ON nbc.codbankcont   = t1.codpart AND t1.obiecttranz = 3
              LEFT JOIN nbank nb      ON nb.codbank        = nbc.codbank
              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 intrari int   on int.codintr       = gs.coddoc and int.tipdoc = gs.tipdoc
              LEFT JOIN iesiri ies    on ies.codies        = gs.coddoc and ies.tipdoc = gs.tipdoc
              LEFT JOIN trezor1 ts1   ON ts1.codtrezor1    = gs.coddoc AND gs.tipdoc IN (29,31)
              LEFT JOIN trezor ts     ON ts.codtrezor      = ts1.codtrezor
          WHERE t.tipdoc = '||vTipDoc::varchar||' AND t.operat = 1 AND Coalesce(t1.anulat, 0) = 0
            AND t.an * 12 + t.luna  between '||To_Char(vAnLunaIni, 'fm00000')||' AND '||To_Char(vAnLunaFin, 'fm00000')||'
            AND t.datadoc BETWEEN '||sdataini|| ' AND '||sdatafin||'
            AND Coalesce(t1.tiptranz,-1) IN (0,1)
            AND t.codbanca::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'')
          )
          SELECT
            r.coddoc, r.coddoc1, r.tipdoc, r.datareg, r.doccumul,
            r.prefixdoc, r.seriedoc, r.nri, r.nrdoc, r.datadoc,
            r.agent, r.obs, r.obiecttranz, r.doc,
            nc.codcont cont,
            r.tiptranz, r.val, r.valdoc,
            CASE WHEN r.den_part=''XXXXX'' THEN nc.simbol ELSE r.den_part END den_part,
            r.codbanca, r.curs, r.sold_col, r.soldlei_col,
            r.subunitatea, r.idxloc, r.anluna, r.codpart,
            r.codpers, r.codgest, r.userid, r.taxcode_saft
          FROM rez r
               LEFT JOIN ncont nc ON nc.codcont = r.aacodcont
          ) a_pg
        GROUP BY
          coddoc, coddoc1, tipdoc, datareg, prefixdoc, seriedoc, nri, nrdoc, datadoc, agent, obs, Coalesce(cont,0), tiptranz, obiecttranz, valdoc, den_part, codbanca, curs, subunitatea, idxloc, anluna, doccumul,
          codpart, codpers, codgest, userid, taxcode_saft
        UNION ALL
        SELECT
          coddoc, coddoc1, tipdoc, datareg, doccumul, prefixdoc, seriedoc, nri, nrdoc, datadoc, agent, obs,
          CASE
            WHEN tiptranz = 0 AND obiecttranz = 0 THEN ''Plata(TVA) furnizor ''
            WHEN tiptranz = 0 AND obiecttranz = 1 THEN ''Plata(TVA) retur ''
            WHEN tiptranz = 0 AND obiecttranz = 2 THEN ''Plata(TVA) angajat ''
            WHEN tiptranz = 0 AND obiecttranz = 3 THEN ''Plata(TVA) viramente interne ''
            WHEN tiptranz = 0 AND obiecttranz = 4 THEN ''Plata(TVA) direct pe cheltuieli ''
            WHEN tiptranz = 0 AND obiecttranz = 5 THEN ''Plata(TVA) datorii / taxe / impozite ''
            WHEN tiptranz = 1 AND obiecttranz = 0 THEN ''Incasare(TVA) client ''
            WHEN tiptranz = 1 AND obiecttranz = 1 THEN ''Incasare(TVA) retur ''
            WHEN tiptranz = 1 AND obiecttranz = 2 THEN ''Incasare(TVA) angajat ''
            WHEN tiptranz = 1 AND obiecttranz = 3 THEN ''Incasare(TVA) viramente interne ''
            WHEN tiptranz = 1 AND obiecttranz = 4 THEN ''Incasare(TVA) direct pe venituri ''
            WHEN tiptranz = 1 AND obiecttranz = 5 THEN ''Incasare(TVA) imprumuturi / subventii ''
            WHEN tiptranz = 1 AND obiecttranz = 6 THEN ''Incasare(TVA) dobanda ''
          END || coalesce(den_part, '''') || '' '' || coalesce(string_agg(DISTINCT DOC, ''''), '''') explicatii,
          case when tiptranz = 1 then 2 else 3 end ordine,
          Coalesce(cont, 0) cont, tiptranz, sum(val) val , Coalesce(valdoc,0) valdoc, den_part, codbanca, curs,
          sum(sold_col) sold_col, sum(soldlei_col) soldlei_col, subunitatea, idxloc, anluna, codpart, codpers, codgest, userid, taxcode_saft
        FROM (
          SELECT
            t.codtrezor coddoc, t1.codtrezor1 coddoc1, t.tipdoc, t.datadoc datareg, t.numedoc doccumul, t1.doc prefixdoc, t1.seriedoc, t1.nri, t1.nrdoc, t1.datadoc, Coalesce(NullIF(t1.agent,0),t.agent) agent, t1.obs, t1.obiecttranz,
            CAST(' || coalesce(sDocument,'') || ' AS VARCHAR(100)) doc, nc.codcont cont, t1.tiptranz,
            g.tva * CASE WHEN g.moneda = ' || coalesce(vCodMoneda , 0) || ' THEN 1 ELSE Coalesce(NullIF(g.curs,0),1) / Coalesce(NullIF(t1.curs,0),1) END val,
            t1.valdoc, CASE t1.obiecttranz WHEN 3 THEN nb.denumire||'' ''||nbc.nrcont WHEN 2 THEN pers.nume||'' ''||pers.prenume WHEN 1 THEN part.den_part WHEN 0 THEN part.den_part ELSE nc.simbol END den_part,
            t.codbanca, Coalesce(NullIF(t1.curs,0),1) curs,
            CASE t1.tiptranz WHEN 1 THEN 1 ELSE -1 END * g.tva * CASE WHEN g.moneda = '||vCodMoneda::varchar||' THEN 1 ELSE Coalesce(NullIF(g.curs,0),1) / Coalesce(NullIF(t1.curs,0),1) END sold_col,
            CASE t1.tiptranz WHEN 1 THEN 1 ELSE -1 END * g.tva * CASE WHEN g.moneda = '||vCodMoneda::varchar||' THEN Coalesce(NullIF(t1.curs,0),1) ELSE Coalesce(NullIF(g.curs,0),1) END soldlei_col,
            t.subunitatea, t1.indexlocal * 10 + 2 idxloc, t.an*12+t.luna anluna, part.codpart, pers.codpers, o.codgest, t.userid,
            (
              SELECT fnc_array_to_vc3200(ARRAY_AGG(TXD.TAXCODE::varchar ORDER BY TXD.CODDOC1)) AS taxcode_saft
              FROM TAXDECL TXD
              WHERE TXD.TIPDOC = T.TIPDOC AND TXD.CODDOC = T1.CODTREZOR1
            ) AS taxcode_saft
          FROM trezor t
            LEFT JOIN trezor1   t1   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 npart     part ON part.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 nbc  ON nbc.codbankcont   = t1.codpart AND t1.obiecttranz = 3
            LEFT JOIN nbank     nb   ON nb.codbank        = nbc.codbank
            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 intrari   int  on int.codintr       = gs.coddoc and int.tipdoc = gs.tipdoc
            LEFT JOIN iesiri    ies  on ies.codies        = gs.coddoc and ies.tipdoc = gs.tipdoc
            LEFT JOIN cc ON (t.an * 12 + t.luna) between cc.alstart   AND cc.alstop
            LEFT JOIN ncont     nc   ON nc.codcont        = CASE WHEN t1.tiptranz = 0 AND t1.obiecttranz =1 THEN cc.codcontcole WHEN t1.tiptranz = 0 OR t1.obiecttranz =1 THEN cc.codcontded ELSE cc.codcontcole END
          WHERE t.tipdoc = '||vTipDoc||' AND t.operat = 1 AND Coalesce(t1.anulat, 0) = 0
            AND (t.an * 12 + t.luna)  between '||vAnLunaIni||' AND '||vAnLunaFin||'
            AND t.datadoc BETWEEN '||sdataini||' AND '||sdatafin||'
            AND Coalesce(t1.tiptranz,-1) IN (0,1)
            AND (Coalesce (g.tva, 0) &lt;&gt; 0)
            AND t.codbanca::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'')
          ) b_pg
        GROUP BY
          coddoc, coddoc1, tipdoc, datareg, prefixdoc, seriedoc, nri, nrdoc, datadoc, agent, obs, Coalesce(cont,0), tiptranz, obiecttranz, valdoc, den_part, codbanca, curs, subunitatea, idxloc, anluna, doccumul,
          codpart, codpers, codgest, userid, taxcode_saft';
  IF  vTipDoc::numeric = 30 THEN
    sSelect := coalesce(sSelect,'') || '
        UNION ALL
        SELECT
          t.codtrezor coddoc, t1.codtrezor1 coddoc1, t.tipdoc, t.datadoc datareg, t.numedoc doccumul, t1.doc prefixdoc, t1.seriedoc, t1.nri, t1.nrdoc, t1.datadoc, t.agent, t1.obs,
          ''Comision Bancar '' explicatii, 2 ordine, iob1.comision cont,
          0 tiptranz, t1.comision val, 0 valdoc, Coalesce(part.den_part,pers.nume|| '' '' || pers.prenume) den_part, t.codbanca, Coalesce(NullIF(t1.curs,0),1) curs,
          - t1.comision sold_col, - t1.comision * Coalesce(NullIF(t1.curs,0),1) soldlei_col,
          t.subunitatea, t1.indexlocal * 10 + 3 idxloc, t.an*12+t.luna anluna, part.codpart, pers.codpers, NULL codgest, NULL userid,
          (
            SELECT fnc_array_to_vc3200(ARRAY_AGG(TXD.TAXCODE::varchar ORDER BY TXD.CODDOC1)) AS taxcode_saft
            FROM TAXDECL TXD
            WHERE TXD.TIPDOC = T.TIPDOC AND TXD.CODDOC = T1.CODTREZOR1
          ) AS taxcode_saft
        FROM trezor t
          LEFT JOIN trezor1    t1   ON t.codtrezor      = t1.codtrezor
          LEFT JOIN npart      part ON part.codpart     = t1.codpart      AND t1.obiecttranz IN (0,1)
          LEFT JOIN npers      pers ON pers.codpers     = t1.codpart      AND t1.obiecttranz = 2
          LEFT JOIN nbankcont1 nbc1 ON nbc1.codbankcont = t.codbanca      AND nbc1.alstart &lt;= t.an * 12 + t.luna AND nbc1.alstop &gt;= t.an * 12 + t.luna
          LEFT JOIN iobank1    iob1 ON iob1.codiobank   = nbc1.codiobanca AND iob1.alstart &lt;= t.an * 12 + t.luna AND iob1.alstop &gt;= t.an * 12 + t.luna
        LEFT JOIN (SELECT TXD.TIPDOC,
                      TXD.CODDOC,
                            fnc_array_to_vc3200 (ARRAY_AGG(TXD.TAXCODE::varchar ORDER BY TXD.CODDOC1)) AS taxcode_saft
              FROM TAXDECL TXD
              GROUP BY TXD.TIPDOC, TXD.CODDOC) TXDL
                                                    ON TXDL.TIPDOC = T.TIPDOC
                                                    and TXDL.CODDOC = T1.CODTREZOR1
        WHERE t.tipdoc = '||vTipDoc::varchar||' AND t.operat = 1 AND Coalesce(t1.anulat, 0) = 0
          AND t.an * 12 + t.luna between '||To_Char(vAnLunaIni, 'fm00000')||' AND '||To_Char(vAnLunaFin, 'fm00000')||'
          AND Coalesce(t1.tiptranz,-1) IN (0,1)
          AND Coalesce(t1.comision,0) &lt;&gt; 0
          AND t.datadoc BETWEEN '||sdataini|| ' AND '||sdatafin||'
          AND t.codbanca::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'') ';
  END IF;
  sSelect := coalesce(sSelect,'') || '
          ) c_pg';
  IF vTipDoc::numeric = 29 THEN
    sSelect := coalesce(sSelect,'') || '
        UNION ALL
        SELECT
          i.codies coddoc, NULL coddoc1, i.tipdoc, i.datadoc datareg, Coalesce(i.prefixdoc,''M'') doccumul, i.prefixdoc, i.seriadoc seriedoc, i.nri, i.nrdoc, i.datadoc, i.agent,
          ''Incasare Monetar '' explicatii, null den_part, x.cont, i.obs,
          1 tiptranz,
          Round(CASE WHEN i.tvadoc = 0 OR i.valdoc = 0 THEN SUM(mp.valoare) ELSE SUM(mp.valoare) * (i.valdoc - i.tvadoc) / i.valdoc END * x.coef,7) val,
          i.valdoc, Coalesce(NullIF(i.curs,0),1) curs, mp.codbankcont codbanca,
          Round(CASE WHEN i.tvadoc = 0 OR i.valdoc = 0 THEN SUM(mp.valoare) ELSE SUM(mp.valoare) * (i.valdoc - i.tvadoc) / i.valdoc END * x.coef,7) sold_col,
          Round(CASE WHEN i.tvadoc = 0 OR i.valdoc = 0 THEN SUM(mp.valoare) ELSE SUM(mp.valoare) * (i.valdoc - i.tvadoc) / i.valdoc END * x.coef * Coalesce(NullIF(i.curs,0),1),7) soldlei_col,
          2 ORDINE, i.subunitatea, i.codies * 10 idxloc, i.an*12+i.luna anluna, NULL codpart, NULL codpers, NULL codgest, i.userid, null as taxcode_saft
        FROM (
          SELECT
            i.codies, Coalesce(ioa1.venituri,i1.contserv,0) cont,
            Sum (
              CASE
                WHEN coalesce(i1.tva, 0) = 0 THEN Coalesce(l1.cant, i1.cant) * i1.pu
                WHEN l1.codlivr1 IS NULL THEN (i1.pu * i1.cant - coalesce(i1.tva, 0))
                WHEN i1.pu * i1.cant = 0 THEN 0
                ELSE (i1.pu * i1.cant - coalesce(i1.tva, 0)) * l1.cant / i1.cant
              END) / (i.valdoc - i.tvadoc - Coalesce(i.valdiscount,0) + Coalesce(i.tvadiscount,0)) coef
          FROM iesiri i
            LEFT JOIN iesiri1 i1   ON i1.codies     = i.codies AND (i.valdoc - i.tvadoc &lt;&gt; 0) AND (i1.pu * i1.cant - coalesce(i1.tva, 0) &lt;&gt; 0)
            LEFT JOIN livr1 l1 ON l1.codies1 = i1.codies1
            LEFT JOIN livr l ON l1.codlivr = l.codlivr AND l.codies = i.codies
            LEFT JOIN livrval lv   ON lv.codlivr1   = l1.codlivr1
            LEFT JOIN nirstoc ns   ON ns.codnirstoc = l1.codnirstoc
            LEFT JOIN ioart1  ioa1 ON ioa1.codioart = CASE WHEN COALESCE(l1.contintermed, 0) &lt;&gt; 0 THEN l1.contintermed ELSE COALESCE(ns.codioart, lv.codioart,-1) END AND '||To_Char(vAnLunaLucru, 'fm00000')||' BETWEEN ioa1.alstart AND ioa1.alstop
          WHERE i.tipdoc = 16 AND i.anulat = 0 AND i.operat = 1
            AND NOT (i1.tiplinie = ''='' AND l1.codlivr1 IS NULL)
            AND i.an * 12 + i.luna between '||To_Char(vAnLunaIni, 'fm00000')||' AND '||To_Char(vAnLunaFin, 'fm00000')||'
            AND i.datadoc BETWEEN '||sdataini|| ' AND '||sdatafin||'
            AND EXISTS (SELECT mp.codies
                        FROM moduriplati mp INNER JOIN tmp_manevra_liste tmp ON mp.codbankcont::varchar = tmp.valoare
                        WHERE mp.codies = i.codies AND tmp.filtru = ''CODBANKCONT'')
          GROUP BY i.codies, i.valdoc, i.tvadoc, i.valdiscount, i.tvadiscount, Coalesce(ioa1.venituri,i1.contserv,0) ) x
          INNER JOIN iesiri      i  ON i.codies  = x.codies
          INNER JOIN moduriplati mp ON mp.codies = i.codies
        WHERE mp.codbankcont::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'')
        GROUP BY i.codies, i.tipdoc, i.prefixdoc, i.seriadoc, i.nri, i.nrdoc, i.datadoc, i.agent, i.obs, i.valdoc, i.tvadoc, i.subunitatea, i.curs, i.an, i.luna, mp.codbankcont, x.cont, x.coef, i.userid
        UNION ALL
        SELECT
          i.codies coddoc, NULL coddoc1, i.tipdoc, i.datadoc datareg, Coalesce(i.prefixdoc,''M'') doccumul, i.prefixdoc, i.seriadoc seriedoc, i.nri, i.nrdoc, i.datadoc, i.agent,
          ''Incasare(TVA) Monetar '' explicatii, null den_part, cc.codcontcole cont, i.obs,
          1 tiptranz,
          Round(CASE WHEN i.tvadoc = 0 OR i.valdoc = 0 THEN 0 ELSE SUM(mp.valoare) * i.tvadoc / i.valdoc END,7) val,
          i.valdoc, Coalesce(NullIF(i.curs,0),1) curs, mp.codbankcont codbanca,
          Round(CASE WHEN i.tvadoc = 0 OR i.valdoc = 0 THEN 0 ELSE SUM(mp.valoare) * i.tvadoc / i.valdoc END,7) sold_col,
          Round(CASE WHEN i.tvadoc = 0 OR i.valdoc = 0 THEN 0 ELSE SUM(mp.valoare) * i.tvadoc / i.valdoc END * Coalesce(NullIF(i.curs,0),1),7) soldlei_col,
          2 ORDINE, i.subunitatea, i.codies * 10 +1 idxloc, i.an*12+i.luna anluna, NULL codpart, NULL codpers, NULL codgest, i.userid, null as taxcode_saft
        FROM iesiri i
          LEFT JOIN moduriplati mp ON mp.codies = i.codies
          LEFT JOIN cc             ON i.an * 12 + i.luna between cc.alstart AND cc.alstop
        WHERE i.tipdoc = 16 AND i.anulat = 0 AND i.operat = 1
          AND i.an * 12 + i.luna between '||To_Char(vAnLunaIni, 'fm00000')||' AND '||To_Char(vAnLunaFin, 'fm00000')||'
          AND i.datadoc BETWEEN '||sdataini|| ' AND '||sdatafin||'
          AND mp.codbankcont::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'')
        GROUP BY i.codies, i.tipdoc, i.prefixdoc, i.seriadoc, i.nri, i.nrdoc, i.datadoc, i.agent, i.obs, i.valdoc, i.tvadoc, i.subunitatea, i.curs, i.an, i.luna, mp.codbankcont, cc.codcontcole, i.userid';
  END IF;
  sSelect := coalesce(sSelect,'') || '
        UNION ALL
        SELECT
          NULL coddoc, NULL coddoc1, NULL tipdoc, ' || coalesce(sdataini, '''') || ' datareg, NULL doccumul, NULL prefixdoc, NULL seriedoc, NULL nri, NULL nrdoc, NULL DATADOC, NULL AGENT,
          (CASE ordine WHEN 1 THEN ''Documente cu data &lt; ' ||  To_Char(dataIni, 'dd.mm.yyyy') || ''' ELSE ''Sold initial'' END) explicatii, NULL den_part, NULL semnificatie, NULL obs,
          -1 tiptranz, 0 val, 0 valdoc, NULL curs, NULL codbanca, SUM (sold) sold_col, SUM (soldlei) soldlei_col, ordine,
          getsubunitate() subunitatea, 0 idxloc, 0 anluna, NULL codpart, NULL codpers, NULL codgest, NULL userid, null as taxcode_saft
        FROM (
          SELECT 0 ordine, 0 sold, 0 soldlei
          UNION ALL
          SELECT 0 ordine, Coalesce(' || coalesce(sColSold,'') || ',0) sold, Coalesce(soldlei,0) soldlei
          FROM nbanksoldluna
          WHERE (an * 12 + luna) = '||TO_CHAR(vAnLunaIni-1, 'fm00000')||'
            AND codbankcont::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'')
          UNION ALL
          SELECT ' || coalesce(sIniOrd,'') || ' ordine,
            (t1.valdoc * CASE t1.tiptranz WHEN 1 THEN 1 ELSE -1 END - Coalesce(t1.comision,0)) * CASE bc.credit WHEN 1 THEN -1 ELSE 1 END sold,
            (t1.valdoc * CASE t1.tiptranz WHEN 1 THEN 1 ELSE -1 END - Coalesce(t1.comision,0)) * Coalesce(NullIF(t1.curs,0),1) * CASE bc.credit WHEN 1 THEN -1 ELSE 1 END soldlei
          FROM trezor t
            LEFT JOIN trezor1   t1 ON t1.codtrezor   = t.codtrezor
            LEFT JOIN nbankcont bc ON bc.codbankcont = t.codbanca
          WHERE t.tipdoc = '||vTipDoc::varchar||' AND t.operat = 1 AND Coalesce(t1.anulat, 0) = 0 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'t',NULL,NULL,NULL)),'') || '
            AND t.codbanca::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'')
            AND t.datadoc &lt; '||sdataini|| '
            AND (t.an * 12 + t.luna) = '||To_Char(vAnLunaIni, 'fm00000');
  IF  vTipDoc::numeric = 29 THEN
    sSelect := coalesce(sSelect,'') || '
          UNION ALL
          SELECT ' || coalesce(sIniOrd,'') || ' ordine, SUM(mp.valoare) sold , SUM(mp.valoare) * Coalesce(NullIF(i.curs,0),1) soldlei
          FROM iesiri i LEFT JOIN moduriplati mp ON mp.codies = i.codies
          WHERE i.tipdoc = 16 AND i.anulat = 0 AND i.operat = 1 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'i',NULL,NULL,NULL)),'') || '
            AND i.an * 12 + i.luna = '||To_Char(vAnLunaIni, 'fm00000')||'
            AND i.datadoc &lt; '||sdataini|| '
            AND mp.codbankcont::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'')
          GROUP BY i.codies, i.tipdoc, i.prefixdoc, i.seriadoc, i.nri, i.nrdoc, i.datadoc, i.agent, i.obs, i.valdoc, i.tvadoc, i.subunitatea, i.curs, mp.codbankcont';
  END IF;
  sSelect := coalesce(sSelect,'') || '
        ) d_pg
        GROUP BY ordine
        UNION ALL
        SELECT NULL coddoc, NULL coddoc1, NULL tipdoc, datadoc datareg, NULL doccumul, NULL prefixdoc, NULL seriedoc, NULL nri, NULL nrdoc, NULL datadoc, NULL AGENT,
          ''Sold ziua precedenta'' explicatii, NULL den_part, NULL semnificatie, NULL obs,
          -1 tiptranz, 0 val, 0 valdoc, NULL curs, NULL codbanca, 0 sold_col, 0 soldlei_col, 1 ordine,
          getsubunitate() subunitatea, 0 idxloc, 0 anluna, NULL codpart, NULL codpers, NULL codgest, NULL userid, null as taxcode_saft
        FROM (
          SELECT datadoc
          FROM  trezor t
          WHERE tipdoc = '||vTipDoc::varchar||' AND t.operat = 1 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,NULL,NULL,NULL,NULL)),'') || '
            AND datadoc between '||sdatainiSP||' AND '||sdatafin||'
            AND t.codbanca::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'')';
  IF  vTipDoc::numeric = 29 THEN
    sSelect := coalesce(sSelect,'') || '
          UNION
          SELECT i.datadoc
          FROM iesiri i LEFT JOIN moduriplati mp ON mp.codies = i.codies
          WHERE i.tipdoc = 16 AND i.anulat = 0 AND i.operat = 1 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'i',NULL,NULL,NULL)),'') || '
            AND i.an * 12 + i.luna between '||To_Char(vAnLunaIni, 'fm00000')||' AND '||To_Char(vAnLunaFin, 'fm00000')||'
            AND i.datadoc BETWEEN ' || coalesce(sdatainiSP,'') || ' AND '||sdatafin||'
            AND mp.codbankcont::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'') ';
  END IF;
  sSelect := coalesce(sSelect,'') || '
          ) e_pg' || coalesce(sSelreg,'') || '),
      R AS (
        SELECT CODBANK, LAST_VALUE(CURS) OVER (PARTITION  BY CODBANK  ORDER BY datadoc desc  range between unbounded preceding and unbounded following) CURS
          FROM reg WHERE tipreg = 45
          AND datadoc BETWEEN '||sdataini|| ' AND '||sdatafin||'
          AND an * 12 + luna between '||To_Char(vAnLunaIni, 'fm00000')||' AND '||To_Char(vAnLunaFin, 'fm00000')||'
          AND codmoneda = '||vCodMoneda::varchar||')
    SELECT distinct
      rb.coddoc, rb.coddoc1, rb.tipdoc, rb.datareg, rb.doccumul, rb.prefixdoc, rb.seriedoc, rb.nri, rb.nrdoc, rb.datadoc, coalesce(ag.nume, '''')||'' ''||coalesce(ag.prenume, '''') agent,
      CAST(rb.explicatii As VARCHAR(300)) explicatii, rb.den_part, nc.simbol semnificatie, cs.simbol contsec, rb.obs,
      Coalesce(CASE WHEN rb.tiptranz  = 1      THEN rb.val END,0) * Coalesce(CASE nbc.codmoneda WHEN 0 THEN rb.curs ELSE 1 END,0) incasare,
      Coalesce(CASE WHEN rb.tiptranz IN (0, 2) THEN rb.val END,0) * Coalesce(CASE nbc.codmoneda WHEN 0 THEN rb.curs ELSE 1 END,0) plata,
      rb.valdoc, rb.valdoc * Coalesce(r.curs,rb.curs) valdoclei,
      CASE nbc.credit WHEN 1 THEN -1 ELSE 1 END * rb.sold_col, CASE nbc.credit WHEN 1 THEN -1 ELSE 1 END * rb.soldlei_col,
      rb.ordine, rb.idxloc, nb.simbol simb_banca, nbc.den_cont, nbc.nrcont, sub.den_subunit, ncb.simbol contrepr, CASE rb.tiptranz WHEN 1 THEN ''Incasare'' ELSE ''Plata'' END tiptranz,
      CASE
        WHEN Coalesce(rb.curs,0) &lt;&gt; 0 THEN rb.curs
        WHEN Coalesce(rb.sold_col,0) &lt;&gt; 0 AND Coalesce(rb.soldlei_col,0) &lt;&gt; 0 THEN rb.soldlei_col/rb.sold_col
        ELSE 1
      END as curs, rb.taxcode_saft, '||sCursRef|| gUserAlias || '
    FROM rb
      LEFT JOIN nbankcont  nbc  ON nbc.codbankcont  = rb.codbanca
      LEFT JOIN nbank      nb   ON nb.codbank       = nbc.codbank
      LEFT JOIN npers      ag   ON ag.codpers       = rb.agent
      LEFT JOIN npart      part ON part.codpart     = rb.codpart
      LEFT JOIN npers      pers ON pers.codpers     = rb.codpers
      LEFT JOIN ngest      ng   ON ng.codgest       = rb.codgest
      LEFT JOIN nsubunit   sub  ON sub.codsubunit   = rb.subunitatea
      LEFT JOIN nbankcont1 nbc1 ON nbc1.codbankcont = rb.codbanca     AND nbc1.alstart &lt;= rb.anluna AND nbc1.alstop &gt;= rb.anluna
      LEFT JOIN iobank1    iob1 ON iob1.codiobank   = nbc1.codiobanca AND iob1.alstart &lt;= rb.anluna AND iob1.alstop &gt;= rb.anluna
      LEFT JOIN ncont      nc   ON nc.codcont       = rb.cont
      LEFT JOIN ncont1     nc1  ON nc1.codcont      = rb.cont AND nc1.alstart &lt;= rb.anluna AND nc1.alstop &gt;= rb.anluna
      LEFT JOIN nconts     cs   ON cs.codconts      = nc1.contsecundar
      LEFT JOIN ncont      ncb  ON ncb.codcont      = iob1.cont
      LEFT JOIN r               ON r.codbank        = nbc.codbank' || gSuplJoins || '
    ORDER BY rb.datareg, rb.ordine, rb.idxloc';

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

  IF getsubunitate() &lt;&gt; 1 AND fnc_getvalconstantalucru('Holding')::NUMERIC &lt;&gt; 1 THEN
    SELECT DEN_SUBUNIT
    INTO vDenSubunit
    FROM NSUBUNIT
    WHERE CodSubunit = current_setting('PKG_GLOBALS.SUBUNITATE', true)::NUMERIC;

    EXECUTE 'SELECT Count(1), Sum(INCASARE), SUM(PLATA), Sum(sold_col), Sum(soldlei_col) FROM ' || tmpName || ' WHERE SUBUNITATEA &lt;&gt; $1'
    INTO vCount, vValI, vValP, vSold_Col, vSoldLei_Col USING vDenSubunit;

    IF vCount &gt; 0 THEN
      EXECUTE 'DELETE FROM ' || tmpName || ' WHERE SUBUNITATEA &lt;&gt; $1' USING vDenSubunit;
      IF vValI &lt;&gt; 0 OR  vValP &lt;&gt; 0 OR vSold_Col &lt;&gt; 0 OR vSoldLei_Col &lt;&gt; 0 THEN
        EXECUTE 'INSERT INTO ' || tmpName || ' (
          DATAREG, AGENT, EXPLICATII, INCASARE, PLATA, VALDOC, VALDOCLEI, SOLD_COL, SOLDLEI_COL, ORDINE, IDXLOC, SUBUNITATEA)
          SELECT to_date(''' || coalesce(To_Char(dataFin, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy''), '' '', ''Tranzactii alte subunitati'', $1, $2, 0, 0, $3, $4, 9, 0, ''Altele'' '
          USING vValI, vValP, vSold_Col, vSoldLei_Col;
      END IF;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regjurnal_processlist</obj_name>
  <obj_hashval>873226ecccc8941683d707f1b471753d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_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;
  sJurnal     varchar;
  aSitV       numeric;
  aBancaV     numeric;
  aMonedaV    numeric;
  sCursRef    varchar := ', 1';
  vSubunit    numeric := CASE current_setting('PKG_LIST_BASE_REGJURNAL.p_SubCurenta', true)::numeric WHEN 0 THEN 1 ELSE null  END ;
  cnt         numeric;
  sCnt        varchar;

  chkInfoValuta boolean;
  vLunaFin      numeric;
  vLunaIni      numeric;
BEGIN
  --Florin 13.05.2022 - fixat 54257
  --Adina 10.05.2021 - alstart,alstop, vLunaIni, vLunaFin
  --Bogdan 31.07.2020
  CALL PRC_AL_CHECK('ncont1', 0);
  vLunaFin := (SELECT pkg_list_base_regjurnal_LunaFin.WME_RESULT FROM pkg_list_base_regjurnal_LunaFin(NULL,NULL));
  vLunaIni := (SELECT WME_RESULT FROM pkg_list_base_regjurnal_LunaIni(NULL,NULL));

  gSuplCols := 'v_jurnal j, nsubunit ns, ngest ng, centrecost c';

  call pkg_list_struct_startsuplcols();

  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONT' , 'CPD', 'CPD.CODCONT = J.CONTD',NULL,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONT' , 'CPC', 'CPC.CODCONT = J.CONTC',NULL,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONT1', 'C1D', 'C1D.CODCONT1 = (select wme_result from PKG_PLANCONTURI_GET_CONT_COD_CARACT_LUNA(null, J.CONTD, J.AN, J.LUNA))');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONT1', 'C1C', 'C1C.CODCONT1 = (select wme_result from PKG_PLANCONTURI_GET_CONT_COD_CARACT_LUNA(null, J.CONTC, J.AN, J.LUNA))');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONTS', 'CSD', 'CSD.CODCONTS = C1D.CONTSECUNDAR',NULL,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONTS', 'CSC', 'CSC.CODCONTS = C1C.CONTSECUNDAR',NULL,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONTT', 'CTD', 'CTD.CODCONTT = C1D.CONTTERTIAR' ,NULL,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCONTT', 'CTC', 'CTC.CODCONTT = C1C.CONTTERTIAR' ,NULL,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TMP_UTILIZATOR', 'UTD', 'UTD.CODUTILIZATOR = (select wme_result from PKG_LIST_BASE_UTILS_GetUserDoc(null, CASE WHEN j.tipdoc IN (29,30,31,33) THEN j.indexlocal ELSE j.coddoc END, j.tipdoc))');
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPART', 'NP', 'NP.CODPART = pkg_list_utilfisacont_GetPartJurnal(j.codjurnal)',NULL,NULL);

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

  PERFORM PKG_LIST_BASE_UTILS_CLEAR_SIMBOL_LIPSA();
  DELETE FROM TMP_NCONT1_BAL;

  IF  current_setting('PKG_LIST_BASE_REGJURNAL.p_plan', true)::numeric = 2 then
    sJurnal := 'v_jurnal_s';
    INSERT INTO TMP_NCONT1_BAL(CODCONT, SIMBOLPLANP)
    SELECT C.CODCONT, C.SIMBOL
    FROM NCONT C
         LEFT JOIN NCONT1 C1 ON  C1.CODCONT = C.CODCONT AND vLunaFin BETWEEN C1.ALSTART AND C1.ALSTOP
    WHERE COALESCE( C1.CONTSECUNDAR, 0) = 0;
  ELSIF  current_setting('PKG_LIST_BASE_REGJURNAL.p_plan', true)::numeric  = 3 then
    sJurnal := 'v_jurnal_t';
    INSERT INTO TMP_NCONT1_BAL (CODCONT, SIMBOLPLANP)
    SELECT C.CODCONT, C.SIMBOL
    FROM NCONT C
         LEFT JOIN NCONT1 C1 ON  C1.CODCONT = C.CODCONT AND vLunaFin BETWEEN C1.ALSTART AND C1.ALSTOP
    WHERE
       COALESCE( C1.CONTTERTIAR, 0) = 0;
  ELSE
    sJurnal := 'v_jurnal';
  END IF;

  IF  current_setting('PKG_LIST_BASE_REGJURNAL.p_plan', true)::numeric  &gt; 1 THEN
    INSERT INTO TMP_LIPSA_CORESP_PLANP ( SIMBOL)
    SELECT DISTINCT  t.SIMBOLPLANP
    FROM JURNAL x INNER JOIN TMP_NCONT1_BAL t ON  t.codcont = x.contd
    WHERE an * 12 + luna BETWEEN vLunaIni AND vLunaFin
    union
    SELECT DISTINCT  t.SIMBOLPLANP
    FROM JURNAL x INNER JOIN TMP_NCONT1_BAL t ON  t.codcont = x.contc
    WHERE an * 12 + luna BETWEEN vLunaIni AND vLunaFin;
  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(j.datadoc,''dd.mm.yyyy'' )))';
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || ' (
          NAV_CODDOC,NAV_TIPDOC, TIPINREG,
          CONTDEBIT, CONTCREDIT, SUMADEBIT, SUMACREDIT, VALOAREV, IFRS, IFRSV, GRUP, GRUPV,
          TIPDOC, DOCUMENT_JRN, EXPLICATII,
          DATADOC, GESTIUNE, ORDINE,
          SUBUNITATEA, CENTRUCOST, CENTRUCOSTSIMB, CURS_REF' || gUserFields || ')
        SELECT
          CASE WHEN j.tipdoc IN (32,36) then NULL else j.coddoc end,
          CASE WHEN j.tipdoc IN (32,36) then NULL else j.tipdoc end, j.tipinreg,
          j.SIMBCONTDEBIT,
          j.SIMBCONCREDIT,
          j.v, j.v, j.valoarev, j.valoare_ifrs, j.valoarev_ifrs, j.valoaregrup,
          j.valoaregrup/(Case  When j.valoarev= 0 then  1 else j.valoare/j.valoarev end),
          (select PKG_LIST_BASE_UTILS_DECODE_TIPDOC.wme_result from PKG_LIST_BASE_UTILS_DECODE_TIPDOC(null,J.TIPDOC)),
          j.document, j.obs,
          CASE WHEN j.tipdoc IN (32,36) THEN last_day(to_date(to_char(j.an,''fm0000'')||to_char(j.luna,''fm00''),''yyyymm''))
                ELSE j.datadoc
          END,
          ng.den_gest, j.tipdoc + (case when j.tipdoc = 32 then 100 end),
          ns.den_subunit, c.denumire, c.simbol ' || sCursRef ||gUserAlias || '
        FROM ' || sJurnal || ' j
            INNER JOIN nsubunit   ns ON ns.codsubunit = j.subunitatea ' || (SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL, 'J', NULL, NULL, vSubunit)) || '
            LEFT  JOIN ngest      ng on ng.codgest    = coalesce(j.gest,0)
            LEFT  JOIN centrecost c  on c.codcentru   = j.codcentru' || gSuplJoins;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regjurnal_subcurenta</obj_name>
  <obj_hashval>9a4cb89c127ff2315e21e7d07e39dac9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_subcurenta()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
begin
  return  current_setting('PKG_LIST_BASE_REGJURNAL.p_SubCurenta')::numeric;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regularizpart_processlist</obj_name>
  <obj_hashval>a28c4c750ae515a860dc8684f7c14822</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regularizpart_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert        varchar;
  sFiltru        varchar;
  gSuplCols      varchar := 'npart p, nbank b, nmonede m, ncont c, ncont cdif';
  pCFavorabilV   numeric;
  pCNefavorabilV numeric;
  gUserFields    VARCHAR := '';
  gUserAlias     VARCHAR := '';
  gNullAlias     VARCHAR := '';
  gSuplJoins     VARCHAR := '';
BEGIN
  --Florin 17.02.2025 - sinc. Oracle
  --Florin 29.07.2020

  pCFavorabilV    := fnc_getvalconstanta('CFavorabilV'  , getlunalucru(), getanlucru());
  pCNefavorabilV  := fnc_getvalconstanta('CNefavorabilV', getlunalucru(), getanlucru());

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

  sFiltru := 'r.TipReg = 46';
  IF (current_setting('PKG_LIST_SELECTLUNAAN.vLunaStart', true)::numeric = current_setting('PKG_LIST_SELECTLUNAAN.vLunaStop', true)::numeric) THEN
    sFiltru := coalesce(sFiltru,'') || '
      AND r.an * 12 + r.luna = ' || coalesce(current_setting('PKG_LIST_SELECTLUNAAN.vLunaStart', true)::numeric, 0);
  ELSE
  sFiltru := coalesce(sFiltru,'') || '
      AND r.an * 12 + r.luna BETWEEN ' || coalesce(current_setting('PKG_LIST_SELECTLUNAAN.vLunaStart', true)::numeric, 0) || ' AND ' ||
        coalesce(current_setting('PKG_LIST_SELECTLUNAAN.vLunaStop', true)::numeric, 0);
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || ' (Nr, Data_REGP, Moneda, Curs, Part, Cont, Doc, SoldV, SoldL, SoldReg, Dif, CursVechi, Sub, Gest' ||
    gUserFields || ')
    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
          ),
    G AS (
      SELECT codsubunit, Max(den_gest) den_gest
      From (SELECT ng.codsubunit, den_gest, dense_rank() over (partition by ng.codsubunit order by coalesce(gmaster, 0) desc, codgest) g from ngest ng) y
      where y.g = 1
      GROUP BY y.codsubunit
    ),
    R AS (
      SELECT
        r.Nrdoc, r.DataDoc, r.codbank, r.codmoneda, r.Curs, r.an, r.luna,
        r1.SoldDocVal, r1.SoldDoc, r1.SoldDocReg, r1.cont, r1.semnificatie,
        i.partener, i.PrefixDoc||i.NrDoc||''/''||To_Char(i.DataDoc,''dd.mm.yyyy'') AS Document, i.subunitatea
      FROM reg1 r1
        INNER JOIN reg     r ON r.codreg     = r1.codreg
        INNER JOIN general g ON g.codgeneral = r1.codgeneral
        INNER JOIN intrari i ON i.codintr    = g.coddoc AND i.tipdoc = g.tipdoc
      WHERE ' || coalesce(sFiltru,'') || '
        AND r1.semnificatie IN (100, 110, 120, 140)
      UNION ALL
      SELECT
        r.Nrdoc, r.DataDoc, r.codbank, r.codmoneda, r.Curs, r.an, r.luna,
        r1.SoldDocVal, r1.SoldDoc, r1.SoldDocReg, r1.cont, r1.semnificatie,
        i.partener, ''DVI''||dvi.NrDoc||''/''||To_Char(dvi.DataDoc,''dd.mm.yyyy'') AS Document, i.subunitatea
      FROM reg1 r1
        INNER JOIN reg     r ON r.codreg     = r1.codreg
        INNER JOIN general g ON g.codgeneral = r1.codgeneral
        INNER JOIN dvi       ON dvi.coddvi   = g.coddoc
        INNER JOIN intrari i ON i.codintr    = dvi.codintr
      WHERE ' || coalesce(sFiltru,'') || '
        AND r1.semnificatie IN (130)
    UNION ALL
    SELECT
      r.Nrdoc, r.DataDoc, r.codbank, r.codmoneda, r.Curs, r.an, r.luna,
      r1.SoldDocVal, r1.SoldDoc, r1.SoldDocReg, r1.cont, r1.semnificatie,
      i.partener, i.PrefixDoc||i.NrDoc||''/''||To_Char(i.DataDoc,''dd.mm.yyyy'') AS Document, i.subunitatea
    FROM reg1 r1
      INNER JOIN reg     r ON r.codreg     = r1.codreg
      INNER JOIN general g ON g.codgeneral = r1.codgeneral
      INNER JOIN iesiri  i ON i.codies     = g.coddoc AND i.tipdoc = g.tipdoc
    WHERE ' || coalesce(sFiltru,'') || '
      AND r1.semnificatie IN (200, 210, 220, 240)
    UNION ALL
    SELECT
      r.Nrdoc, r.DataDoc, r.codbank, r.codmoneda, r.Curs, r.an, r.luna,
      r1.SoldDocVal, r1.SoldDoc, r1.SoldDocReg, r1.cont, r1.semnificatie,
      t1.codpart partener, t1.Doc||t1.NrDoc||''/''||To_Char(t1.DataDoc,''dd.mm.yyyy'') AS Document, t.subunitatea
    FROM reg1 r1
      INNER JOIN reg     r  ON r.codreg      = r1.codreg
      INNER JOIN general g  ON g.codgeneral  = r1.codgeneral
      INNER JOIN trezor1 t1 ON t1.codtrezor1 = g.coddoc
      INNER JOIN trezor  t  ON t.codtrezor   = t1.codtrezor
    WHERE ' || coalesce(sFiltru,'') || '
      AND r1.semnificatie IN (310, 410, 330, 430)
    UNION ALL
    SELECT
      r.Nrdoc, r.DataDoc, r.codbank, r.codmoneda, r.Curs, r.an, r.luna,
      r1.SoldDocVal, r1.SoldDoc, r1.SoldDocReg, r1.cont, r1.semnificatie,
      nc.part partener, ''NC''||nc.NrDoc||''/''||To_Char(nc.DataDoc,''dd.mm.yyyy'') AS Document, nc.subunitatea
    FROM reg1 r1
      INNER JOIN reg     r ON r.codreg     = r1.codreg
      INNER JOIN general g ON g.codgeneral = r1.codgeneral
      INNER JOIN nc1       ON nc1.codnc1   = g.coddoc
      INNER JOIN nc        ON nc.codnc     = nc1.codnc
    WHERE ' || coalesce(sFiltru,'') || '
      AND r1.semnificatie IN (1200, 1201)
    UNION ALL
    SELECT
      r.Nrdoc, r.DataDoc, r.codbank, r.codmoneda, r.Curs, r.an, r.luna,
      r1.SoldDocVal, r1.SoldDoc, r1.SoldDocReg, r1.cont, r1.semnificatie,
      i.partener, ''Litigiu ''||i.PrefixDoc||i.NrDoc||''/''||To_Char(i.DataDoc,''dd.mm.yyyy'') AS Document, i.subunitatea
    FROM reg1 r1
      INNER JOIN reg      r  ON r.codreg           = r1.codreg
      INNER JOIN general  g  ON g.codgeneral       = r1.codgeneral
      INNER JOIN obligpif o  ON o.codgeneral       = g.codgeneral
      INNER JOIN a        ol ON ol.rootcodobligpif = o.codobligpif
      INNER JOIN general  gl ON gl.codgeneral      = ol.codgeneral AND gl.tipdoc IN (19,21,22,26)
      INNER JOIN iesiri   i  ON i.codies           = gl.coddoc AND i.tipdoc = gl.tipdoc
    WHERE ' || coalesce(sFiltru,'') || '
      AND r1.semnificatie = 1303
    )
    SELECT
      r.NrDoc, r.dataDoc, m.Simbol SMon, r.Curs,
      p.Den_Part, c.simbol cont, r.Document,
      r.SoldDoc, r.SoldDocVal, r.SoldDocReg, r.SoldDocReg - r.SoldDocVal, r.SoldDocVal / r.SoldDoc ,
      s.den_subunit, g.den_gest ' || gUserAlias || '
    FROM R
      LEFT JOIN npart    p    ON p.codpart    = r.partener
      LEFT JOIN nmonede  m    ON m.codmoneda  = r.codmoneda
      LEFT JOIN nsubunit s    ON s.codsubunit = r.subunitatea
      LEFT JOIN g             ON g.codsubunit = r.subunitatea
      LEFT JOIN ncont    c    ON c.codcont    = PKG_LIST_BASE_UTILS_icont_CodCont(r.cont,r.partener,r.an*12+r.luna,r.semnificatie)
      LEFT JOIN ncont    cdif ON cdif.codcont = CASE WHEN r.SoldDocReg - r.SoldDocVal &lt; 0 THEN ' || coalesce(pCNefavorabilV, 0) ||
                                                   ' ELSE ' || coalesce(pCFavorabilV, 0) || ' END' || gSuplJoins;
    --insert into x(view_name, test) values ('regpart', sinsert);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_restlistgest_setjoinuri</obj_name>
  <obj_hashval>8c33b215cda0c1e80bea0794bc7a63ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_restlistgest_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_RESTLISTGEST.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_restlistnp_setjoinuri</obj_name>
  <obj_hashval>ca9339bb0acb70190dcf7d68231f1eba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_restlistnp_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.12.2020 - sincronizare cu Oracle
  --Adina 15.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_RESTLISTNP.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rezdoc_setparams</obj_name>
  <obj_hashval>d4c2c9680e90722c81037842f9d78bb1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rezdoc_setparams(pcodcomanda numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  perform set_config('PKG_LIST_BASE_REZDOC.vCodComanda',(pCodComanda)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rptvanzum_setjoinuri</obj_name>
  <obj_hashval>df994724a992e3cbe5082d5a982f0450</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rptvanzum_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 10 septembrie 2020
  NULL;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rptvanzum_setparams</obj_name>
  <obj_hashval>9ee4762afe9e9afbed078d26068c6f4a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rptvanzum_setparams(acodum numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 10 septembrie2020
  perform set_config('PKG_LIST_BASE_RPTVANZUM.gCodUm',(aCodUm)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_scadcheltavans_processlist</obj_name>
  <obj_hashval>b6f69e0eb68551d115d11fd237352a33</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_scadcheltavans_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC RECORD;
  sInsert       varchar := '';
  sSelect       varchar := '';
  sXDinSel       varchar := '';
  sDinSel       varchar := '';
  sDinIns       varchar := '';
  sDataStart     varchar := coalesce(To_Char(getANLUCRU(), 'fm0000'),'') || coalesce(To_Char(getLUNALUCRU(), 'fm00'),'') || '01';
  vAL           numeric := getANLUNALUCRU();
  vAn           numeric := getANLUCRU();
  vLuna         numeric := getLUNALUCRU();
  gSuplCols     VARCHAR := 'CHELTAVANS CAV, CHELTAVANS1 CAV1, NPART P, NGEST G, IOART IOA';
   gUserFields   VARCHAR := '';
  gUserAlias    VARCHAR := '';
  gNullAlias    VARCHAR := '';
  gSuplJoins    VARCHAR := '';
  vNrLuni       NUMERIC := COALESCE(current_setting('PKG_LIST_BASE_SCADCHELTAVANS.vNrLuni', true)::NUMERIC,0);  -- este setat in pkg_list_base_scadcheltavans_baga_dinamic_cols (nu stiu de unde este apelata)
BEGIN
  --Florin 10.01.2023 - fixat 56751
  --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_SCADCHELTAVANS.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'');
  gNullAlias  := coalesce(gNullAlias,'');
  gSuplJoins  := coalesce(gSuplJoins,'');
  gSuplCols   := coalesce(gSuplCols,'');

  FOR vRec IN (
    SELECT FieldName, IndexLocal
    FROM tmp_dinamic_cols
    WHERE upper(FieldName) LIKE 'D%' AND  Coalesce(IndexLocal, 0) &gt; 0
    ORDER BY IndexLocal
  )
  LOOP
    sDinIns  := coalesce(sDinIns,'')   || ','   || coalesce(vRec.FieldName,'');
    sDinSel  := coalesce(sDinSel,'')   || ',T.' || coalesce(vRec.FieldName,'');
    sXDinSel := coalesce(sXDinSel,'') || ',Sum(Case WHEN AL =' || coalesce((vAl + vRec.IndexLocal - 1)::varchar,'') || ' THEN AMOL ELSE 0 END ) ' || coalesce(vRec.FieldName,'');
  END LOOP;

  INSERT INTO x(view_name, test) VALUES ('sDinIns', sDinIns);

  sInsert :=
  'INSERT INTO ' || tmpName || ' (
    TIP, ART,
    NRDOC, DATADOC, GEST, PART, OBS, IOART,
    VALOARE, ANINCEPUT, LUNAINCEPUT, AMO, REST,
    DURATAN, DURATAF' || coalesce(sDinIns,'') || gUserFields || ')';

  sSelect := '
  WITH RECURSIVE aa(datastart,nivel) AS
  (
    SELECT To_Date(''' || coalesce(sDataStart,'') || ''',''yyyymmdd'') datastart, 1 nivel
    UNION ALL
    SELECT add_months(aa.datastart,1),(aa.nivel+1) as nivel FROM aa WHERE aa.nivel &lt;= ' || vNrLuni::varchar || '
  ),
  T AS (
    SELECT CODCHELTAVANS1' || coalesce(sXDinSel,'') || '
    FROM (
      SELECT
        cav1.CODCHELTAVANS1, xAl.AL,
        CASE
          WHEN CAV.DATASTART IS NOT NULL AND CAV.DATAEND IS NOT NULL AND CAV.DATAEND   &lt; xAl.DATASTART THEN 0
          WHEN CAV.DATASTART IS NOT NULL AND CAV.DATAEND IS NOT NULL AND CAV.DATASTART &gt; xAl.DATAEND   THEN 0
          WHEN CAV.DATASTART IS NOT NULL AND CAV.DATAEND IS NOT NULL THEN (CAV1.VALOARE - Coalesce(CAV1.AMO,0))/(CAV.DATAEND - GREATEST(xAl.DATASTART, CAV.DATASTART) + 1)*(LEAST(xAl.DATAEND, CAV.DATAEND) - GREATEST(xAl.DATASTART, CAV.DATASTART))
          WHEN CAV.ANINCEPUT*12+CAV.LUNAINCEPUT &gt; xAL.AL THEN 0
          WHEN Coalesce(CAV1.DURATAF,0) = 0 THEN 0
          WHEN CAV.ANINCEPUT*12+CAV.LUNAINCEPUT+CAV1.DURATAF &lt;= xAL.AL THEN 0
          ELSE (CAV1.VALOARE - Coalesce(CAV1.AMO,0)) / CAV1.DURATAF
        END AMOL
      FROM CHELTAVANS1 CAV1
        INNER JOIN CHELTAVANS CAV ON CAV.CODCHELTAVANS = CAV1.CODCHELTAVANS
        CROSS JOIN (SELECT EXTRACT(YEAR FROM DATASTART)*12+EXTRACT(MONTH FROM DATASTART) AL, DATASTART, Last_Day(DATASTART) DATAEND
                    FROM (SELECT DATASTART FROM AA WHERE aa.nivel &lt;= ' || vNrLuni::varchar || ' ) xx
                   ) xAL
      WHERE CAV1.ANSTART = ' || coalesce(vAn::varchar,'') || ' AND CAV1.LUNASTART = ' || coalesce(vLuna::varchar,'') || '
    ) A_PG
    GROUP BY CODCHELTAVANS1
  )
  SELECT
    CASE WHEN Coalesce(CAV.IsVenit, 0) = 1 THEN ''VENIT'' ELSE ''CHELTUIALA'' END Tip,
    CASE
      WHEN i.codintr  IS NOT NULL THEN OBJ.DENUMIRE
      WHEN ies.codies IS NOT NULL THEN OBJ.DENUMIRE
      WHEN n.codnc    IS NOT NULL THEN ''Chelt Avans din NC ''
      WHEN o.semnificatie = 900   THEN ''Direct pe cheltuieli(TVA)''
      WHEN o.semnificatie = 950   THEN ''Datorii, taxe, impozite''
      WHEN o.semnificatie = 901   THEN ''Direct pe venituri(TVA)''
      WHEN o.semnificatie = 951   THEN ''Imprumuturi, subventii''
      ELSE NULL
    END DENUMIRE,
    COALESCE(I.NRDOC, IES.NRDOC, N.NRDOC, T1.NRDOC) NRDOC, COALESCE(I.DATADOC, IES.DATADOC, N.DATADOC, T1.DATADOC) DATADOC, G.DEN_GEST, P.DEN_PART, COALESCE(I1.OBS, IES1.OBS, N1.OBS, T1.OBS) OBS, IOA.DEN_IOART,
    CAV1.VALOARE, CAV.ANINCEPUT, CAV.LUNAINCEPUT, Coalesce(CAV1.AMO,0) AMO, (CAV1.VALOARE - Coalesce(CAV1.AMO,0)) REST,
    CASE WHEN CAV.DATASTART IS NOT NULL AND CAV.DATAEND IS NOT NULL THEN MONTHS_BETWEEN(CAV.DATASTART,CAV.DATAEND) + 1 ELSE Coalesce(CAV1.DURATAN,0) END DURATAN,
    CASE WHEN CAV.DATASTART IS NOT NULL AND CAV.DATAEND IS NOT NULL THEN (EXTRACT(YEAR FROM CAV.DATAEND) * 12 + EXTRACT(MONTH FROM CAV.DATAEND)) - (CAV1.ANSTART * 12 + CAV1.LUNASTART) + 1 ELSE Coalesce(CAV1.DURATAF,0) END DURATAF' || coalesce(sDinSel,'') || gUserAlias || '
  FROM T
    INNER JOIN CHELTAVANS1 CAV1 ON CAV1.CODCHELTAVANS1 = T.CODCHELTAVANS1
    INNER JOIN CHELTAVANS  CAV  ON CAV.CODCHELTAVANS   = CAV1.CODCHELTAVANS
    LEFT  JOIN INTRARI1    I1   ON I1.CODINTR1         = CAV.CODINTR1
    LEFT  JOIN INTRARI     I    ON I.CODINTR           = I1.CODINTR
    LEFT  JOIN IESIRI1     IES1 ON IES1.CODIES1        = CAV.CODIES1
    LEFT  JOIN IESIRI      IES  ON IES.CODIES          = IES1.CODIES
    LEFT  JOIN NC1         N1   ON N1.CODNC1           = CAV.CODNC1
    LEFT  JOIN NC          N    ON N.CODNC             = N1.CODNC
    LEFT  JOIN OBLIGPIF    O    ON O.CODOBLIGPIF       = CAV.CODOBLIGPIF AND O.SEMNIFICATIE IN (900, 950, 901, 951)
    LEFT  JOIN GENERAL     GE   ON GE.CODGENERAL       = O.CODGENERAL
    LEFT  JOIN TREZOR1     T1   ON T1.CODTREZOR1       = GE.CODDOC
    LEFT  JOIN NGEST       G    ON G.CODGEST           = I1.GESTACT
    LEFT  JOIN NPART       P    ON P.CODPART           = COALESCE(IES.PARTENER, I.PARTENER, N.PART, O.CODPART)
    LEFT  JOIN IOART       IOA  ON IOA.CODIOART        = Coalesce(CAV.CODIOART,0)
    LEFT  JOIN NARTOBJ     OBJ  ON OBJ.CODOBIECT       = Coalesce(IES1.CODOBIECT, I1.CODOBIECT)' || gSuplJoins;
   INSERT INTO x(view_name, test) VALUES ('sSelect', sInsert || sSelect);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_scadcheltavans_setjoinuri</obj_name>
  <obj_hashval>a78832d78a2cab99b77c0a82d8bdadf7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_scadcheltavans_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 26 august 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_SCADCHELTAVANS.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_scadentarcl_processlist</obj_name>
  <obj_hashval>fcd0229364710f413a0a741f7bf1c555</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_scadentarcl_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC        RECORD;
  sInsert     varchar := '';
  sSelect     varchar := '';
  sUpdate     varchar := '';
  sFAdaosDoc  varchar := ', NULL ADAOS';
  sValDiscZP  varchar := ', NULL VALDISCZP, NULL VALDISCC';
  aSitV       numeric;
  aBancaV     numeric;
  aMonedaV    numeric;
  sCursRef    varchar := ', 1 ';
  pRegProviz  NUMERIC;
  i           NUMERIC;
  aVTot       NUMERIC;
  gSuplCols   VARCHAR := '';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  wmeRes      BOOLEAN;

  sConv       VARCHAR(100);
BEGIN
  --Florin 01.10.2025 - sinc. Oracle
  --Stef 31.05.2023
  CALL PRC_AL_CHECK('ncont1'  ,0);
  CALL PRC_AL_CHECK('npart1'  ,0);
  CALL PRC_AL_CHECK('nagenda1',0);

  IF  NOT pkg_list_selectscadentar_tmpok() THEN
    PERFORM PKG_LIST_BASE_SCADENTARCL_UmpleTmp(aListId);
  END IF;
  sConv      := Coalesce(current_setting('PKG_LIST_BASE_SCADENTARCL.sConv', true),'');

  pRegProviz := Coalesce(fnc_GetValConstanta('RegProviz',EXTRACT( YEAR FROM to_date(current_setting('PKG_LIST_BASE_SCADENTARCL.dDataRef', true),'dd.mm.yyyy'))::numeric, EXTRACT( MONTH FROM to_date(current_setting('PKG_LIST_BASE_SCADENTARCL.dDataRef', true),'dd.mm.yyyy'))::numeric)::numeric,0);

  gSuplCols :=
    'TMP_SCADENTARCL S, TMP_SCADENTARST STINS, 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, NGEST G,'||
    '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_SCADENTARCL.gSuplCols',gSuplCols,false);

  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 := ', PKG_LIST_BASE_UTILS_GETCURSREFERINTA('||aMonedaV::varchar||','||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' || sConv || ' 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, ''' || coalesce(current_setting('PKG_LIST_BASE_SCADENTARCL.sDataRef', true),'') || ''',(s.restval - Coalesce(stins.valoare,0)))), 0)
    END' || sConv || ' VALDISCZP,
    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(''' || coalesce(current_setting('PKG_LIST_BASE_SCADENTARCL.sDataRef', true),'') || ''',''dd.mm.yyyy''), (s.restval - Coalesce(stins.valoare,0)))), 0)
    END' || sConv || ' VALDISCC';
  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,
    DOCUMENT_LEG,
    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,
    SUBUNITATE, EXCLUSPLATA,
    PROVIZION,
    CREDITC,
    SERTDECONT, SERTDOC, SERTSER, SERTNRDOC, SERTDATADOC, SERTVALDOC, SERTDATADEC, SERTVALASOC,
    CENTRUCOST, SIMBCENTRUCOST,
    AVANS, PROCTVAMEDIU, TVAINCAS,
    PARTVALIESAC, PARTVALIESAP,
    CF_AS, CF_CURS,
    ANSAPT, CURS,CURS_INI,CURS_REF,ADAOSDOC,VALDISCZP, VALDISCC ' || gUserFields || ')';

  sSelect := '
  SELECT
    CASE WHEN ts.codsubunit IS NULL OR s.initializari = 1 THEN NULL ELSE s.CodDoc  END AS NAV_CodDoc,
    CASE WHEN ts.codsubunit IS NULL OR s.initializari = 1 THEN NULL ELSE s.CodDoc1 END AS NAV_CodDoc1,
    CASE WHEN ts.codsubunit IS NULL OR s.initializari = 1 THEN NULL ELSE s.TipDoc  END AS NAV_TipDoc,
    (select wme_result from pkg_list_base_utils_decode_tipdoc(null,s.TipDoc)) AS TipDoc,
    np.den_part, g.den_gest, fisc.codfiscal, slivr.obs LIVR_DEN, llivr.den_localit LIVR_LOC, jlivr.den_judet LIVR_JUD, zlivr.den_zona LIVR_ZONA, ncp.den_clasep,
    (case when np.blocat=1 then ''DA'' else ''NU'' end) BLOCAT, (case when s.blocat=1 then ''DA'' else ''NU'' end) BLOCATDOC, s.doc, s.nrdoc, s.datadoc, s.nri, s.obs OBSDOC, Coalesce(s.seriadoc,dc.serie) SERDOC,
    CASE WHEN ag_doc.codpers &lt;&gt; 0 THEN ag_doc.nume||'' ''||ag_doc.prenume ELSE ag_doc.nume END AGDOC,
    Coalesce(s.termen,s.datadoc) TERMEN, EXTRACT(YEAR FROM Coalesce(s.termen,s.datadoc)) AS TERMENAN, EXTRACT(MONTH FROM Coalesce(s.termen,s.datadoc)) AS TERMENLUNA,
    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 || ' AS VALOARE,
    s.majorare,
    (s.restval - Coalesce(stins.valoare,0))' || sConv || ' AS REST,
    (s.resttva - Coalesce(stins.tva,0))' || sConv || ' AS RESTTVA,
    Sum((s.restval - Coalesce(stins.valoare,0))' || sConv || ') OVER (PARTITION BY s.codpart) AS RESTPART,
    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)
    END ' || sConv || ' AS valmaj,
    (case when s.termen is NULL then 0 else s.termen - s.datadoc end) ZILE_SCADENTA, CASE WHEN s.zile_trecute &gt; 0 THEN s.zile_trecute ELSE 0 END ZILE_TRECUTE, s.zile_depasire,
    NULLIF(s.doc    ||s.nrdoc    ||''/''||to_char(s.datadoc,    ''dd.mm.yyyy''),''/'') AS DOCUMENT,
    NULLIF(s.leg_doc||s.leg_nrdoc||''/''||to_char(s.leg_datadoc,''dd.mm.yyyy''),''/'') DOCUMENT_LEG,
    mon.den_moneda MONEDA, nc.simbol CONT, cs.simbol CONTS,
    CASE WHEN s.zile_depasire &lt;= 0                THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END Z_0,
    CASE WHEN s.zile_depasire BETWEEN   1 AND  30 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END L_1,
    CASE WHEN s.zile_depasire BETWEEN  31 AND  60 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END L_2,
    CASE WHEN s.zile_depasire BETWEEN  61 AND  90 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END L_3,
    CASE WHEN s.zile_depasire BETWEEN  91 AND 120 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END L_4,
    CASE WHEN s.zile_depasire BETWEEN 121 AND 150 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END L_5,
    CASE WHEN s.zile_depasire BETWEEN 151 AND 180 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END L_6,
    CASE WHEN s.zile_depasire BETWEEN  91 AND 180 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END T_2,
    CASE WHEN s.zile_depasire BETWEEN 181 AND 270 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END T_3,
    CASE WHEN s.zile_depasire BETWEEN 181 AND 210 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END T_31,
    CASE WHEN s.zile_depasire BETWEEN 211 AND 240 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END T_32,
    CASE WHEN s.zile_depasire BETWEEN 241 AND 270 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END T_33,
    CASE WHEN s.zile_depasire BETWEEN 271 AND 360 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END T_4,
    CASE WHEN s.zile_depasire BETWEEN   1 AND   7 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END S_1,
    CASE WHEN s.zile_depasire BETWEEN   8 AND  15 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END S_2,
    CASE WHEN s.zile_depasire BETWEEN  16 AND  21 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END S_3,
    CASE WHEN s.zile_depasire BETWEEN  22 AND  30 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END S_4,
    CASE WHEN s.zile_depasire &gt;  30               THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END P_30,
    CASE WHEN s.zile_depasire &gt;  60               THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END P_60,
    CASE WHEN s.zile_depasire &gt;  90               THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END P_90,
    CASE WHEN s.zile_depasire &gt; 360               THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END P_360,
    CASE WHEN s.zile_depasire BETWEEN  -7 AND  -1 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END TS_1,
    CASE WHEN s.zile_depasire BETWEEN -14 AND  -8 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END TS_2,
    CASE WHEN s.zile_depasire BETWEEN -21 AND -15 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END TS_3,
    CASE WHEN s.zile_depasire BETWEEN -28 AND -22 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END TS_4,
    CASE WHEN s.zile_depasire &lt; -28               THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END TS_4p,
    sub.den_subunit SUBUNITATE, (case when s.exclusplata=1 then ''DA'' else ''NU'' end) EXCLUSPLATA,
    (s.restval - Coalesce(stins.valoare,0)) * Coalesce(s.coefprovizion,0) * CASE WHEN ' || coalesce(pRegProviz::varchar,'') || ' = 2 AND o.semnificatie = 1303 THEN s.cursini ELSE s.curs END PROVIZION,
    COALESCE (xa1.creditclient, np1.creditclient) CREDITC,
    TLSS.DECONT SERTDECONT, TLSS.DOC SERTDOC, TLSS.SER SERTSER, TLSS.NRDOC SERTNRDOC, TLSS.DATADOC SERTDATADOC, TLSS.VALOARE SERTVALDOC, TLSS.DATADECONT SERTDATADEC, TLSS.VALASOC SERTVALASOC,
    CC.DENUMIRE CENTRUCOST, CC.SIMBOL SIMBCENTRUCOST,
    CASE WHEN O.semnificatie IN (110111,210,211,310,330,410,430) THEN ''DA'' ELSE ''NU'' END AVANS, Coalesce(S.TVAMediu,0) PROCTVAMEDIU, (case when s.TvaIncasare=1 then ''DA'' else ''NU'' end) TVAINCAS,
    Coalesce(PCA.PARTVALIESAC,0) PARTVALIESAC, Coalesce(PCA.PARTVALIESAP,0) PARTVALIESAP,
    TO_CHAR( Coalesce(s.termen,s.datadoc+Coalesce(np.scadentav,0)::integer),''IYYY.IW'') CF_AS, Coalesce(cfc.valoare,1) CF_CURS,
    s.ansapt, s.curs, s.cursini'||sCursRef||sFAdaosDoc||sValDiscZP||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 '||getAnLunaLucru()::varchar||' 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 '||getAnLunaLucru()::varchar||' 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 '||getAnLunaLucru()::varchar||' 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  tlss       ON tlss.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_LST_CURS         cfc        ON cfc.codmoneda            = s.moneda
    LEFT JOIN TMP_LST_SCAD_PARTVAL pca        ON pca.partener             = s.codpart
    LEFT JOIN TMP_UTILIZATOR       UTILIZATOR ON utilizator.codutilizator = s.userid'||
    gSuplJoins||'
  WHERE Abs(s.restval - Coalesce(stins.valoare,0)) &gt;= 0.01'||
  CASE
    WHEN current_setting('PKG_LIST_SELECTSCADENTAR.g_DetTranzInCurs', true)::boolean THEN '
    AND NOT(o.semnificatie = 600 AND Coalesce(stins.valoare,0) &lt;&gt; 0)'
    ELSE ''
  END;

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

  EXECUTE 'UPDATE ' || coalesce(tmpname,'') || ' SET CF_VALOARE = CF_CURS*REST';

  IF pkg_list_selectscadentar_calcdisctermen() THEN
    EXECUTE 'SELECT sum(valoare)
      FROM ' || coalesce(tmpname,'') || '
      WHERE NAV_TipDoc IN (19,26)' INTO aVTot ;
    perform set_config('PKG_LIST_BASE_SCADENTARCL.aVTot',COALESCE(aVTot::varchar,''),false);

    EXECUTE 'UPDATE ' || coalesce(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 WHEN ansapt='||vrec.Cod::varchar||' THEN rest ELSE 0 END)';
    END LOOP;
    sUpdate := 'UPDATE '||tmpname||' SET '||SubStr(sUpdate,2);

    IF  i &gt; 0 THEN
      EXECUTE sUpdate;
    END IF;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitbonretail_processlist</obj_name>
  <obj_hashval>c41f837f6ae2cdf962d559d494e232d8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitbonretail_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 := 'EMULARE E, EMULARE1 E1, NARTOBJ O';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
begin
  --Bogdan 10.07.2023 - 58827 : PG - Lista Situatia bonurilor emise
  --Bogdan 25.05.2021 - 542392 : PG - Lista Situatia bonurilor emise
  --Bogdan 25.01.2021

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = O.CODOBIECT',NULL);

  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias , gNullAlias , gSuplJoins , gSuplCols);
  perform set_config('PKG_LIST_BASE_SITBONRETAIL.gSuplCols',gSuplCols,false);
    gUserFields := coalesce(gUserFields,'');
    gUserAlias  := coalesce(gUserAlias,'') ;
    gNullAlias  := coalesce(gNullAlias,'') ;
    gSuplJoins  := coalesce(gSuplJoins,'') ;
    gSuplCols   := coalesce(gSuplCols,'')  ;

  sInsert := 'INSERT INTO '
  || coalesce (TMPNAME,'')
  || ' (ART, UM, CANT, CODINTERN, CODEXTERN, PRET, PRETRAFT, VAL, TVA, PROCTVA,
      DISCOUNT, DEN_IOART, DEN_GEST, CONTSERV, FARASTOC, COMANDA, TIPLIVRARE, CADOU,
      NRBON, DATABON, VALBON, VALDISCBON, CASAMARCAT, TVATOTAL, TVADISCOUNT, PARTENER,
      MONETAR, OPERATOR, SEDIU, AGENT, OBS, DELEGAT, INCASARE, INCASARE0, INCASARE1,
      INCASARE2, INCASARE3 '
  || gUserFields
  || ') ';
  sSelect := '
      WITH MAN_E1 AS
        ( SELECT E1.CODEMULARE1
          FROM EMULARE1           E1
               INNER JOIN EMULARE E ON E1.CODEMULARE = E.CODEMULARE
          WHERE
            E.DATACREARE BETWEEN to_timestamp ('''|| coalesce (To_Char (PKG_LIST_SELECTPERIOADA_DATAORAINI() ,'DD.MM.YYYY HH24:MI') ,'')|| ''',''DD.MM.YYYY HH24:MI'')
                             AND to_timestamp ('''|| coalesce (To_Char (PKG_LIST_SELECTPERIOADA_DATAORAFIN() ,'DD.MM.YYYY HH24:MI') ,'')|| ''',''DD.MM.YYYY HH24:MI'')
        )
        SELECT O.DENUMIRE, UM1.DEN_UM1, E1.CANT, O.CODINTERN,
          O.CODEXTERN, E1.PRET, E1.PRETART, E1.PRET * E1.CANT,
          E1.TVA, ROUND (coalesce (E1.TVA,0) / E1.CANT * E1.PRET * 100, 2) , E1.DISCOUNT, IOA.DEN_IOART,
          G.DEN_GEST, S.SIMBOL,
          CASE WHEN E1.FARASTOC = 1 THEN ''DA'' ELSE ''NU'' END,
          CASE WHEN C.CODCOMANDA &gt; 0 THEN C.PREFIXDOC||C.NRDOC||'' / ''||TO_CHAR (C.DATADOC,''DD.MM.YYYY'') END,
          CASE
            WHEN E1.TIPLIVRARE = 1 THEN ''Ridicata''
            WHEN E1.TIPLIVRARE = 2 THEN ''Custodie''
            WHEN E1.TIPLIVRARE = 3 THEN ''Nesosita''
            WHEN E1.TIPLIVRARE = 4 THEN ''De ridicat''
          END,
          CASE WHEN E1.CADOU = 1 THEN ''DA'' ELSE ''NU'' END,
          E.NRBON, E.DATABON, E.VALOARE,
          E.VALOAREDISCOUNT, CM.DENUMIRE, E.TVATOTAL, E.TVADISCOUNT,
          P.DEN_PART,
          CASE WHEN I.CODIES &gt; 0 THEN I.PREFIXDOC ||I.NRDOC ||'' / '' ||TO_CHAR (I.DATADOC, ''DD.MM.YYYY'') END,
          CASE WHEN OP.CODPERS &gt; 0 THEN OP.NUME ||'' '' ||OP.PRENUME END,
          AG.OBS,
          CASE WHEN AGE.CODPERS &gt; 0 THEN AGE.NUME ||'' '' ||AGE.PRENUME END,
          E.OBS,
          CASE WHEN DEL.CODPERS &gt; 0 THEN DEL.NUME ||'' '' ||DEL.PRENUME END,
          (SELECT fnc_array_to_vc3200 (ARRAY_AGG (E2.DENUMIRE ||'':'' ||E2.VALOARE ||'' '')) FROM EMULARE2 E2 WHERE E2.CODEMULARE = E.CODEMULARE AND coalesce (E2.VALOARE,0) &lt;&gt; 0) ,
          (SELECT SUM (VALOARE) FROM EMULARE2 E2 WHERE E2.CODEMULARE = E.CODEMULARE AND E2.TIPPLATA = 0) ,
          (SELECT SUM (VALOARE) FROM EMULARE2 E2 WHERE E2.CODEMULARE = E.CODEMULARE AND E2.TIPPLATA = 1) ,
          (SELECT SUM (VALOARE) FROM EMULARE2 E2 WHERE E2.CODEMULARE = E.CODEMULARE AND E2.TIPPLATA = 2) ,
          (SELECT SUM (VALOARE) FROM EMULARE2 E2 WHERE E2.CODEMULARE = E.CODEMULARE AND E2.TIPPLATA = 3) '
            || gUserAlias || '
        FROM MAN_E1
          INNER JOIN EMULARE1   E1  ON MAN_E1.CODEMULARE1 = E1.CODEMULARE1
          INNER JOIN EMULARE    E   ON E.CODEMULARE       = E1.CODEMULARE
          LEFT JOIN NARTOBJ     O   ON O.CODOBIECT        = E1.CODOBIECT
          LEFT JOIN NUM1        UM1 ON UM1.CODUM1         = E1.UMSEC
          LEFT JOIN IOART       IOA ON IOA.CODIOART       = E1.CODIOART
          LEFT JOIN NGEST       G   ON G.CODGEST          = E1.CODGEST
          LEFT JOIN NCONT       S   ON S.CODCONT          = E1.CONTSERV
          LEFT JOIN COMANDA1    C1  ON C1.CODCOMANDA1     = E1.CODCOMANDA1
          LEFT JOIN COMANDA     C   ON C.CODCOMANDA       = C1.CODCOMANDA
          LEFT JOIN NCASEMARCAT CM  ON CM.CODCASEMARCAT   = E.CODCASAMARCAT
          LEFT JOIN NPART       P   ON P.CODPART          = E.CODPART
          LEFT JOIN IESIRI      I   ON I.CODIES           = E.CODMONETAR
          LEFT JOIN NPERS       OP  ON OP.CODPERS         = E.CODPERS
          LEFT JOIN NAGENDA     AG  ON AG.CODAGENDA       = E.CODLOCATIE
          LEFT JOIN NPERS       AGE ON AGE.CODPERS        = E.CODAGENT
          LEFT JOIN NPERS       DEL ON DEL.CODPERS        = E.DELEGAT '
  || gSuplJoins
  || ' ORDER BY E.DATABON';
  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_sitbonretail_setgnullalias</obj_name>
  <obj_hashval>e47698199b736e1d17b08f6628c19024</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitbonretail_setgnullalias(agnullalias character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_SITBONRETAIL.gNullAlias',agNullAlias,false);
end;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitconsum_m_processlist</obj_name>
  <obj_hashval>88ff83fd6e6e76d034965d2a167fae8f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitconsum_m_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sColSerii       varchar := ', NULL serii, NULL serobs, NULL sercant';
  sJoinSerii       varchar := '';
  sFiltru         varchar := '';
  gSuplCols        VARCHAR :=   'ioart io,iesiri i,iesiri1 i1,livr l,num1 u,nartobj o,nart a,nartamb aa,comanda1 ci1,comanda ci,nirstoc nirstoc,nclasea ca,centrecost cc,'||
                               'utilaje2c ut2c,utilaje ut,utilaje2 ut2,ninterventiiauto interv,nartobj intervserv,nartobj utilajobj,NCLASEINT CLSINT';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  bAduSerii        boolean := ((current_setting('PKG_LIST_SELECTPER.bAduSerii' , true)::numeric)=1);
  vToateArt        boolean := ((current_setting('PKG_LIST_SELECTPER.vToateArt' , true)::numeric)=1);
  vToateGest      boolean := ((current_setting('PKG_LIST_SELECTPER.vToateGest', true)::numeric)=1);
BEGIN
  --Adina 08.04.2021 - alstart,alstop
  --Adina 16 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_SITCONSUM_M.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF bAduSerii THEN
    sColSerii := ',
        CASE WHEN coalesce(ns.tipserie,0) &lt;&gt; 0 THEN string_agg(s.serie ,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||'''  order by s.serie) END serii,
        CASE WHEN coalesce(ns.tipserie,0) &lt;&gt; 0 THEN string_agg(nser.obs,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||'''  order by s.serie) END serobs,
        CASE WHEN coalesce(ns.tipserie,0) &lt;&gt; 0 THEN array_agg(s.serie||''(~#''||l1.cant||''#~)'' order by s.serie) END sercant';
    sJoinSerii := '
           LEFT JOIN nirser nser ON nser.codnirser = l1.codnirser
           LEFT JOIN nserii s    on s.codserie      = nser.codserie';
  END IF;

  IF  vToateArt = FALSE THEN
    sFiltru := sFiltru || '
        AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' AND VALOARE = i1.CODOBIECT::varchar ) ';
  END IF;

  IF  vToateGest = FALSE THEN
    sFiltru := sFiltru || '
        AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = i.CODGESTPROD::varchar) ';
  END IF;

  sInsert :=
  'INSERT INTO ' || TMPNAME || ' (
    NAV_CodDoc,NAV_TipDoc,PREFIXDOC,NRDOC,DATADOC,DOCIESIRE,
    GEST_PROD,GEST_SURSA, DENUMIRE,PRODUS,CONT,CHELTUIELI,
    PU,CANT,UM,VALOARE, CANTUM1, CANTUM2, UM1, UM2,
    PERS, MASINA, TIPRETETA,
    NRCI, DATACI,
    PRETACHIZ, VALACHIZ, NRNP, UTILAJ, INTERVENTIE ' || gUserFields || ' )
  WITH lg As (
    SELECT
      i.codies, i1.codies1, l.codlivr, l1.umsec, coalesce(coalesce(lv.gest, n.gest),0) gest, coalesce(ns.codlocatie,0) codlocatie,
      (SELECT xx.CodIoart1 FROM ioart1 xx WHERE xx.codioart = coalesce(lv.codioart,ns.codioart) AND (i.an * 12 + i.luna) BETWEEN xx.ALStart and xx.ALStop) codioart1,
      ns.furn, ns.codgestprod gestfurn, sum(l1.cant) cant, sum(l1.cantum1) cantum1, sum(l1.cantum2) cantum2, ns.d1, ns.d2, ns.d3, ns.codnirstoc, coalesce(l1.codnirser,0) codnirser,
      coalesce(lv.pretachiz, coalesce(ns.pret,0) - coalesce(ns.adaos,0)) pretachiz, sum(l1.cant * coalesce(lv.pretachiz, coalesce(ns.pret,0) - coalesce(ns.adaos,0))) valachiz, I1.CODCMDINT1 ' || sColSerii || '
    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 COMANDA1 C1   ON I1.CODCMDINT1 = C1.CODCOMANDA1
      INNER JOIN COMANDA  C   ON C1.CODCOMANDA = C.CODCOMANDA
      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' || sJoinSerii || '
    WHERE i.tipdoc = 24 AND (l.operat = 1) AND (l.anulat = 0) AND C.TIPTRANZACTIE = 1 AND C.OPERAT = 1 AND C.ANULAT = 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('i',NULL,NULL,NULL),'') || '
      AND l.datalivr BETWEEN TO_DATE(''' || coalesce(To_Char(PKG_LIST_SELECTPER_DataIni(),'dd.mm.yyyy'),'') || ''',''DD/MM/YYYY'') AND TO_DATE(''' || coalesce(To_Char(PKG_LIST_SELECTPER_DataFin(),'dd.mm.yyyy'),'') || ''',''DD/MM/YYYY'')' || sFiltru || '
    GROUP BY
      i.codies, i.an, i.luna, i1.codies1, l.codlivr, l1.umsec, SIGN(l1.cant), ns.codnirstoc,l1.codnirser, ns.pret, ns.adaos, lv.pretachiz,
      lv.codioart, lv.gest, n.gest, ns.codlocatie, ns.codioart, ns.furn, ns.codgestprod, ns.tipserie, ns.d1, ns.d2, ns.d3, i1.codcmdint1
  )
  SELECT
    i.codies, i.tipdoc, i.prefixdoc, i.nrdoc, i.datadoc, i.prefixdoc||''/''||i.nrdoc||''/''||to_char(i.datadoc,''dd.mm.yyyy'') dociesire,
    gp.den_gest, gs.den_gest, o.denumire, oc.denumire, c.simbol,cch.simbol,
    i1.pu*u.paritate, lg.cant/u.paritate, u.den_um1, i1.pu*lg.cant, lg.cantum1, lg.cantum2, u1.den_um, u2.den_um,
    pers.nume||'' ''||pers.prenume, auto.nrinreg, (case pc.tipreteta when 1 then ''Agregare'' when 2 then ''Dezagregare'' end),
    ci.nrdoc, ci.datadoc,
    lg.PretAchiz, lg.ValAchiz, nr_np.nrdocs, utilajobj.denumire, intervserv.denumire ' || gUserAlias || '
  FROM lg
    LEFT JOIN iesiri      i     ON i.codies         = lg.codies
    LEFT JOIN livr        l     ON l.codlivr        = lg.codlivr
    LEFT JOIN iesiri1     i1     ON i1.codies1       = lg.codies1
    LEFT JOIN ioart1      io1   ON io1.codioart1    = lg.codioart1
    LEFT JOIN ioart       io     ON io1.codioart     = io.codioart
    LEFT JOIN ncont       c     ON c.codcont        = io1.cont
    LEFT JOIN ncont       cch   ON cch.codcont      = io1.cheltuieli
    LEFT JOIN ngest       gp     ON gp.codgest       = i.codgestprod
    LEFT JOIN ngest       gs     ON gs.codgest       = lg.gest
    LEFT JOIN nartobj     o     ON o.codobiect      = i1.codobiect
    LEFT JOIN nart        a     ON a.codarticol     = o.codarticol
    LEFT JOIN num1        u     ON u.codum1         = lg.umsec
    LEFT JOIN num         u1     ON u1.codum         = a.um1
    LEFT JOIN num         u2     ON u2.codum         = a.um2
    LEFT JOIN npers       pers   ON pers.codpers     = i.codpers
    LEFT JOIN nparcaut    auto   ON auto.codnparcaut = i.codauto
    LEFT JOIN nartamb     aa     ON aa.codobiect     = i1.codobiect AND aa.umsec = i1.umsec
    LEFT JOIN iesprodlink ipl   ON ipl.codies1      = lg.codies1
    LEFT JOIN cmdprodmat  cp     ON cp.codcmdprodmat = ipl.codcmdprodmat
    LEFT JOIN cmdprodmat  cp2   ON cp2.codcomanda1  = cp.codcomanda1 AND cp2.tip = 0
    LEFT JOIN comanda1    c1     ON c1.codcomanda1   = cp.codcomanda1
    LEFT JOIN prodcomp    pc     ON pc.codprodcomp   = c1.codreteta
    LEFT JOIN nartobj     oc     ON oc.codobiect     = cp2.codobiect
    LEFT JOIN (select
                 string_agg(i.nrdoc::varchar,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||'''  order by i.nrdoc) nrdocs,
                 i1.codcmdint1,
                 i1.codobiect
               from intrari1 i1
                    inner join intrari i on i1.codintr = i.codintr
               where coalesce(i.anulat,0) = 0 and i.operat = 1 and i.tipdoc = 7
               group by i1.codcmdint1, i1.codobiect
              ) NR_NP                     on nr_np.codcmdint1          = lg.codcmdint1 and nr_np.codobiect = oc.codobiect
    LEFT JOIN comanda1         ci1         ON ci1.codcomanda1           = i1.codcmdint1
    LEFT JOIN comanda          ci         ON ci.codcomanda             = ci1.codcomanda
    left join utilaje2c        ut2c       on ut2c.codcomanda1          = ci1.codcomanda1
    left join utilaje          ut         on ut2c.codutilaj            = ut.codutilaj
    left join utilaje2         ut2         on ut2.codutilaj2            = ut2c.codutilaj2
    left join ninterventiiauto interv     on interv.CODINTERVENTIIAUTO = ut2.interventie
    left join nartobj          intervserv on intervserv.codobiect      = interv.serviciu
    left join nartobj          utilajobj   on utilajobj.codobiect       = ut.codobiect
    LEFT JOIN nirstoc                     ON lg.codnirstoc             = nirstoc.codnirstoc
    LEFT JOIN nclasea          ca         ON ca.codclasea              = a.clasa
    LEFT JOIN NCLASEINT        CLSINT     ON INTERV.CLASA              = CLSINT.CODCLASEINT
    LEFT JOIN centrecost       cc         on i1.codcentru              = cc.codcentru' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitimob_processlist</obj_name>
  <obj_hashval>a72294f845db8f4b616b7e70cd319ea4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitimob_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;
  sUpdate1   varchar;
  sUpdate2   varchar;
  sDifReeval varchar;
  sValRamasa varchar;
  sColCurs   varchar;
  BancaSitV  numeric := 0;
  MonedaSitV numeric := 0;
  vLunaAnFin varchar := current_setting('PKG_LIST_BASE_SITIMOB.vLunaAnFin', true);
  vLunaAnIni varchar := current_setting('PKG_LIST_BASE_SITIMOB.vLunaAnIni', true);
  vOldMF     NUMERIC := current_setting('PKG_LIST_BASE_SITIMOB.vOldMF', true)::NUMERIC;
  vAllGest   NUMERIC := current_setting('PKG_LIST_BASE_SITIMOB.vAllGest', true)::NUMERIC;
  vAllIOArt  NUMERIC := current_setting('PKG_LIST_BASE_SITIMOB.vAllIOArt', true)::NUMERIC;
  vAllMF     NUMERIC := current_setting('PKG_LIST_BASE_SITIMOB.vAllMF', true)::NUMERIC;
BEGIN
  --Florin 15.05.2024 - sinc. Oracle
  --Florin 28.02.2024 - fixat 61164
  --Stef 29.01.2024
  CALL PRC_AL_CHECK('ioart1',0);

  gSuplCols := 'MIFIX1 MIFIX1, MIFIX MIFIX, NIRSTOC NS, NARTOBJ OBJ, NUM1 NUM1, IOART IO,NCONT N, MFCLASIF CLASA, NIR NIR, NGEST NG, NSUBUNIT SUB, TRANSF TRANSF, JURNAL1 J1, '||
               'MIFIX1 AMO_INI, NCLASEG  NCLG, NPERS PERS, NART ART, NCLASEA NCLA, NCLASEAS NCLAS, NPART NP_CUST, NLOCATII LOC, NPART FURN, NARTAMB AA, CENTRECOST CC, NIRSTOC1 NS1, '||
               'NIRSTOC NSO, NIR NIRO, INTRARI INTRO, IESIRI IESO, NIRSER NSER, NSERII SER';

  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_addsupltabs (gSuplCols , 'LIVR1'     , 'L1'  , 'L1.CODLIVR1 = PKG_LIST_BASE_SITIMOB_GetCodLivr1Vanz(MIFIX1.STARE, MIFIX1.CODNIRSTOC, MIFIX1.ANSTART, MIFIX1.LUNASTART)');
  call pkg_list_struct_addsupltabs (gSuplCols , 'LIVR'      , 'L'   , 'L.CODLIVR = L1.CODLIVR',NULL);
  call pkg_list_struct_addsupltabs (gSuplCols , 'IESIRI'    , 'IES' , 'IES.CODIES = L.CODIES AND IES.TIPDOC = L.TIPLIVR',NULL);

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

  IF fnc_GetValConstantaLucru ('UseRezervaReev') = '1' THEN
      sDifReeval := ',
            Round (
              CASE
                WHEN mifix1.DataReeval IS NULL         THEN 0
                WHEN Coalesce (mifix1.TipReeval,0) = 0 THEN (mifix1.Pret - Coalesce (mifix1.amo,0)) - (mifix1.PretVechi - mifix1.AmoVechi)
                WHEN mifix1.IncludRata = 1             THEN mifix1.Pret - mifix1.PretVechi + Coalesce (mifix1.amo,0) + Coalesce (j1.valoare,0)
                ELSE mifix1.Pret - mifix1.PretVechi
              END,7)
            DifReeval';
      sValRamasa := ', Round (
                CASE
                  WHEN mifix1.DataReeval IS NOT NULL AND mifix1.TipReeval  = 1 AND mifix1.IncludRata = 1 THEN ns.pret * mifix1.cant
                  ELSE ns.pret * mifix1.cant - Coalesce (mifix1.amo,0) - Coalesce (j1.valoare,0)
                END,7)
              val_ramas';
  ELSE
    sDifReeval := ', 0 DifReeval';
    sValRamasa := ', Round ( (ns.pret * mifix1.cant) - Coalesce (mifix1.amo,0) - Coalesce (j1.valoare,0) ,7) val_ramas';
  END IF;

  IF Coalesce (getAnLucru(), 0) &gt; 0 AND Coalesce (getLunaLucru(), 0) &gt; 0 THEN
    BEGIN
      SELECT (fnc_GetValConstanta ('BancaSitV',  getAnLucru(), getLunaLucru()))::NUMERIC INTO STRICT BANCASITV;
    EXCEPTION
      WHEN no_data_found THEN
        BANCASITV := 0;
      WHEN OTHERS THEN
        BANCASITV := 0;
    END;

    BEGIN
      SELECT (fnc_GetValConstanta ('MonedaSitV',  getAnLucru(), getLunaLucru()))::NUMERIC INTO STRICT MONEDASITV;
    EXCEPTION
      WHEN no_data_found THEN
        MONEDASITV := 0;
      WHEN OTHERS THEN
        MONEDASITV := 0;
    END;
  END IF;

  IF Coalesce (MonedaSitV, 0) &lt;&gt; 0 AND Coalesce (BancaSitV, 0) &lt;&gt; 0 THEN
    sColCurs := ' (SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA (NULL, '
      || coalesce (MonedaSitV::varchar,'')|| ','
      || coalesce (BancaSitV::varchar,'')
      || ',TO_CHAR(ns.dataachiz,''dd.mm.yyyy''))) CursAchiz, (select wme_result from PKG_LIST_BASE_UTILS_GETCURSREFERINTA (null, '
      || coalesce (MonedaSitV::varchar,'')|| ','
      || coalesce (BancaSitV::varchar,'')
      || ',to_char(nir.datanir,''dd.mm.yyyy''))) CursModifPret,';
  ELSE
    sColCurs := ' 1 CursAchiz, 1 CursModifPret,';
  END IF;

  sInsert :=
  'INSERT INTO '|| TMPNAME ||'(
    CODMIFIX,TIMP_RAMAS,
    AMO_CURENT,
    AMO_PREC,AMO_TOTAL,GRADU,PRET_AMO,
    VAL_RAMAS,
    CODNIRSTOC,DENMIFIX,CANT,NRINVENTAR,DEN_UM1,DEN_IOART,CONT,
    DENCLASA,SIMBOLCLASA,DURATAN,
    TIPAMO,
    DEN_GEST,DATAACHIZ,DEN_SUBUNIT,ANLUNAINTR,
    DEN_CLASEG,RESPONSABIL, DEN_CLASEA, CODINTERN, CODEXTERN,
    NEUTILPREC, STARE,
    SERIE,LOCATIE,PART_CUSTODIE,
    FURNIZOR,OBSMIFIX,AMOINCEPUT,
    AMOCUMUL,
    AMO_CURENTF,
    AMOF, TIMP_RAMASF,
    AMOFCUMUL,
    AMO_CURENTG,
    AMOG, TIMP_RAMASG,
    AMOGCUMUL,
    CentruCost, PretInc,
    RezNoua, SoldRez, CReeval, VReeval, Val105,
    Reeval, TipReeval, InclRata,
    Rezerva,
    DifReeval,
    PretInitial,
    LUNA, AN,
    INFOMFIMB,
    CursAchiz,
    CursModifPret,
    DataModifPret,
    NrOrd,
    NrMax'||gUserFields||')
  SELECT
    mifix1.codmifix, mifix1.durataf AS timp_ramas,
    CASE when mifix1.datareeval is not null and mifix1.Includrata = 1 then 0 else Coalesce(j1.valoare,0) END amo_curent,
    CASE WHEN mifix1.TipReeval = 1 THEN 0 ELSE (select wme_result from PKG_INCHIDERI_GET_AMO_MIFIX(null, mifix1.codmifix, mifix1.anstart, mifix1.lunastart)) END amo_prec,
    0 amo_total, mifix1.gradu, ns.pret'||
    sValRamasa||',
    mifix1.codnirstoc, obj.denumire DENMIFIX, mifix1.cant, mifix.nrinventar, num1.den_um1, io.den_ioart, n.simbol CONT,
    clasa.denumire DENCLASA, clasa.simbol SIMBOLCLASA ,mifix1.duratan,
    CASE
      WHEN mifix1.tipamo = 1                        THEN ''Liniara''
      WHEN mifix1.tipamo = 2 AND mifix.tip = ''MF'' THEN ''Accelerata''
      WHEN mifix1.tipamo = 2                        THEN ''100% la punerea in functiune''
      WHEN mifix1.tipamo = 3 AND mifix.tip = ''MF'' THEN ''Degresiva 1''
      WHEN mifix1.tipamo = 3                        THEN ''50% la punerea in functiune''
      WHEN mifix1.tipamo = 4 AND mifix.tip = ''MF'' THEN ''Degresiva 2''
    END TipAmo,
    ng.den_gest, ns.dataachiz, SUB.DEN_SUBUNIT, MIFIX.LUNAINTRARE||''/''||MIFIX.ANINTRARE ANLUNAINTR,
    NCLG.DEN_CLASEG, PERS.NUME||'' ''||PERS.PRENUME RESPONSABIL, NCLA.DEN_CLASEA, OBJ.CODINTERN, OBJ.CODEXTERN,
    mifix1.NEUTIL NEUTILPREC,
    CASE mifix1.stare
      WHEN 1 THEN ''In curs de amortizare''
      WHEN 2 THEN ''Trecut in conservare''
      WHEN 3 THEN ''Casat in luna curenta''
      WHEN 4 THEN ''Vandut in luna curenta''
      WHEN 5 THEN ''Investitie in curs''
      WHEN 6 THEN ''Cedat ca aport la capital''
      WHEN 7 THEN ''Transferat ca marfa''
    END STARE,
    SER.SERIE,LOC.DENUMIRE LOCATIE, NP_CUST.DEN_PART PART_CUSTODIE, FURN.DEN_PART FURNIZOR, mifix.obs obsmifix, Coalesce(AMO_INI.AMO,0) AMOINCEPUT,
    Round(Coalesce(MIFIX1.AMO,0) - Coalesce(AMO_INI.AMO,0) + Coalesce(j1.valoare,0),7) amocumul,
    Round (CASE when mifix1.stare IN (2,3,4) THEN 0 ELSE (SELECT wme_result FROM pkg_inchideri_AMORTIZARELUNARA_F(null,mifix.codmifix,mifix1.anstart,mifix1.lunastart)) END,7) AS amo_curentf,
    mifix1.amof, mifix1.durataff TIMP_RAMASF,
    Round(Coalesce(MIFIX1.AMOF,0) - Coalesce(AMO_INI.AMOF,0) + CASE WHEN mifix1.stare IN (2,3,4) THEN 0 ELSE (SELECT wme_result FROM pkg_inchideri_AMORTIZARELUNARA_F(null,mifix.codmifix,mifix1.anstart,mifix1.lunastart)) END,7) AS amofcumul,
    Round(CASE WHEN mifix1.stare IN (2,3,4) THEN 0 ELSE (SELECT wme_result FROM pkg_inchideri_AMORTIZARELUNARA_G (null,mifix.codmifix,mifix1.anstart,mifix1.lunastart)) END,7) amo_curentg,
    mifix1.amog, mifix1.duratafg TIMP_RAMASG,
    Round(Coalesce(MIFIX1.AMOG,0) - Coalesce(AMO_INI.AMOG,0) + CASE WHEN mifix1.stare IN (2,3,4) THEN 0 ELSE (SELECT wme_result FROM pkg_inchideri_AMORTIZARELUNARA_G (null,mifix.codmifix,mifix1.anstart,mifix1.lunastart)) END,7) AS amogcumul,
    cc.denumire CentruCost, CASE WHEN Coalesce(mifix1.PretVechi,0) &lt;&gt; 0 THEN mifix1.PretVechi WHEN Coalesce(nso.Pret,0) = 0 THEN ns.Pret - Coalesce(ns.Adaos,0) ELSE nso.Pret - Coalesce(nso.Adaos,0) END AS PretInc,
    0 RezNoua, 0 SoldRez, 0 CReeval, 0 VReeval, 0 Val105,
    CASE WHEN mifix1.DataReeval IS NULL THEN ''NU'' ELSE ''DA'' END Reeval,
    CASE WHEN mifix1.DataReeval IS NULL THEN NULL WHEN mifix1.TipReeval = 1 THEN ''pe valori nete'' ELSE ''pe valori brute'' END TipReeval,
    CASE WHEN mifix1.DataReeval IS NULL THEN NULL WHEN mifix1.IncludRata = 1 THEN ''dupa amortizarea curenta'' ELSE ''inainte de amortizarea curenta'' END InclRata,
    coalesce(mifix1.Rezerva, 0)'||
    sDifReeval||',
    CASE WHEN Coalesce(nso.pret,0) = 0 THEN ns.pret ELSE nso.pret END PretInitial,
    mifix1.lunastart, mifix1.anstart,
    Coalesce(PKG_MIFIX_GetINFOMFIMB(mifix.codmifiximb), mifix.nrinventar || '' '' || obj.denumire) INFOMFIMB,'||
    sColCurs||'
    nir.datanir DataModifPret,
    Row_Number() OVER (PARTITION BY mifix.codmifix ORDER BY mifix1.anstart*12+mifix1.lunastart, mifix1.codmifix1) NrOrd,
    Count(1) OVER (PARTITION BY mifix.codmifix) NrMax'||gUserAlias||'
  FROM mifix1
    INNER JOIN mifix              ON mifix1.codmifix   = mifix.codmifix
    INNER JOIN nirstoc    ns      ON mifix1.codnirstoc = ns.codnirstoc
    INNER JOIN nartobj    obj     ON obj.codobiect     = ns.codobiect
    INNER JOIN num1               ON num1.codum1       = ns.umsec
    INNER JOIN ioart      io      ON ns.codioart       = io.codioart
    INNER JOIN ioart1     io1     ON io.codioart       = io1.codioart    AND (mifix1.anstart * 12 + mifix1.lunastart) BETWEEN io1.ALStart and io1.ALStop
    INNER JOIN ncont      n       ON n.codcont         = io1.cont
    INNER JOIN mfclasif   clasa   ON clasa.codclasif   = mifix1.codclasif
    INNER JOIN nir                ON nir.codnir        = ns.codnir
    INNER JOIN ngest      ng      ON ng.codgest        = nir.gest
    INNER JOIN nsubunit   sub     ON sub.codsubunit    = ng.codsubunit
    LEFT  JOIN transf             ON transf.codtransf  = nir.codtransf
    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
    LEFT  JOIN mifix1     amo_ini ON amo_ini.codmifix  = mifix1.codmifix AND amo_ini.anstart = mifix1.anstart AND amo_ini.lunastart = 1
    LEFT  JOIN nclaseg    nclg    ON nclg.codclaseg    = ng.codclasa
    LEFT  JOIN npers      pers    ON pers.codpers      = mifix1.codpers
    LEFT  JOIN nart       art     ON art.codarticol    = obj.codarticol
    LEFT  JOIN nclasea    ncla    ON ncla.codclasea    = art.clasa
    LEFT  JOIN nclaseas   nclas   ON nclas.codclaseas  = art.clasastatist
    LEFT  JOIN npart      np_cust ON np_cust.codpart   = mifix1.codpart
    LEFT  JOIN nlocatii   loc     ON loc.codlocatie    = Coalesce(ns.codlocatie,0)
    LEFT  JOIN npart      furn    ON furn.codpart      = ns.furn
    LEFT  JOIN nartamb    aa      ON aa.codobiect      = ns.codobiect    AND aa.umsec = ns.umsec
    LEFT  JOIN centrecost cc      ON cc.codcentru      = Coalesce(mifix1.codcentru,0)
    LEFT  JOIN nirstoc1   ns1     on ns1.codnirstoc    = ns.codnirstoc
    LEFT  JOIN nirstoc    nso     on nso.codnirstoc    = ns1.codnirstocorig
    LEFT  JOIN nir        niro    on nso.codnir        = niro.codnir
    LEFT  JOIN intrari    intro   on intro.codintr     = niro.codintr
    LEFT  JOIN iesiri     ieso    on ieso.codies       = niro.codies
    LEFT  JOIN nirser     nser    ON nser.codnirser    = mifix1.codnirser
    LEFT  JOIN nserii     ser     ON ser.codserie      = nser.codserie '||
    gSuplJoins||'
  WHERE mifix1.anstart * 12 + mifix1.lunastart &lt;= '||vLunaAnFin||
    PKG_LIST_BASE_UTILS_COND_SUBUNIT ('NG', 'CODSUBUNIT')||' '||
  CASE
    WHEN vOldMF = 1 THEN '
    AND (mifix1.stare IN (3,4) OR mifix1.anstart * 12 + mifix1.lunastart &gt;= '||vLunaAnIni||')'
    ELSE '
    AND mifix1.anstart * 12 + mifix1.lunastart &gt;= '||vLunaAnIni
  END||
  CASE
    WHEN vAllGest = 0 THEN '
    and exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = ''CODGEST'' and tmp.valoare = nir.gest::varchar)'
    ELSE ''
  END||
  CASE
    WHEN vAllIOArt = 0 THEN '
    and exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = ''CODIOART'' and tmp.valoare = ns.codioart::varchar)'
    ELSE ''
  END||
  CASE
    WHEN vAllMF = 0 THEN '
    and exists (select tmp.valoare from tmp_manevra_liste tmp where tmp.filtru = ''CODMIFIX'' and tmp.valoare = mifix.codmifix::varchar)'
    ELSE ''
  END;

  sUpdate1 :=
  'UPDATE '|| TMPNAME ||'
  SET SoldIni   = CASE WHEN NrOrd = 1     THEN AMO_PREC   END,
      SoldFin   = CASE WHEN NrOrd = NrMax THEN VAL_RAMAS  END,
      AMO_TOTAL = Round(AMO_CURENT + AMO_PREC,7)';

  sUpdate2 :=
  'UPDATE '|| TMPNAME ||'
  SET RezNoua  = Rezerva + coalesce(DifReeval, 0),
      SoldRez  = CASE WHEN Rezerva + DifReeval &lt; 0 THEN 0 ELSE Rezerva + DifReeval END,
      VReeval  = CASE
                    WHEN Rezerva + DifReeval &gt; 0 AND Rezerva &lt; 0 THEN - Rezerva
                    WHEN Rezerva + DifReeval &lt; 0 AND Rezerva &lt; 0 AND DifReeval &gt; 0 THEN DifReeval
                    ELSE 0
                  END,
      CReeval  = CASE
                    WHEN Rezerva + DifReeval &lt; 0 AND Rezerva &gt;= 0 THEN - (Rezerva + DifReeval)
                    WHEN Rezerva + DifReeval &lt; 0 AND Rezerva  &lt; 0 AND DifReeval &lt; 0 THEN - DifReeval
                    ELSE 0
                  END,
      Val105   = DifReeval -
                  CASE --VReeval
                    WHEN Rezerva + DifReeval &gt; 0 AND Rezerva &lt; 0 THEN - Rezerva
                    WHEN Rezerva + DifReeval &lt; 0 AND Rezerva &lt; 0 AND DifReeval &gt; 0 THEN DifReeval
                    ELSE 0
                  END +
                  CASE --CReeval
                    WHEN Rezerva + DifReeval &lt; 0 AND Rezerva &gt;= 0 THEN - (Rezerva + DifReeval)
                    WHEN Rezerva + DifReeval &lt; 0 AND Rezerva  &lt; 0 AND DifReeval &lt; 0 THEN - DifReeval
                    ELSE 0
                  END
  WHERE Reeval IS NOT NULL';

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitiniesluna_processlist</obj_name>
  <obj_hashval>9049e02dd9afe0407220f356cb3ff8f6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitiniesluna_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sJoinCLS    varchar;
  sTipDocIes  varchar;
  sCondGest   varchar;
  sCondAL     varchar;
  gSuplCols   varchar := 'NARTOBJ O, NART A, NCLASEA CA, NCLASEAS CAS, INTRARI INTR, IESIRI IES, NPART FURN, NPART CLI, NPART PROD, NTVA NTVA, NTVA1 NTVA1, NAGENDA SLIVR, NLOCALIT LOClivr, NJUDET JUDlivr, NCLASEP CF, NCLASEP CC, NCLASEP CP, IESIRI1 IES1,INTRARI1 II1,DVI1 DVI1,TRANSF1 TT1';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  sFiltruClasa VARCHAR;
  sFiltruGest  VARCHAR;
  sCondGest1   VARCHAR(1000);
  sCondGest2   VARCHAR(1000);
  sCondGestN   VARCHAR(1000);
    sFiltru    VARCHAR(500) := ' WHERE 1 = 1 ';
BEGIN
  --Florin 06.10.2025 - fixat 66864
  --Florin 22.08.2025 - fixat 66466
  --Florin 18.08.2025 - fixat 66412
  --Florin 18.02.2025 - sinc. Oracle
  --Florin 05.11.2024 - sinc. Oracle
  --Florin 07.08.2024 - sinc. Oracle
  --Florin 04.03.2024 - sinc. Oracle
  --Florin 20.10.2023 - fixat 59764
  --Florin 10.10.2023 - sinc. Oracle (06.10.2023)
  --Florin 25.09.2023 - sinc. Oracle
  --Florin 29.08.2023 - sinc. Oracle
  --Florin 21.04.2024 - fixat 58012
  --Florin 11.04.2023 - sinc. Oracle (10.04.2023)
  --Florin 23.03.2023 - sinc. Oracle (22.03.2023)
  --Florin 22.03.2023 - sinc. Oracle (21.03.2023)
  --Florin 20.12.2022 - sinc. Oracle
  --Florin 07.11.2022 - fixat 56169/56229
  --Florin 31.10.2022 - sinc. Oracle (28.10.2022)
  --Florin 28.10.2022 - sinc. Oracle
  --Florin 25.10.2022 - sinc. Oracle
  --Florin 09.06.2022 - fixat 54564
  --Stef   10.05.2022
  --Florin 01.11.2021 - fixat 51841, 51849
  --Florin 14.10.2021 - sinc. Oracle (51626)
  --Florin 10.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_addsupltabs(gSuplCols, 'TMP_MEDEX1_LST', 'MED1', 'MED1.CODCIM    = O.CODCNAS',NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_SITINIESLUNA.gSuplCols',gSuplCols,false);

  IF InStr(gSuplJoins, 'TMP_MEDEX1_LST') &gt; 0 THEN
    PERFORM pkg_list_base_utils_UMPLE_TMP_MEDEX1_LST();
  END IF;

  IF current_setting('PKG_LIST_SELECTLUNAAN.vAllX', TRUE)::NUMERIC = 0 THEN
    sJoinCLS := '
        INNER JOIN NARTOBJ O ON O.CODOBIECT  = NS.CODOBIECT
        INNER JOIN NART    A ON A.CODARTICOl = O.CODARTICOL AND A.CLASA::VARCHAR IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODCLASEA'')';
    sFiltruClasa := 'A.CLASA::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODCLASEA'')';
  END IF;

  sCondGest := '';
  sCondGest1 := '';
  sCondGest2 := '';
  sCondGestN := '';
  sFiltruGest := '';
  IF current_setting('PKG_LIST_SELECTLUNAAN.vAllY', TRUE)::NUMERIC = 1 THEN
    sCondGest := sCondGest||' AND NOT N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
    sCondGestN := sCondGestN||' AND NOT NN.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
    sCondGest1 := sCondGest1||' AND NOT NL.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
    sFiltruGest := sFiltruGest||' NOT J.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'')';
  END IF;

  sTipDocIes := '16, 19, 20, 21, 24';
  IF current_setting('PKG_LIST_SELECTLUNAAN.vOpt1', TRUE)::NUMERIC = 1 THEN
    sTipDocIes := coalesce(sTipDocIes,'') || ', 14, 15';
  END IF;

  IF current_setting('PKG_LIST_SELECTLUNAAN.vLunaStart', TRUE)::NUMERIC = current_setting('PKG_LIST_SELECTLUNAAN.vLunaStop', TRUE)::NUMERIC
  THEN sCondAL := ' = ' || coalesce(current_setting('PKG_LIST_SELECTLUNAAN.vLunaStart', TRUE)::NUMERIC, 0);
  ELSE sCondAL := ' BETWEEN ' || coalesce(current_setting('PKG_LIST_SELECTLUNAAN.vLunaStart', TRUE)::NUMERIC, 0) || ' AND ' || coalesce(current_setting('PKG_LIST_SELECTLUNAAN.vLunaStop', TRUE)::NUMERIC, 0);
  END IF;

  IF sFiltruClasa IS NOT NULL AND sFiltruClasa &lt;&gt; ''
  THEN IF sFiltruGest IS NOT null and sFiltruGest &lt;&gt; ''
    THEN sFiltru := ' AND ' || sFiltruClasa || ' AND ' || sFiltruGest;
    ELSE sFiltru := ' AND ' || sFiltruClasa;
    END IF;
  ELSE IF sFiltruGest IS NOT null and sFiltruGest &lt;&gt; ''
    THEN sFiltru := ' AND ' || sFiltruGest;
    END IF;
  END IF;

  sInsert := 'INSERT INTO ' || coalesce(TMPNAME,'') || '(
    DENUMIRE, PRODUCATOR, SERIE,
    FURNIZOR, INTRPREFIX, INTRNRDOC, INTRDATADOC,
    STOCINIT,
    CANTINT,
    CLIENT, CANTIES, IESPREFIX, IESNRDOC, IESDATADOC,
    STOC, ORDINE ' || gUserFields || ')
  WITH
  OINT AS (
    SELECT
      CODOBIECT, CODNIRSTOC, CODIES, CODINTR, DATA AS DATADOC, FURN, SERIE, GEST, TIPDOC, STOCINIT, CANTINT, 0 CANTIES, 0 ORD, CODINTR1, CODIES1, CODDVI1, CODTRANSF1
    FROM (
      SELECT
        NS.CODOBIECT, COALESCE(NSO.FURN,0) FURN, SER.SERIE, NSO.CODNIRSTOC, Last_Day(To_Date(NL.AN||''.''||NL.LUNA,''yyyy.mm''))+1 AS DATA, 0 CODINTR, 0 CODIES,
        SUM(CASE WHEN Coalesce(NE.CODNIRSER, 0) = 0 THEN NL.REST ELSE NE.REST END) STOCINIT, 0 CANTINT, N.GEST AS GEST, N.TIPNIR TIPDOC, II1.CODINTR1, 0 CODIES1,
        DVI1.CODDVI1, TT1.CODTRANSF1
      FROM NIRLUNA NL
        INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = NL.CODNIRSTOC
        INNER JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = NS.CODNIRSTOC
        INNER JOIN NIRSTOC NSO ON NSO.CODNIRSTOC = NS1.CODNIRSTOCORIG'||
        coalesce(sJoinCLS,'') || '
        INNER JOIN NIR N ON N.CODNIR = NSO.CODNIR
        INNER JOIN NIR NN ON NN.CODNIR = NS.CODNIR
        INNER JOIN NGEST G ON NN.GEST = G.CODGEST
        LEFT JOIN INTRARI R ON R.CODINTR = N.CODINTR AND R.TIPDOC = N.TIPNIR
        LEFT JOIN NIRSERLUNA NE ON NL.CODNIRSTOC = NE.CODNIRSTOC AND NL.AN = NE.AN AND NL.LUNA = NE.LUNA
        LEFT JOIN NIRSER NSE ON NSE.CODNIRSER = NE.CODNIRSER
        LEFT JOIN NSERII SER ON SER.CODSERIE = NSE.CODSERIE
        LEFT JOIN INTRARI1 II1 ON II1.CODINTR1 = NS.CODINTR1
        LEFT JOIN TRANSF1 TT1 ON NS.CODTRANSF1 = TT1.CODTRANSF1
        LEFT JOIN DVI1 DVI1 ON NS.CODDVI1 = DVI1.CODDVI1
      WHERE NL.AN*12+NL.LUNA+1 = ' || coalesce(current_setting('PKG_LIST_SELECTLUNAAN.vLunaStart', TRUE)::NUMERIC, 0) || coalesce(sCondGest,'') ||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT')||' AND NL.REST &gt; 0
      GROUP BY NS.CODOBIECT, COALESCE(NSO.FURN,0), SER.SERIE, NL.AN, NL.LUNA, N.GEST, N.TIPNIR, NSO.CODNIRSTOC,
               II1.CODINTR1, DVI1.CODDVI1, TT1.CODTRANSF1
     UNION ALL
      SELECT
        NS.CODOBIECT, COALESCE(NSO.FURN,0) FURN, SER.SERIE, NSO.CODNIRSTOC, I.DATADOC AS DATA, I.CODINTR, 0 CODIES,
        0 STOCINIT, CASE WHEN Coalesce(NSE.CODNIRSER, 0) = 0 THEN NS.CANTNIR ELSE NSE.CANTNIR END CANTINT, NN.GEST AS GEST, NN.TIPNIR TIPDOC,
        II1.CODINTR1, 0 CODIES1, DVI1.CODDVI1, TT1.CODTRANSF1
      FROM INTRARI I
        INNER JOIN NIR N ON N.CODINTR = I.CODINTR AND N.TIPNIR = I.TIPDOC
        INNER JOIN NIRSTOC NS ON NS.CODNIR = N.CODNIR
        INNER JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = NS.CODNIRSTOC
        INNER JOIN NIRSTOC NSO ON NSO.CODNIRSTOC = NS1.CODNIRSTOCORIG
        INNER JOIN NIR NN ON NN.CODNIR = NSO.CODNIR
        INNER JOIN NGEST G ON N.GEST = G.CODGEST'||
        COALESCE(sJoinCLS, '') ||'
        LEFT JOIN DVI1 D1 ON D1.CODDVI1 = NS.CODDVI1
        LEFT JOIN INTRARI1 I1 ON I1.CODINTR1 = Coalesce(NS.CODINTR1,D1.CODINTR1,0) AND I1.CODINTR = I.CODINTR
        LEFT JOIN NIRSER NSE ON NS.CODNIRSTOC = NSE.CODNIRSTOC
        LEFT JOIN NSERII SER ON SER.CODSERIE = NSE.CODSERIE
        LEFT JOIN INTRARI1 II1 ON II1.CODINTR1 = NS.CODINTR1
        LEFT JOIN TRANSF1 TT1 ON NS.CODTRANSF1 = TT1.CODTRANSF1
        LEFT JOIN DVI1 DVI1 ON NS.CODDVI1 = DVI1.CODDVI1
      WHERE I.TIPDOC IN (1, 2, 3, 4, 5, 7) AND I.ANULAT = 0 AND I.OPERAT = 1
        AND I1.CODINTR1 IS NOT NULL
        AND I.AN*12+I.LUNA'|| coalesce(sCondAL,'') ||  coalesce(sCondGest,'') || PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT');
  IF  current_setting('PKG_LIST_SELECTLUNAAN.vOpt1', TRUE)::NUMERIC = 1 THEN
    sInsert := coalesce(sInsert,'') || '
      UNION ALL
     SELECT
        NS.CODOBIECT, COALESCE(NSO.FURN,0) FURN, SER.SERIE, NSO.CODNIRSTOC, I.DATADOC AS DATA, I.CODINTR, IES.CODIES,
        0 STOCINIT, CASE WHEN Coalesce(NSE.CODNIRSER, 0) = 0 THEN IES1.CANT ELSE IES1.CANT END CANTINT, NN.GEST AS GEST, NN.TIPNIR TIPDOC, 0 CODINTR1, IES1.CODIES1,
        0 CODDVI1, 0 CODTRANSF1
       FROM INTRARI I
        INNER JOIN NIR N ON N.CODINTR = I.CODINTR AND N.TIPNIR = 15 AND N.CODIES &gt; 0
        INNER JOIN IESIRI IES ON N.CODIES = IES.CODIES
        INNER JOIN NIRSTOC NS ON NS.CODNIR = N.CODNIR
        INNER JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = NS.CODNIRSTOC
        INNER JOIN NIRSTOC NSO ON NSO.CODNIRSTOC = NS1.CODNIRSTOCORIG
        INNER JOIN NIR NN ON NN.CODNIR = NSO.CODNIR
        INNER JOIN LIVR1 L1 ON L1.CODNIRSTOC = NS.CODNIRSTOC
        INNER JOIN INTRARI1 I1 ON I1.CODINTR1 = NS.CODINTR1 AND I1.CODINTR = I.CODINTR
        INNER JOIN IESIRI1 IES1 ON IES1.CODIES = IES.CODIES AND IES1.CODIES1 = L1.CODIES1
        INNER JOIN NGEST G ON N.GEST = G.CODGEST'||
        COALESCE(sJoinCLS, '')||'
        LEFT JOIN DVI1 D1 ON D1.CODDVI1 = NS.CODDVI1
        LEFT JOIN NIRSER NSE ON NS.CODNIRSTOC = NSE.CODNIRSTOC
        LEFT JOIN NSERII SER ON SER.CODSERIE = NSE.CODSERIE
      WHERE N.TIPNIR = 15 AND I.ANULAT = 0 AND I.OPERAT = 1
        AND I1.CODINTR1 IS NOT NULL
        AND IES.AN*12+IES.LUNA'|| COALESCE(sCondAL, '') || COALESCE(sCondGest, '') ||PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT');
  END IF;
  if current_setting('PKG_LIST_SELECTLUNAAN.vOpt2', TRUE)::NUMERIC = 1 THEN
    sInsert := sInsert||'
     UNION ALL
     SELECT
        NS.CODOBIECT, COALESCE(NSO.FURN,0) FURN, SER.SERIE, NSO.CODNIRSTOC, T.DATADOC AS DATA,
        T.CODTRANSF CODINTR, 0 CODIES,
        0 STOCINIT, CASE WHEN Coalesce(NSE.CODNIRSER, 0) = 0 THEN T1.CANT ELSE NSE.CANTNIR END CANTINT, NO.GEST AS GEST, T.TIPDOC,
        0 CODINTR1, 0 CODIES1, 0 CODDVI1, T1.CODTRANSF1
     FROM TRANSF T
        INNER JOIN NIR N ON N.CODTRANSF = T.CODTRANSF
        INNER JOIN TRANSF1 T1 ON T1.CODTRANSF = T.CODTRANSF
        INNER JOIN NIRSTOC NS ON NS.CODNIR = N.CODNIR AND NS.CODTRANSF1 = T1.CODTRANSF1
        INNER JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = NS.CODNIRSTOC
        INNER JOIN NIRSTOC NSO ON NSO.CODNIRSTOC = NS1.CODNIRSTOCORIG
        INNER JOIN NIR NO ON NO.CODNIR = NSO.CODNIR
        INNER JOIN NGEST    G   ON G.CODGEST = N.GEST
        LEFT  JOIN INTRARI  R   ON R.CODINTR = NO.CODINTR AND R.TIPDOC = NO.TIPNIR
        LEFT  JOIN TRANSF  RT   ON RT.CODTRANSF = NO.CODTRANSF AND RT.TIPDOC = NO.TIPNIR'||
        COALESCE(sJoinCLS, '') ||'
        LEFT JOIN NIRSER NSE ON NS.CODNIRSTOC = NSE.CODNIRSTOC
        LEFT JOIN NSERII SER ON SER.CODSERIE = NSE.CODSERIE
      WHERE N.TIPNIR = 12 AND T.ANULAT = 0 AND T.OPERAT = 1
        AND T1.CODTRANSF1 IS NOT NULL
        AND T.AN*12+T.LUNA'|| COALESCE(sCondAL, '') || COALESCE(sCondGest, '') ||PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT');
  end if;
  sInsert := coalesce(sInsert,'') || '
    UNION ALL
      SELECT
        NS.CODOBIECT, COALESCE(NSO.FURN,0) FURN, SER.SERIE, NSO.CODNIRSTOC, I.DATADOC AS DATA, I.CODINTR, 0 CODIES,
        0 STOCINIT, -L1.CANT CANTINT, NO.GEST AS GEST, NO.TIPNIR TIPDOC, I1.CODINTR1, 0 CODIES1,
        0 CODDVI1, 0 CODTRANSF1
      FROM INTRARI I
        INNER JOIN LIVR L ON L.CODINTR = I.CODINTR AND L.TIPLIVR = I.TIPDOC
        INNER JOIN LIVR1 L1 ON L1.CODLIVR = L.CODLIVR
        INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
        INNER JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = NS.CODNIRSTOC
        INNER JOIN NIRSTOC NSO ON NSO.CODNIRSTOC = NS1.CODNIRSTOCORIG
        INNER JOIN NIR NO ON NO.CODNIR = NSO.CODNIR
        INNER JOIN NIR N ON NS.CODNIR = N.CODNIR
        INNER JOIN NGEST G ON N.GEST = G.CODGEST'||
        coalesce(sJoinCLS, '')||'
        LEFT JOIN DVI1 D1 ON D1.CODDVI1 = L1.CODDVI1
        LEFT JOIN INTRARI1 I1 ON I1.CODINTR1 = Coalesce(D1.CODINTR1, L1.CODINTR1,0) AND I1.CODINTR = I.CODINTR
        LEFT JOIN NIRSER NSE ON NSE.CODNIRSER = L1.CODNIRSER
        LEFT JOIN NSERII SER ON SER.CODSERIE = NSE.CODSERIE
      WHERE I.TIPDOC IN (1, 2, 3, 4, 5, 7) AND I.ANULAT = 0 AND I.OPERAT = 1
        AND I1.CODINTR1 IS NOT NULL
        AND I.AN*12+I.LUNA'||COALESCE(sCondAL, '') || COALESCE(sCondGest, '') || PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT') ||'
     UNION ALL
      SELECT
        NS.CODOBIECT, COALESCE(NSO.FURN,0) FURN, SER.SERIE, NSO.CODNIRSTOC, I.DATADOC AS DATA, I.CODINTR, 0 CODIES,
        0 STOCINIT, -L1.CANT CANTINT, NO.GEST AS GEST, NO.TIPNIR TIPDOC, I1.CODINTR1, 0 CODIES1,
        D1.CODDVI1, 0 CODTRANSF1
      FROM INTRARI I
        INNER JOIN LIVR L ON L.CODINTR = I.CODINTR AND L.TIPLIVR = I.TIPDOC
        INNER JOIN LIVR1 L1 ON L1.CODLIVR = L.CODLIVR
        INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
        INNER JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = NS.CODNIRSTOC
        INNER JOIN NIRSTOC NSO ON NSO.CODNIRSTOC = NS1.CODNIRSTOCORIG
        INNER JOIN NIR NO ON NO.CODNIR = NSO.CODNIR
        INNER JOIN NIR N ON NS.CODNIR = N.CODNIR
        INNER JOIN NGEST G ON N.GEST = G.CODGEST'||
        COALESCE(sJoinCLS, '')||'
        LEFT JOIN DVI1 D1 ON D1.CODDVI1 = L1.CODDVI1
        LEFT JOIN INTRARI1 I1 ON I1.CODINTR1 = Coalesce(D1.CODINTR1, L1.CODINTR1,0) AND I1.CODINTR = I.CODINTR
        LEFT JOIN NIRSER NSE ON NSE.CODNIRSER = L1.CODNIRSER
        LEFT JOIN NSERII SER ON SER.CODSERIE = NSE.CODSERIE
      WHERE I.TIPDOC IN (1, 2, 3, 4, 5, 7) AND I.ANULAT = 0 AND I.OPERAT = 1
        AND I1.CODINTR1 IS NOT NULL
        AND I.AN*12+I.LUNA'|| COALESCE(sCondAL, '') || COALESCE(sCondGest, '') || PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT')||'
    ) A_PG
    WHERE (STOCINIT &lt;&gt; 0 OR CANTINT &lt;&gt; 0)
  ),
  OIES AS (
    SELECT
      NSL.CODOBIECT, NS.CODNIRSTOC, I.CODIES, 0 CODINTR, I.DATADOC,
      COALESCE(NS.FURN,0) AS FURN, SER.SERIE, N.GEST, I.TIPDOC, 0 STOCINIT, 0 CANTINT, CASE WHEN I.TIPDOC = 15 THEN -1 ELSE 1 END * L1.CANT AS CANTIES, 1 ORD,
      L1.CODINTR1, L1.CODIES1, L1.CODDVI1, 0 CODTRANSF1
    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 NIRSTOC  NSL ON NSL.CODNIRSTOC = L1.CODNIRSTOC
      INNER JOIN NIR      NL  ON NL.CODNIR = NSL.CODNIR
      INNER JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = L1.CODNIRSTOC
      INNER JOIN NIRSTOC  NS  ON NS.CODNIRSTOC = NS1.CODNIRSTOCORIG
      INNER JOIN NIR      N   ON N.CODNIR = NS.CODNIR
      INNER JOIN NGEST    G   ON NL.GEST = G.CODGEST
      LEFT  JOIN INTRARI  R   ON R.CODINTR = N.CODINTR AND R.TIPDOC = N.TIPNIR
      LEFT  JOIN TRANSF  RT   ON RT.CODTRANSF = N.CODTRANSF AND RT.TIPDOC = N.TIPNIR
      LEFT  JOIN IESIRI   IES ON IES.CODIES = N.CODIES AND IES.TIPDOC = N.TIPNIR
      LEFT  JOIN NIRSER   NSE ON NSE.CODNIRSER = L1.CODNIRSER
      LEFT  JOIN NSERII   SER ON SER.CODSERIE = NSE.CODSERIE
    WHERE I.TIPDOC IN ('||sTipDocIes||') AND I.OPERAT = 1 AND I.ANULAT = 0 AND (L1.CANT &gt; 0 AND I.TIPDOC &lt;&gt; 15 OR L1.CANT &lt; 0 AND I.TIPDOC = 15)
      AND I.AN*12+I.LUNA'|| COALESCE(sCondAL, '') || COALESCE(sCondGest1, '') || PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT') ||
  'UNION ALL
   SELECT
        NS.CODOBIECT, NSO.CODNIRSTOC, I.CODIES, COALESCE(INTR.CODINTR, T.CODTRANSF) CODINTR, I.DATADOC,
        COALESCE(NSO.FURN,0) FURN, SER.SERIE, N.GEST AS GEST, I.TIPDOC, 0 STOCINIT,0 CANTINT, L1.CANT CANTIES, 1 ORD,
        II1.CODINTR1, L1.CODIES1, DVI1.CODDVI1, TT1.CODTRANSF1
      FROM NIRSTOC NS
           INNER JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = NS.CODNIRSTOC
           INNER JOIN NIRSTOC NSO ON NSO.CODNIRSTOC = NS1.CODNIRSTOCORIG'||
           coalesce(sJoinCLS, '')||'
           INNER JOIN LIVR1 L1 ON L1.CODNIRSTOC = NS.CODNIRSTOC
           INNER JOIN NIR N ON N.CODNIR = NSO.CODNIR
           INNER JOIN NIR NN ON NN.CODNIR = NS.CODNIR
           INNER JOIN NGEST G ON NN.GEST = G.CODGEST
           INNER JOIN LIVR L ON L.CODLIVR = L1.CODLIVR
           INNER JOIN IESIRI I ON I.CODIES = L.CODIES
           INNER JOIN IESIRI1 I1 ON I1.CODIES1 = L1.CODIES1 AND I1.CODIES = I.CODIES
           LEFT JOIN INTRARI1 II1 ON II1.CODINTR1 = NS.CODINTR1
           LEFT JOIN TRANSF1 TT1 ON NS.CODTRANSF1 = TT1.CODTRANSF1
           LEFT JOIN DVI1 DVI1 ON NS.CODDVI1 = DVI1.CODDVI1
           LEFT JOIN INTRARI1 INTR1 ON NSO.CODINTR1 = INTR1.CODINTR1
           LEFT JOIN INTRARI INTR ON INTR.CODINTR = INTR1.CODINTR
           LEFT JOIN TRANSF1 T1 ON NSO.CODTRANSF1 = T1.CODTRANSF1
           LEFT JOIN TRANSF T ON T1.CODTRANSF = T.CODTRANSF
           LEFT JOIN NIRSER NSE ON L1.CODNIRSER = NSE.CODNIRSER
           LEFT JOIN NSERII SER ON SER.CODSERIE = NSE.CODSERIE
      WHERE I.AN*12+I.LUNA'||COALESCE(sCondAL, '') || COALESCE(sCondGestN, '') || PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT') || ' AND L1.CANT &lt; 0
     UNION ALL
     SELECT
      LV.CODOBIECT, 0 CODNIRSTOC, I.CODIES, 0 CODINTR, I.DATADOC,
      COALESCE(NS.FURN,0) AS FURN, SER.SERIE, LV.GEST, I.TIPDOC, 0 STOCINIT, 0 CANTINT, CASE WHEN I.TIPDOC = 15 THEN -1 ELSE 1 END * L1.CANT AS CANTIES, 1 ORD,
      L1.CODINTR1, L1.CODIES1, L1.CODDVI1, 0 CODTRANSF1
    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 LIVRVAL  LV  ON LV.CODLIVR1 = L1.CODLIVR1
      LEFT JOIN NIRSTOC  NSL ON NSL.CODNIRSTOC = L1.CODNIRSTOC
      LEFT JOIN NIR      NL  ON NL.CODNIR = NSL.CODNIR
      LEFT JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = L1.CODNIRSTOC
      LEFT JOIN NIRSTOC  NS  ON NS.CODNIRSTOC = NS1.CODNIRSTOCORIG
      LEFT JOIN NIR      N   ON N.CODNIR = NS.CODNIR
      LEFT JOIN NGEST    G   ON LV.GEST = G.CODGEST
      LEFT  JOIN INTRARI  R   ON R.CODINTR = N.CODINTR AND R.TIPDOC = N.TIPNIR
      LEFT  JOIN TRANSF  RT   ON RT.CODTRANSF = N.CODTRANSF AND RT.TIPDOC = N.TIPNIR
      LEFT  JOIN IESIRI   IES ON IES.CODIES = N.CODIES AND IES.TIPDOC = N.TIPNIR
      LEFT  JOIN NIRSER   NSE ON NSE.CODNIRSER = L1.CODNIRSER
      LEFT  JOIN NSERII   SER ON SER.CODSERIE = NSE.CODSERIE
    WHERE I.TIPDOC IN ('||sTipDocIes||') AND I.OPERAT = 1 AND I.ANULAT = 0 AND (L1.CANT &lt;&gt; 0 AND I.TIPDOC &lt;&gt; 15 OR L1.CANT &lt; 0 AND I.TIPDOC = 15)
      AND I.AN*12+I.LUNA' || COALESCE(sCondAL, '') || COALESCE(sCondGest2, '') ||PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT');
    if current_setting('PKG_LIST_SELECTLUNAAN.vOpt2', TRUE)::NUMERIC = 1 THEN
    sInsert := sInsert||'
    UNION ALL
    SELECT
      NS.CODOBIECT, NS.CODNIRSTOC, T.CODTRANSF CODIES, 0 CODINTR, T.DATADOC,
      COALESCE(NS.FURN,0) AS FURN, SER.SERIE, N.GEST, T.TIPDOC,
      0 STOCINIT, 0 CANTINT, L1.CANT AS CANTIES, 1 ORD,
      0 CODINTR1, 0 CODIES1, 0 CODDVI1, T1.CODTRANSF1
    FROM TRANSF T
      INNER JOIN TRANSF1  T1  ON T1.CODTRANSF = T.CODTRANSF
      INNER JOIN LIVR     L   ON L.CODTRANSF = T.CODTRANSF AND L.TIPLIVR = T.TIPDOC
      INNER JOIN LIVR1    L1  ON L1.CODLIVR = L.CODLIVR AND L1.CODIES1 = T1.CODTRANSF1
      INNER JOIN NIRSTOC  NSL ON NSL.CODNIRSTOC = L1.CODNIRSTOC
      INNER JOIN NIR      NL  ON NL.CODNIR = NSL.CODNIR
      INNER JOIN NIRSTOC1 NS1 ON NS1.CODNIRSTOC = L1.CODNIRSTOC
      INNER JOIN NIRSTOC  NS  ON NS.CODNIRSTOC = NS1.CODNIRSTOCORIG
      INNER JOIN NIR      N   ON N.CODNIR = NS.CODNIR
      INNER JOIN NGEST    G   ON G.CODGEST = NL.GEST
      LEFT  JOIN INTRARI  R   ON R.CODINTR = N.CODINTR AND R.TIPDOC = N.TIPNIR
      LEFT  JOIN TRANSF   RT  ON RT.CODTRANSF = N.CODTRANSF AND RT.TIPDOC = N.TIPNIR
      LEFT  JOIN NIRSER   NSE ON NSE.CODNIRSER = L1.CODNIRSER
      LEFT  JOIN NSERII   SER ON SER.CODSERIE = NSE.CODSERIE
    WHERE T.TIPDOC = 12 AND T.OPERAT = 1 AND T.ANULAT = 0
      AND T.AN*12+T.LUNA'|| COALESCE(sCondAL, '')||COALESCE(sCondGest1, '') ||PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT');
  END IF;
  sInsert := sInsert||')
  SELECT
    O.DENUMIRE, PROD.DEN_PART PRODUCATOR, J.SERIE, COALESCE(FURN.DEN_PART,GI.DEN_GEST) FURNIZOR,
    CASE WHEN DIM.CODIES &gt; 0 THEN DIM.PREFIXDOC ELSE COALESCE(INTR.PREFIXDOC,TRI.PREFIXDOC) END,
    CASE WHEN DIM.CODIES &gt; 0 THEN DIM.NRDOC ELSE COALESCE(INTR.NRDOC,TRI.NRDOC) END,
    CASE WHEN DIM.CODIES &gt; 0 THEN DIM.DATADOC ELSE COALESCE(INTR.DATADOC,TRI.DATADOC) END,
    J.STOCINIT,
    J.CANTINT,
    COALESCE(CLI.DEN_PART,GE.DEN_GEST) CLIENT, J.CANTIES, COALESCE(IES.PREFIXDOC,TRE.PREFIXDOC), COALESCE(IES.NRDOC,TRE.NRDOC), COALESCE(IES.DATADOC,TRE.DATADOC),
    Sum(J.STOCINIT+J.CANTINT-J.CANTIES) OVER (PARTITION BY O.CODOBIECT, FURN.CODPART, Coalesce(J.SERIE,''~'')
    ORDER BY J.DATADOC, J.ORD, J.CODIES ROWS UNBOUNDED PRECEDING) STOC,
    Row_Number()                     OVER (PARTITION BY O.CODOBIECT, FURN.CODPART, Coalesce(J.SERIE,''~'')
    ORDER BY J.DATADOC, J.ORD, J.CODIES) ORDINE  '||gUserAlias||'
  FROM (SELECT * FROM OINT
        UNION ALL
        SELECT * FROM OIES
       ) J
    INNER JOIN NARTOBJ  O       ON O.CODOBIECT        = J.CODOBIECT
    INNER JOIN NART     A       ON A.CODARTICOl       = O.CODARTICOL
    INNER JOIN NART1    A1      ON A1.CODARTICOl      = O.CODARTICOL AND '|| coalesce(current_setting('PKG_LIST_SELECTLUNAAN.vLunaStop', TRUE)::NUMERIC, 0) ||' BETWEEN    A1.ALSTART and    A1.ALSTOP
    INNER JOIN NGEST    G       ON G.CODGEST          = J.GEST
    LEFT  JOIN NTVA             ON NTVA.CODTVA        = A1.CODTVA
    LEFT  JOIN NTVA1            ON NTVA1.CODTVA       = A1.CODTVA    AND '|| coalesce(current_setting('PKG_LIST_SELECTLUNAAN.vLunaStop', TRUE)::NUMERIC, 0) ||' BETWEEN NTVA1.ALSTART and NTVA1.ALSTOP
    LEFT  JOIN NCLASEA  CA      ON CA.CODCLASEA       = A.CLASA
    LEFT  JOIN NCLASEAS CAS     ON CAS.CODCLASEAS     = A.CLASASTATIST
    LEFT  JOIN INTRARI  INTR    ON INTR.CODINTR       = J.CODINTR AND J.TIPDOC = INTR.TIPDOC
    LEFT  JOIN IESIRI   IES     ON IES.CODIES         = J.CODIES AND J.TIPDOC = IES.TIPDOC
    LEFT  JOIN IESIRI   DIM     ON DIM.CODIES         = J.CODIES AND J.TIPDOC = DIM.TIPDOC AND J.TIPDOC = 15
    LEFT  JOIN TRANSF   TRI     ON TRI.CODTRANSF      = J.CODINTR AND J.TIPDOC = TRI.TIPDOC
    LEFT  JOIN TRANSF   TRE     ON TRE.CODTRANSF      = J.CODIES AND J.TIPDOC = TRE.TIPDOC
    LEFT  JOIN NPART    FURN    ON FURN.CODPART       = J.FURN
    LEFT  JOIN NPART    CLI     ON CLI.CODPART        = IES.PARTENER
    LEFT  JOIN NGEST    GI      ON GI.CODGEST         = TRI.CODGESTCMD
    LEFT  JOIN NGEST    GE      ON GE.CODGEST         = TRE.CODGESTCMD
    LEFT  JOIN NPART    PROD    ON PROD.CODPART       = O.CODPRODUCATOR
    LEFT  JOIN NCLASEP  CF      ON CF.CODCLASEP       = FURN.CODCLASA
    LEFT  JOIN NCLASEP  CC      ON CC.CODCLASEP       = CLI.CODCLASA
    LEFT  JOIN NCLASEP  CP      ON CP.CODCLASEP       = PROD.CODCLASA
    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 IESIRI1 IES1     ON IES1.CODIES1 = J.CODIES1
    LEFT  JOIN INTRARI1 II1     ON II1.CODINTR1 = J.CODINTR1
    LEFT  JOIN DVI1     DVI1    ON DVI1.CODDVI1 = J.CODDVI1
    LEFT  JOIN TRANSF1  TT1     ON TT1.CODTRANSF1 = J.CODTRANSF1
    '||
    gSuplJoins||sFiltru;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_soldpart_processlist</obj_name>
  <obj_hashval>e3b175c860078ac4dd9e76e53a96354c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_soldpart_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar := '';
  vAnLunaC    NUMERIC;
  vAnPrec     NUMERIC;
  vLunaPrec   NUMERIC;
  vDoarSub    BOOLEAN := False;
  gSuplCols   VARCHAR := 'NPART P, NPART1 P1, NMONEDE MON, NCont C, NPERS AG';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Adina 30.04.2021 - alstart,alstop
  --Adina 24 august 2020
  CALL PRC_AL_CHECK('npart1' ,0);
  CALL PRC_AL_CHECK('iopart1',0);

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

  PERFORM pkg_NomPart_SET_CODPART_SOLD_ANALIZAT( 0);

  SELECT ancurent * 12 + lunacurenta INTO vAnLunaC FROM FirmaLuni;

  SELECT  NEWAN, newLuna INTO vAnPrec, vLunaPrec from pkg_globals_Calculeaza_Luna_Precedenta(getANLUCRU(), getLUNALUCRU(), vAnPrec, vLunaPrec);

  PERFORM pkg_globals_SetLunaPRECEDENTA( vAnPrec, vLunaPrec);
  PERFORM pkg_globals_SetLunaTemp( GetAnLucru(), GetLunaLucru());

  IF  getAnLunaLucru() &gt;= vAnLunaC THEN
    PERFORM PKG_INCHIDERI_MAKE_REST_OBLIGPIF_LUNA();
  END IF;

  IF  GetSubunitate() &gt; 1 THEN
    vDoarSub :=  COALESCE( (fnc_GetValConstanta('Holding', GetAnLucru(), GetLunaLucru()))::numeric, 2) &lt;&gt; 2;
  END IF;

  sInsert := '
  INSERT INTO ' || tmpName || '(CODPART, PARTENER, CONT, SOLDL, SOLDV, RTVAL, RTVAV, MONEDA' || gUserFields || ')
  WITH
  iop1 AS (
    SELECT
      io1.codiopart, xxx.icont,
      coalesce(CASE xxx.iCont
        WHEN 02 THEN io1.ContFurnizor
        WHEN 03 THEN io1.ContClient
        WHEN 04 THEN io1.ContFurnAvans
        WHEN 05 THEN io1.ContClientAvans
        WHEN 06 THEN io1.ContFurnAVIZ
        WHEN 07 THEN io1.ContClientAVIZ
        WHEN 08 THEN io1.ContFurnMF
        WHEN 09 THEN io1.ContCreditD
        WHEN 10 THEN io1.ContDebitD
        WHEN 11 THEN io1.ContLitigii
        WHEN 12 THEN io1.ContFurnAVS
        WHEN 13 THEN io1.ContFurnAVIC
        WHEN 14 THEN io1.ContFurnAVIN
        WHEN 15 THEN io1.ContTerti
        WHEN 16 THEN io1.ContFurnLEAS
        WHEN 17 THEN io1.ContNCRF
        WHEN 18 THEN io1.ContNCRC
        WHEN 19 THEN io1.ContCheltAvans
        WHEN 20 THEN io1.ContVenitAvans
        WHEN 21 THEN io1.ContGarantieEF
        WHEN 22 THEN io1.ContGarantieTF
        WHEN 23 THEN io1.ContGarantieEC
        WHEN 24 THEN io1.ContGarantieTC
        WHEN 25 THEN io1.ContSuplimF1
        WHEN 26 THEN io1.ContSuplimF2
        WHEN 27 THEN io1.ContSuplimF3
        WHEN 28 THEN io1.ContSuplimF4
        WHEN 29 THEN io1.ContSuplimF5
        WHEN 30 THEN io1.ContSuplimC1
        WHEN 31 THEN io1.ContSuplimC2
        WHEN 32 THEN io1.ContSuplimC3
        WHEN 33 THEN io1.ContSuplimC4
        WHEN 34 THEN io1.ContSuplimC5
        WHEN 35 THEN io1.ContSuplimF6
        WHEN 36 THEN io1.ContSuplimF7
        WHEN 37 THEN io1.ContSuplimF8
        WHEN 38 THEN io1.ContSuplimF9
        WHEN 39 THEN io1.ContSuplimF10
        WHEN 40 THEN io1.ContSuplimF11
        WHEN 41 THEN io1.ContSuplimF12
        WHEN 42 THEN io1.ContSuplimF13
        WHEN 43 THEN io1.ContSuplimF14
        WHEN 44 THEN io1.ContSuplimF15
        WHEN 45 THEN io1.ContSuplimF16
        WHEN 46 THEN io1.ContSuplimF17
        WHEN 47 THEN io1.ContSuplimF18
        WHEN 48 THEN io1.ContSuplimF19
        WHEN 49 THEN io1.ContSuplimF20
        WHEN 50 THEN io1.ContSuplimF21
        WHEN 51 THEN io1.ContSuplimF22
        WHEN 52 THEN io1.ContSuplimF23
        WHEN 53 THEN io1.ContSuplimF24
        WHEN 54 THEN io1.ContSuplimF25
        WHEN 55 THEN io1.ContSuplimF26
        WHEN 56 THEN io1.ContSuplimF27
        WHEN 57 THEN io1.ContSuplimF28
        WHEN 58 THEN io1.ContSuplimF29
        WHEN 59 THEN io1.ContSuplimF30
      END,0) codCont
    FROM
            iopart1 io1
            CROSS JOIN (SELECT i AS iCont FROM generate_series(2, 59) s(i) ) xxx
    WHERE getAnLunaLucru() BETWEEN io1.ALStart and io1.ALStop
  )
  SELECT S.CODPART, P.DEN_PART, C.SIMBOL, S.SOLDLEI, S.SOLDVALUTA, S.RESTTVALEI, S.RESTTVAVALUTA, MON.DEN_MONEDA' || gUserAlias || '
  FROM ' || CASE WHEN vDoarSub THEN 'V_SOLDPARTSUB_EXT' ELSE 'V_SOLDPART_EXT' END  || ' S
    INNER JOIN NPART   P    ON P.CODPART      = S.CODPART
    INNER JOIN NMONEDE MON  ON MON.CODMONEDA  = S.CODMONEDA
    LEFT  JOIN NPART1  P1   ON P1.CODPART     = P.CODPART    AND getAnLunaLucru() BETWEEN P1.ALStart and P1.ALStop
    LEFT  JOIN IOP1         ON IOP1.CODIOPART = P1.CODIOPART AND IOP1.ICONT = S.ICONT
    LEFT  JOIN NCONT   C    ON C.CODCONT      = IOP1.CODCONT
    LEFT  JOIN NAGENDA SSOC ON SSOC.CODPART   = S.CODPART    AND SSOC.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(ssoc.INACTIV, 0) = 0
    LEFT  JOIN NPERS   AG   ON AG.CODPERS     = SSOC.CODAGENT' || gSuplJoins || '
  WHERE (coalesce(S.SOLDLEI,0) &lt;&gt; 0 OR coalesce(S.SOLDVALUTA,0) &lt;&gt; 0)
    AND S.CODPART &lt;&gt; 0' || COALESCE((CASE WHEN vDoarSub THEN ' AND S.SUBUNITATEA = ' || GetSubunitate()::varchar END),'') ;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_setguseralias</obj_name>
  <obj_hashval>d38c67c9b9118fd3f3f0bdafe5c114de</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_setguseralias(aguseralias character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_STOCEP.gUserAlias',agUserAlias,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocexp_processlist</obj_name>
  <obj_hashval>37cd77f3f3ea8d64665f7dcdffa8c2f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocexp_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       varchar := '';
  vZiuaFin       date     := to_date(current_setting('PKG_LIST_SELECTSCAD.vDataScad', true), 'DD.MM.YYYY');
  sZiuaFin       varchar := 'To_date(''' || coalesce(To_Char(vZiuaFin, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
  vToateGest     BOOLEAN := current_setting('PKG_LIST_SELECTSCAD.vToateGest',  true)::boolean;
  vToateIOArt   BOOLEAN := current_setting('PKG_LIST_SELECTSCAD.vToateIoart', true)::boolean;
  vAduSerii     BOOLEAN := current_setting('PKG_LIST_SELECTSCAD.vExtra2',     true)::boolean;
  vCateGest     NUMERIC := 0;
  vCateLGest     NUMERIC := 0;
  sColSerie     varchar := ', NULL SERIE';
  sJoinSerie     varchar := '';
  sGrupSerie     varchar := '';
  sFiltru       varchar := '';
  gSuplCols      VARCHAR := 'NARTOBJ NAO, NART NA, NIR ROOTNIR, NGEST NG, IOART IO, INTRARI I, NLOCATII NL, NUM NUM, NPART NFURN, NSUBUNIT NSUB, NGEST NGP, NPART NPROD';
   gUserFields    VARCHAR := '';
  gUserAlias     VARCHAR := '';
  gNullAlias     VARCHAR := '';
  gSuplJoins     VARCHAR := '';
BEGIN
  --Adina 08.04.2021 - alstart,alstop
  --Adina 03 septembrie 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_STOCEXP.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  CALL PRC_AL_CHECK('ioart1',0);

  IF vAduSerii THEN
    sColSerie := ', SER.SERIE';
    sJoinSerie := '
        LEFT JOIN NSERII SER ON SER.CODSERIE = NSER.CODSERIE';
    sGrupSerie := ', SER.SERIE';
  END IF;

  IF  NOT vToateIOArt THEN
    sFiltru := sFiltru || '
        AND NS.CODIOART::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' ) ';
  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
      sFiltru := sFiltru || '
        AND NIR.GEST::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' ) ';
    ELSIF vCateGest = 0 THEN
      sFiltru := sFiltru || '
        AND NS.CODLOCATIE::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' ) ';
    ELSE
      sFiltru := sFiltru || '
        AND (NIR.GEST::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' ) OR
             NS.CODLOCATIE::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'')) ';
    END IF;
  END IF;

  sInsert :=
  'INSERT INTO ' || tmpName ||
  '( CodObiect, Gest, LGest, Cont, Articol, UM, Stoc, Valoare, TG, Serie, MG, DataIn, PretAchiz, PretInreg, Furn, CodExtern, CodIntern, Producator, Provizion' || gUserFields || ')
  WITH
    STOCTG AS (
      SELECT
        NS.CODOBIECT, NS.CODNIR, NS.CODLOCATIE, NS.CODIOART, IO1.MG, NS.PRET, NS.ADAOS,NS.PROVIZION, NIR.GEST,
        SUM(COALESCE(NSER.REST,NS.REST)) REST, COALESCE(NSER.TG,NS.TG) TG' || sColSerie || ',
        CASE WHEN NS.CODNIRSTOCPARINTE IS NULL THEN NS.CODNIR ELSE PKG_LIST_BASE_STOCEXP_GETROOTCODNIR(NS.CODNIRSTOCPARINTE) END ROOTCODNIR
      FROM NIRSTOC NS
        INNER JOIN NIR          ON NIR.CODNIR      = NS.CODNIR
        INNER JOIN NARTOBJ NAO  ON NAO.CODOBIECT   = NS.CODOBIECT
        INNER JOIN NART    NA   ON NA.CODARTICOL   = NAO.CODARTICOL
        INNER JOIN IOART1  IO1  ON IO1.CODIOART    = NS.CODIOART AND ' || coalesce(getAnLunaLucru()::varchar,'0') || ' BETWEEN IO1.ALStart and IO1.ALStop
        LEFT  JOIN  NIRSER NSER ON NSER.CODNIRSTOC = NS.CODNIRSTOC ' || sJoinSerie || '
      WHERE IO1.MG &lt;&gt; 5
        AND (COALESCE(NSER.TG,NS.TG) IS NOT NULL) AND (COALESCE(NSER.TG,NS.TG) &lt;= ' || coalesce(sZiuaFin,'') || ')
        AND COALESCE(NSER.REST, NS.REST) &gt; 0' || sFiltru || '
      GROUP BY
        NS.CODOBIECT, NS.CODNIR, NS.CODLOCATIE, NS.CODIOART, NS.PRET, NS.ADAOS, NS.PROVIZION, COALESCE(NSER.TG,NS.TG)' || sGrupSerie || ',NIR.GEST,
        CASE WHEN NS.CODNIRSTOCPARINTE IS NULL THEN NS.CODNIR ELSE PKG_LIST_BASE_STOCEXP_GETROOTCODNIR(NS.CODNIRSTOCPARINTE) END, IO1.MG
      )
  SELECT
    NAO.CodObiect, NG.DEN_GEST, NL.DENUMIRE, IO.DEN_IOART, NAO.DENUMIRE, NUM.DEN_UM, STG.REST, STG.REST * STG.PRET, STG.TG, STG.SERIE,
    (case STG.MG when 1 then ''FIFO'' when 2 then ''LIFO'' when 3 then ''PMP'' when 4 then ''IDS'' else NULL end), ROOTNIR.DATANIR,
    STG.PRET - STG.ADAOS, STG.PRET, (case I.TIPDOC when 6 then NSUB.DEN_SUBUNIT when 7 then NGP.DEN_GEST else NFURN.DEN_PART end),
    NAO.CODEXTERN, NAO.CODINTERN, NPROD.DEN_PART, STG.PROVIZION' || gUserAlias || '
  FROM STOCTG STG
    INNER JOIN NARTOBJ  NAO     ON NAO.CODOBIECT   = STG.CODOBIECT
    INNER JOIN NART     NA      ON NA.CODARTICOL   = NAO.CODARTICOL
    INNER JOIN NIR      ROOTNIR ON ROOTNIR.CODNIR  = STG.ROOTCODNIR
    INNER JOIN NGEST    NG      ON NG.CODGEST      = STG.GEST ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG', 'CODSUBUNIT',NULL,NULL),'') || '
    INNER JOIN IOART    IO      ON IO.CODIOART     = STG.CODIOART
    LEFT  JOIN INTRARI  I       ON I.CODINTR       = ROOTNIR.CODINTR
    LEFT  JOIN NLOCATII NL      ON NL.CODLOCATIE   = STG.CODLOCATIE
    LEFT  JOIN NUM              ON NUM.CODUM       = NA.UM
    LEFT  JOIN NPART    NFURN   ON NFURN.CODPART   = I.PARTENER
    LEFT  JOIN NSUBUNIT NSUB    ON NSUB.CODSUBUNIT = I.CODSUBUNIT
    LEFT  JOIN NGEST    NGP     ON NGP.CODGEST     = I.CODGESTPROD
    LEFT  JOIN NPART    NPROD   ON NPROD.CODPART   = NAO.CODPRODUCATOR' || gSuplJoins || '
  WHERE STG.REST &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_stocfaramisc_processlist</obj_name>
  <obj_hashval>224136c9de3e964a7f04944ba21cb8fd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocfaramisc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       varchar := '';
  vToateGest     BOOLEAN := current_setting('PKG_LIST_SELECTSCAD.vToateGest',  true)::boolean;
  vToateIOArt   BOOLEAN := current_setting('PKG_LIST_SELECTSCAD.vToateIoart', true)::boolean;
  vInclNoStoc   BOOLEAN := current_setting('PKG_LIST_SELECTSCAD.vExtra1',     true)::boolean;
  vSerii         BOOLEAN := current_setting('PKG_LIST_SELECTSCAD.vExtra2',     true)::boolean;
  vCateGest     NUMERIC := 0;
  vCateLGest     NUMERIC := 0;
  vZiuaIni       date := to_date(current_setting('PKG_LIST_SELECTSCAD.vDataIni', true), 'DD.MM.YYYY');
  vZiuaFin       date := to_date(current_setting('PKG_LIST_SELECTSCAD.vDataScad', true), 'DD.MM.YYYY');
  sZiuaIni       varchar := 'To_date(''' || coalesce(To_Char(vZiuaIni, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
  sZiuaFin       varchar := 'To_date(''' || coalesce(To_Char(vZiuaFin, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
  sStoc         VARCHAR(5000) := '';
  sFiltruStoc   varchar := '';
  sWhere         varchar := '';
  sAux           varchar := '';
  sJoinNIR       varchar := '';
  sJoinNGest    varchar := '';
  sJoinStoc     varchar := 'INNER';
  sExclLivrPer   varchar := '';
  sExclNirPer   varchar := '';
  sSerie         varchar := ' 0 ';
  sCantNir       varchar := 'NS.CANTNIR';
  sJoinSer       varchar := '';
  sFiltruL       varchar := '';
  sSGroup       varchar := '';
  sDenGest       varchar := '';
  sCampSer       varchar := '';
  sCodGest       varchar := 'N.Gest';
  gSuplCols      VARCHAR := 'NARTOBJ NAO, NART NA, NUM NUM, NPART PROD, NCONT NC, NCLASEA CLS';
   gUserFields    VARCHAR := '';
  gUserAlias     VARCHAR := '';
  gNullAlias     VARCHAR := '';
  gSuplJoins     VARCHAR := '';
  vCentralizat  NUMERIC := current_setting('PKG_LIST_SELECTSCAD.vCentralizat', true)::numeric;
BEGIN
  --Florin 21.04.2023 - fixat 58002
  --Florin 03.04.2023 - sinc. Oracle
  --Adina 08.04.2021 - alstart,alstop
  --Adina 04.01.2021 tichet 41971- add AATMP_LM cu alias LM la linia 234
  --Adina 28.12.2020 - inlocuit cursorul LM cu tabela temporara AATMP_LM
  --Adina 14.12.2020 tichete 41572, 41573
  --Adina 03 septembrie 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_STOCFARAMISC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  CALL PRC_AL_CHECK('ioart1',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';

    IF  vCateLGest = 0 THEN
      sFiltruStoc := sFiltruStoc || '
        AND N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
    ELSIF vCateGest = 0 THEN
      sFiltruStoc := sFiltruStoc || '
        AND NS.CODLOCATIE::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'') ';
    ELSE
      sFiltruStoc := sFiltruStoc || '
        AND (N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') OR NS.CODLOCATIE::varchar (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'')) ';
    END IF;
  END IF;

  IF  NOT vToateIOArt THEN
    sFiltruStoc := sFiltruStoc || '
        AND NS.CODIOART::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
  END IF;

  sAux := (PKG_LIST_BASE_UTILS_COND_SUBUNIT('G', 'CODSUBUNIT', '
        AND',NULL));

  IF sAux IS NOT NULL  THEN
    sJoinNIR   := '
        INNER JOIN NIR N ON N.CODNIR = NS.CODNIR';
    sJoinNGest := '
        INNER JOIN NGEST G ON G.CODGEST = N.GEST';
    sFiltruStoc := sFiltruStoc || sAux;
  END IF;

  IF vSerii THEN
    sSerie   := ' NSER.';
    sCantNir := 'COALESCE(NSER.CANTNIR,NS.CANTNIR,0)';
    sCampSer := ', L1.CODNIRSER';
    sJoinSer := '
        LEFT JOIN NIRSER NSER ON NSER.CODNIRSTOC = NS.CODNIRSTOC';
    sFiltruL := ' AND coalesce(L.CODNIRSER,0) = coalesce(NSER.CODNIRSER,0)';
    sSGroup  := sSGroup || ', NSER.CODSERIE';
  END IF;

--  CASE vCentralizat
--    WHEN 1 THEN
--      sDenGest := 'NG.';
--      sSGroup  := sSGroup || ', N.GEST';
--    WHEN 2 THEN
--      sDenGest := 'NG.';
--      sSGroup  := sSGroup || ', N.GEST';
--    ELSE
--      sDenGest := '''FIRMA'' ';
--      sCodGest := 'NULL::numeric Gest';
--  END CASE;

  sSGroup := sSGroup || ', NS.CODIOART';

  IF  vCentralizat &lt;&gt; 0 THEN
    sExclLivrPer := '
            WHEN L.TIPLIVR IN (6,12,13,23) THEN 0';
    sExclNirPer  := '
            WHEN N.TIPNIR IN  (6,12,13,23) THEN 0';
  END IF;

  IF vInclNoStoc THEN
    sJoinStoc := 'LEFT';
  END IF;

  IF  NOT vToateGest AND vInclNoStoc AND  vCateGest &lt;&gt; 0 THEN
    sWhere := '
    AND (S.CODOBIECT IS NOT NULL OR NA.GESTIMPLICITA::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST''))';
  ELSIF NOT vToateGest AND vInclNoStoc AND  vCateGest = 0 THEN
    sJoinStoc := 'INNER';
  END IF;

  IF  NOT vToateIOArt AND vInclNoStoc THEN
    sWhere := sWhere || '
    AND (S.CODOBIECT IS NOT NULL OR NA.CONTIMPLICIT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART''))';
  END IF;

  sStoc := 'SELECT
      NS.CODOBIECT, '||sSerie||'CODSERIE, N.GEST CODGEST, NS.CODIOART,
      SUM('||sCantNir||'+coalesce(L.CANTIES,0)) CANT, SUM(('||sCantNir||'+coalesce(L.CANTIES,0)) * NS.PRET) VALINREG,
      SUM(CASE'||
            sExclNirPer||'
            WHEN N.DATANIR &gt;= '||sZiuaIni||' THEN 1
            ELSE 0
          END
      ) INTR_PER,
      SUM(coalesce(L.LIVR_PER,0)) LIVR_PER
    FROM NIR N
      INNER JOIN NIRSTOC NS ON NS.CODNIR = N.CODNIR
      INNER JOIN NGEST G ON G.CODGEST = N.GEST'||
      sJoinSer||'
      LEFT JOIN          L  ON L.CODNIRSTOC = NS.CODNIRSTOC'||sFiltruL||'
    WHERE N.OPERAT = 1 and N.DATANIR &lt;= '||sZiuaFin||
      sFiltruStoc ||'
    GROUP BY NS.CODOBIECT, N.GEST, NS.CODIOART'||sSGroup;
  if vCentralizat = 1 then
    sStoc := 'SELECT
      NS.CODOBIECT, '||sSerie||'CODSERIE, 0 CODGEST, 0 CODIOART,
      SUM('||sCantNir||'+coalesce(L.CANTIES,0)) CANT, SUM(('||sCantNir||'+coalesce(L.CANTIES,0)) * NS.PRET) VALINREG,
      SUM(CASE'||
            sExclNirPer||'
            WHEN N.DATANIR &gt;= '||sZiuaIni||' THEN 1
            ELSE 0
          END
      ) INTR_PER,
      SUM(coalesce(L.LIVR_PER,0)) LIVR_PER
    FROM NIR N
      INNER JOIN NIRSTOC NS ON NS.CODNIR = N.CODNIR
      INNER JOIN NGEST G ON G.CODGEST = N.GEST'||
      sJoinSer||'
      LEFT JOIN          L  ON L.CODNIRSTOC = NS.CODNIRSTOC'||sFiltruL||'
    WHERE N.OPERAT = 1 and N.DATANIR &lt;= '||sZiuaFin||
      sFiltruStoc ||'
    GROUP BY NS.CODOBIECT'||sSGroup;
  else if vCentralizat = 2 then
    sStoc := 'SELECT
      NS.CODOBIECT, '||sSerie||'CODSERIE,0 CODGEST, NS.CODIOART,
      SUM('||sCantNir||'+coalesce(L.CANTIES,0)) CANT, SUM(('||sCantNir||'+coalesce(L.CANTIES,0)) * NS.PRET) VALINREG,
      SUM(CASE'||
            sExclNirPer||'
            WHEN N.DATANIR &gt;= '||sZiuaIni||' THEN 1
            ELSE 0
          END
      ) INTR_PER,
      SUM(coalesce(L.LIVR_PER,0)) LIVR_PER
    FROM NIR N
      INNER JOIN NIRSTOC NS ON NS.CODNIR = N.CODNIR
      INNER JOIN NGEST G ON G.CODGEST = N.GEST'||
      sJoinSer||'
      LEFT JOIN          L  ON L.CODNIRSTOC = NS.CODNIRSTOC'||sFiltruL||'
    WHERE N.OPERAT = 1 and N.DATANIR &lt;= '||sZiuaFin||
      sFiltruStoc ||'
    GROUP BY NS.CODOBIECT, NS.CODIOART'||sSGroup;
  end if; end if;


  sInsert :=
  'INSERT INTO ' || tmpName || '(
    CodObiect, Art,Ser,Gest,TipCont,Cont,UM,Stoc,PrInreg,ValInreg,MG,
    CodExt,CodInt,Prod,Promise,Last_Furn,Last_DataAchiz,Last_PretAchiz ' || gUserFields || ')
  WITH
  PROMISE AS
  (
    SELECT c1.codobiect, Sum(coalesce(c1.restacceptat,0) - coalesce(rr.cant,0)) cant
    FROM comanda1 c1
      INNER JOIN comanda c ON c1.codcomanda = c.codcomanda
      LEFT JOIN (
                 SELECT r.codcomanda1, CASE WHEN coalesce(r.codobiect,0) = 0 THEN cc1.codobiect ELSE r.codobiect END codobiect, Sum(r.rest) cant
                 FROM rezervats r INNER JOIN comanda1 cc1 on r.codcomanda1 = cc1.codcomanda1
                 WHERE r.codnirstoc &gt; 0
                 GROUP BY r.codcomanda1, CASE WHEN coalesce(r.codobiect,0) = 0 THEN cc1.codobiect ELSE r.codobiect END
                ) rr ON rr.codcomanda1 = c1.codcomanda1 and c1.codobiect = rr.codobiect
    WHERE c.operat = 1 and c.anulat = 0 and c.tipdoc = 18 and coalesce(c.tiptranzactie,0) = 0
      AND c1.termen BETWEEN ' || sZiuaIni || ' AND ' || sZiuaFin || '
    GROUP BY c1.codobiect
  ),
  L AS
  (
    SELECT l1.codnirstoc' || sCampSer || ',
      SUM((case when L.TIPLIVR=15 then 1 else -1 end) * L1.CANT) CANTIES,
      SUM(CASE' || sExclLivrPer || '
            WHEN L.DATALIVR &gt;= ' || sZiuaIni || ' THEN 1
            ELSE 0
          END
      ) LIVR_PER
    FROM LIVR L
      INNER JOIN livr1   l1 ON l1.codlivr    = l.codlivr
      INNER JOIN nirstoc ns ON ns.codnirstoc = l1.codnirstoc' || sJoinNIR || sJoinNGest || '
    WHERE L.DATALIVR &lt;= ' || sZiuaFin || sFiltruStoc || '
    GROUP BY l1.codnirstoc' || sCampSer || '
  ),
  STOC AS
  (
    SELECT
      NS.CODOBIECT, ' || sSerie || 'CODSERIE, ' || sCodGest || ', NS.CODIOART,
      SUM(' || sCantNir || '+coalesce(L.CANTIES,0)) CANT, SUM((' || sCantNir || '+coalesce(L.CANTIES,0)) * NS.PRET) VALINREG,
      SUM(CASE' || sExclNirPer || '
            WHEN N.DATANIR &gt;= ' || sZiuaIni || ' THEN 1
            ELSE 0
          END
      ) INTR_PER,
      SUM(coalesce(L.LIVR_PER,0)) LIVR_PER
    FROM NIR N
        INNER JOIN NIRSTOC NS ON NS.CODNIR    = N.CODNIR' || sJoinNGest || sJoinSer || '
        LEFT  JOIN         L  ON L.CODNIRSTOC = NS.CODNIRSTOC' || sFiltruL || '
    WHERE N.OPERAT = 1 and N.DATANIR &lt;= ' || sZiuaFin || sFiltruStoc || '
    GROUP BY NS.CODOBIECT, N.GEST' || sSGroup || '
  )
--  ,
--  LM AS
--  (
--    SELECT
--      NS.CODOBIECT,
--      (array_remove(array_agg(P.DEN_PART ORDER BY N.DATANIR DESC, N.CODNIR DESC), null))[1] AS LAST_FURN,  --AA= 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, NS.CODINTR1 ASC), null))[1] AS LAST_PRETACHIZ  -- 14.12.2020 #41573 - pe acelasi Nir am acelasi produs cu 2 preturi diferite si ca sa fie ca in Oracle am adaugat  ''NS.CODINTR1 ASC''
--    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(PKG_LIST_BASE_UTILS_COND_SUBUNIT('G', 'CODSUBUNIT',NULL,NULL),'') || '
--    GROUP BY NS.CODOBIECT
--  )
  SELECT
    NAO.CodObiect, NAO.DENUMIRE, SER.SERIE, ' || sDenGest || 'DEN_GEST, IO.DEN_IOART, NC.SIMBOL, NUM.DEN_UM, coalesce(S.CANT,0), coalesce(S.VALINREG/S.CANT,0), coalesce(S.VALINREG,0), (case IO1.MG when 1 then ''FIFO'' when 2 then ''LIFO'' when 3 then ''PMP'' when 4 then ''IDS'' when 5 then ''VALORIC'' else NULL end),
    NAO.CODEXTERN, NAO.CODINTERN, PROD.DEN_PART PRODUCATOR, coalesce(Promise.Cant,0),LM.Last_Furn,LM.Last_DataAchiz,LM.Last_PretAchiz ' || gUserAlias || '
  FROM NARTOBJ                    NAO
    INNER JOIN NART               NA   ON NA.CODARTICOL     = NAO.CODARTICOL
    ' || sJoinStoc || ' JOIN STOC S    ON S.CODOBIECT       = NAO.CODOBIECT
    LEFT  JOIN AATMP_LM           LM   ON LM.CODOBIECT      = NAO.CODOBIECT
    LEFT  JOIN PROMISE                 ON PROMISE.CODOBIECT = NAO.CODOBIECT
    LEFT  JOIN NCLASEA            CLS  ON NA.CLASA          = CLS.CODCLASEA
    LEFT  JOIN NSERII             SER  ON SER.CODSERIE      = S.CODSERIE
    LEFT  JOIN NGEST              NG   ON NG.CODGEST        = COALESCE(S.GEST, NA.GESTIMPLICITA, 0)
    LEFT  JOIN IOART              IO   ON IO.CODIOART       = COALESCE(S.CODIOART, NA.CONTIMPLICIT, 0)
    LEFT  JOIN IOART1             IO1  ON IO1.CODIOART      = COALESCE(S.CODIOART, NA.CONTIMPLICIT, 0) AND ' || coalesce(getAnLunaLucru()::varchar,'') || ' BETWEEN IO1.ALStart and IO1.ALStop
    LEFT  JOIN NUM                     ON NUM.CODUM         = NA.UM
    LEFT  JOIN NPART              PROD ON PROD.CODPART      = NAO.CODPRODUCATOR
    LEFT  JOIN NCONT              NC   ON NC.CODCONT        = IO1.CONT' || gSuplJoins || '
  WHERE coalesce(S.CANT,-1) &lt;&gt; 0 AND coalesce(S.INTR_PER,0) = 0 AND coalesce(S.LIVR_PER,0) = 0 AND NA.TIPARTICOL = 0::varchar';

  EXECUTE 'DROP TABLE IF EXISTS AATMP_LM';
  EXECUTE 'CREATE TEMPORARY TABLE AATMP_LM AS
             SELECT
      NS.CODOBIECT,
      (array_remove(array_agg(P.DEN_PART ORDER BY N.DATANIR DESC, N.CODNIR DESC), null))[1] AS LAST_FURN,  --AA= 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, NS.CODINTR1 ASC), null))[1] AS LAST_PRETACHIZ  -- 14.12.2020 #41573 - pe acelasi Nir am acelasi produs cu 2 preturi diferite si ca sa fie ca in Oracle am adaugat  ''NS.CODINTR1 ASC''
    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(PKG_LIST_BASE_UTILS_COND_SUBUNIT('G', 'CODSUBUNIT',NULL,NULL),'') || '
    GROUP BY NS.CODOBIECT '
  ;
  EXECUTE 'CREATE INDEX AATMP_LM_IDX ON AATMP_LM(CODOBIECT)';

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  EXECUTE 'DROP TABLE IF EXISTS AATMP_LM';
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocprognoza_processlist</obj_name>
  <obj_hashval>616b7aa420a58dc4de44f8e76786557c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocprognoza_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sColMinMax       varchar := ', NAOS.STOCMIN, NAOS.STOCMAX ';
  sJoinExt         varchar := '';
  gSuplCols        VARCHAR := 'NARTOBJ NAO, NART NA, NARTOBJSUBUNIT NAOS, NUM NUM, NCLASEA CLS, NARTOBJ POBJ';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  sNeconforme     varchar := '';
BEGIN
  --Florin 01.11.2024 - sinc. Oracle
  --Adina 17.08.2021 - sinc.Oracle din 17.08.2021
  --Adina 19.04.2021 - sinc.Oracle - doar la zi
  --Adina 13.03.2021 - sinc.Oracle din 12.03.2021
  --Adina 04 septembrie 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, 'COMANDA',     'COM',   'COM.CODCOMANDA = P.CODCOMANDA'   , 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDA1',   'COM1', 'COM1.CODCOMANDA1 = P.CODCOMANDA1', 1);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_STOCPROGNOZA.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  IF  getSUBUNITATE() = 1 THEN
    sColMinMax := ', NAO.STOCMIN, NAO.STOCMAX';
  END IF;

  sNeconforme := '';
  if current_setting('PKG_LIST_BASE_STOCPROGNOZA.vExclNeconforme',true)::boolean then
    sNeconforme := ' and coalesce(g.tip,0) &lt;&gt; 4 ';
  end if;

  sInsert :=
  'INSERT INTO ' || tmpName || '( Art,UM,Termen,TipTranz,CantIn,CantIes,Stoc,Obs,PrefDoc,NrCom,DataCom,Ord,CodExt,CodInt, Produs,StocMin,StocMax' || gUserFields || ' )
  WITH PROGNOZA AS (
    SELECT
      NS.CODOBIECT, 0 CODCOMANDA, 0 CODCOMANDA1, 0 ORD,
      NULL TERMEN, ''Stoc la moment'' TIPTRANZ, NULL PREFIXDOC, 0 CANTIES, coalesce(SUM(REST),0) CANTIN,
      NULL OBS, NULL NRCOM, NULL DATACOM, NULL PRODUS, 0 CODPRODUS
    FROM NIRSTOC NS
      INNER JOIN NIR   N ON N.CODNIR  = NS.CODNIR
      INNER JOIN NGEST G ON G.CODGEST = N.GEST ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('G', 'CODSUBUNIT',NULL,NULL),'') || '
    WHERE 1 = 1 ' || coalesce(pkg_list_base_stocprognoza_FiltruObj('NS.CODOBIECT'),'') || coalesce(pkg_list_base_stocprognoza_FiltruGestStoc('N.GEST'),'')||sNeconforme|| '
    GROUP BY CODOBIECT
    UNION ALL
    SELECT
      CODOBIECT, CODCOMANDA, CODCOMANDA1,
      Row_NUMBER() OVER (PARTITION BY CODOBIECT ORDER BY coalesce(TERMEN, DATACOM)) ORD,
      TERMEN, TIPTRANZ, PREFIXDOC, CANTIES, CANTIN,
      OBS, NRCOM, DATACOM, PRODUS, CODPRODUS
    FROM (
      SELECT -- comenzi clienti / furnizori
        C1.CODOBIECT, C.CODCOMANDA, C1.CODCOMANDA1,
        C1.TERMEN TERMEN, pkg_list_base_utils_decode_tipdoc(C.TIPDOC) TIPTRANZ, C.PREFIXDOC PREFIXDOC,
        (case when C.TIPDOC=18 then RESTACCEPTAT else 0 end) CANTIES, (case when C.TIPDOC=8 then RESTACCEPTAT else 0 end) CANTIN,
        NPART.DEN_PART OBS, C.NRDOC NRCOM, C.DATADOC DATACOM, NULL PRODUS, 0 CODPRODUS
      FROM COMANDA1 C1
        INNER JOIN COMANDA C ON C.CODCOMANDA  = C1.CODCOMANDA
        INNER JOIN NPART     ON NPART.CODPART = C.PARTENER
      WHERE C.TIPDOC IN (8,18) AND C.OPERAT = 1 AND C.ANULAT = 0
        AND coalesce(C.INCHISA,0) = 0 AND C1.RESTACCEPTAT &lt;&gt; 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || coalesce(pkg_list_base_stocprognoza_FiltruObj('C1.CODOBIECT') ,'') || '
      UNION ALL
      SELECT -- comenzi catre subunitati
        C1.CODOBIECT, C.CODCOMANDA, C1.CODCOMANDA1,
        C1.TERMEN TERMEN, pkg_list_base_utils_decode_tipdoc(C.TIPDOC) TIPTRANZ, C.PREFIXDOC PREFIXDOC,
        0 CANTIES, RESTACCEPTAT CANTIN,
        S.DEN_SUBUNIT OBS, C.NRDOC NRCOM, C.DATADOC DATACOM, NULL PRODUS, 0 CODPRODUS
      FROM COMANDA1 C1
        INNER JOIN COMANDA  C ON C1.CodComanda = C.CodComanda
        INNER JOIN NSUBUNIT S ON S.CODSUBUNIT  = C.SUBUNITSURSA
      WHERE C.TIPDOC = 44 AND C.OPERAT = 1 AND C.ANULAT = 0
        AND coalesce(C.INCHISA,0) = 0 AND C1.RESTACCEPTAT &lt;&gt; 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || coalesce(pkg_list_base_stocprognoza_FiltruObj('C1.CODOBIECT'),'') || '
      UNION ALL
      SELECT -- comenzi de la subunitati
        C1.CODOBIECT, C.CODCOMANDA, C1.CODCOMANDA1,
        C1.TERMEN TERMEN, pkg_list_base_utils_decode_tipdoc(60) TIPTRANZ, C.PREFIXDOC PREFIXDOC,
        RESTACCEPTAT CANTIES, 0 CANTIN,
        S.DEN_SUBUNIT OBS, C.NRDOC NRCOM, C.DATADOC DATACOM, NULL PRODUS, 0 CODPRODUS
      FROM COMANDA1 C1
        INNER JOIN COMANDA  C ON C1.CodComanda = C.CodComanda
        INNER JOIN NSUBUNIT S ON S.CODSUBUNIT  = C.SUBUNITATEA
      WHERE C.TIPDOC = 44 AND C.OPERAT = 1 AND C.ANULAT = 0
        AND coalesce(C.INCHISA,0) = 0 AND C1.RESTACCEPTAT &lt;&gt; 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C', 'SubunitSursa',NULL,NULL),'') || coalesce(pkg_list_base_stocprognoza_FiltruObj('C1.CODOBIECT'),'') || '
      UNION ALL
      SELECT -- comenzi gestiuni
        C1.CODOBIECT, C.CODCOMANDA, C1.CODCOMANDA1,
        C1.TERMEN TERMEN, pkg_list_base_utils_decode_tipdoc(C.TIPDOC) TIPTRANZ, C.PREFIXDOC PREFIXDOC,
        RESTACCEPTAT CANTIES, 0 CANTIN,
        G.DEN_GEST OBS, C.NRDOC NRCOM, C.DATADOC DATACOM, NULL PRODUS, 0 CODPRODUS
      FROM COMANDA1 C1
        INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
        INNER JOIN NGEST   G ON G.CodGest     = C.CodGest
      WHERE C.TIPDOC = 43 AND C.OPERAT = 1 AND C.ANULAT = 0 AND coalesce(G.Tip,0) = 1
        AND coalesce(C.INCHISA,0) = 0 AND C1.RESTACCEPTAT &lt;&gt; 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || coalesce(pkg_list_base_stocprognoza_FiltruObj('C1.CODOBIECT'),'') || '
      UNION ALL
      SELECT -- comenzi interne intrare
        CMDMAT.CodObiect, C.CODCOMANDA, C1.CODCOMANDA1,
        C1.TERMEN TERMEN, pkg_list_base_utils_decode_tipdoc(C.TIPDOC) TIPTRANZ, C.PREFIXDOC PREFIXDOC,
        0 CANTIES, CMDMAT.Rest CANTIN,
        G.DEN_GEST OBS, C.NRDOC NRCOM, C.DATADOC DATACOM, O.DENUMIRE PRODUS, O.CODOBIECT
      FROM CMDPRODMAT CMDMAT
        INNER JOIN COMANDA1 C1 ON CMDMAT.CodComanda1 = C1.CodComanda1
        INNER JOIN COMANDA  C  ON C1.CodComanda      = C.CodComanda
        INNER JOIN NARTOBJ  O  ON O.CODOBIECT        = C1.CODOBIECT
        LEFT  JOIN NGEST    G  ON G.CodGest          = C.CodGest
      WHERE C.TIPDOC = 53 AND C.OPERAT = 1 AND C.ANULAT = 0 AND NVL(C.INCHISA,0) = 0 AND CMDMAT.REST &gt; 0
        AND ((C1.Consum = 1 AND CMDMAT.Tip &lt;&gt; 1) OR (C1.Consum = 2 AND CMDMAT.Tip = 2)) ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || coalesce(pkg_list_base_stocprognoza_FiltruObj('CMDMAT.CODOBIECT'),'') || '
      UNION ALL
      SELECT -- comenzi interne iesire
        CMDMAT.CodObiect, C.CODCOMANDA, C1.CODCOMANDA1,
        C1.TERMEN TERMEN, pkg_list_base_utils_decode_tipdoc(C.TIPDOC) TIPTRANZ, C.PREFIXDOC PREFIXDOC,
        CMDMAT.Rest CANTIES, 0 CANTIN,
        G.DEN_GEST OBS, C.NRDOC NRCOM, C.DATADOC DATACOM, O.DENUMIRE PRODUS, O.CODOBIECT
      FROM CMDPRODMAT CMDMAT
        INNER JOIN COMANDA1 C1 ON CMDMAT.CodComanda1 = C1.CodComanda1
        INNER JOIN COMANDA  C  ON C1.CodComanda      = C.CodComanda
        INNER JOIN NARTOBJ  O  ON O.CODOBIECT        = C1.CODOBIECT
        INNER JOIN CMDPRODMAT PROD ON PROD.CODCOMANDA1 = C1.CODCOMANDA1 AND PROD.TIP = 0
        LEFT  JOIN NGEST    G  ON G.CodGest          = C.CodGest
      WHERE C.TIPDOC = 53 AND C.OPERAT = 1 AND C.ANULAT = 0 AND NVL(C.INCHISA,0) = 0 AND PROD.REST &gt; 0 and CMDMAT.REST &gt; 0
        AND ((C1.Consum = 1 AND CMDMAT.Tip = 1) OR (C1.Consum = 2 AND CMDMAT.Tip &lt;&gt; 2)) ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || coalesce(pkg_list_base_stocprognoza_FiltruObj('CMDMAT.CODOBIECT'),'') || '
    ) A_PG
  )
  ,PROGNOZA1 AS (SELECT a.*, row_number() over() ROWNUM FROM PROGNOZA A)  --aa: adaugat col.ROWNUM
  SELECT NAO.DENUMIRE, NUM.DEN_UM, P.TERMEN, P.TIPTRANZ, case when P.CANTIN &lt; 0 then 0 else P.CANTIN end, case when P.CANTIES &lt; 0 then 0 else P.CANTIES end,
    SUM(case when P.CANTIN &lt; 0 then 0 else P.CANTIN end - case when P.CANTIES &lt; 0 then 0 else P.CANTIES end) OVER(PARTITION BY P.CODOBIECT ORDER BY P.ORD,ROWNUM) STOC,
    P.OBS, P.PREFIXDOC, P.NRCOM, P.DATACOM, P.ORD, NAO.CodExtern, NAO.CodIntern,P.PRODUS' || sColMinMax || gUserAlias || '
  FROM PROGNOZA1 P  --aa: in loc de PROGNOZA
    INNER JOIN NARTOBJ        NAO  ON NAO.CODOBIECT  = P.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(getSUBUNITATE()::varchar,'') || '
    LEFT  JOIN NUM                 ON NUM.CODUM      = NA.UM
    LEFT  JOIN NARTOBJ        POBJ ON POBJ.CODOBIECT = P.CODPRODUS
    LEFT  JOIN NCLASEA        CLS  ON CLS.CODCLASEA  = NA.CLASA' || gSuplJoins || '
  WHERE NA.TIPARTICOL = 0::varchar';

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocrezerv_processlist</obj_name>
  <obj_hashval>4d8a960c9285893bc6991c12375d293d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocrezerv_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 nao, nart a, num1 num1, npart np, npart prod, npers npe, nirstoc ns, rezervats r';
   gUserFields   VARCHAR := '';
  gUserAlias    VARCHAR := '';
  gNullAlias    VARCHAR := '';
  gSuplJoins    VARCHAR := '';
  btoateart      BOOLEAN;
BEGIN
  --Adina 09.04.2021 - alstart,alstop
  --Adina 27 august 2020
  btoateart := current_setting('PKG_LIST_BASE_STOCREZERV.vToateArt', true)::boolean;

  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, '', '', '',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_STOCREZERV.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  CALL PRC_AL_CHECK('ioart1',0);

  sInsert :=
  'INSERT INTO ' || tmpName || '(
    PART ,NRDOC, DATADOC, ART, ARTCOM, CANT, PRET, VALOARE,
    REZERVAT, STOC ,TERMEN,
    AGENT, CODEXTERN, CODINTERN, PROD, CANTUM1, UM1, SERIE' || gUserFields || ' )
  WITH STOCART AS (
    SELECT NS.CODOBIECT, SUM(NS.REST) STOC
    FROM NIRSTOC NS
      INNER JOIN IOART1 IOA ON IOA.CODIOART = NS.CODIOART AND ' || coalesce(getAnLunaLucru()::varchar,'') || ' BETWEEN IOA.ALStart and IOA.ALStop
      INNER JOIN NIR    N   ON N.CODNIR     = NS.CODNIR
      INNER JOIN NGEST  NG  ON NG.CODGEST   = N.GEST
    WHERE IOA.MG &lt;&gt; 5 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG', 'CODSUBUNIT',NULL,NULL)::varchar ,'');

  IF  NOT btoateart THEN
    sInsert := coalesce(sInsert,'') || '
      AND NS.CODOBIECT::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')';
  END IF;

  sInsert := sInsert || '
    GROUP BY CODOBIECT)
  SELECT
    (case C.TipDoc when 44 then NSU.Den_Subunit  when 53 then NG.Den_Gest else NP.Den_Part end) BENEFICIAR,
    C.NRDOC, C.DATADOC, NAOR.DENUMIRE, NAO.DENUMIRE, C1.RESTACCEPTAT CANT, C1.PU PRET, (C1.RESTACCEPTAT * C1.PU) VALOARE,
    R.REST REZERVAT, SA.STOC , C1.TERMEN,
    (NPE.NUME || ''  ''||NPE.PRENUME) AGENT, NAO.CODEXTERN, NAO.CODINTERN, PROD.DEN_PART, C1.CANTUM1, U1.DEN_UM, S.SERIE' || gUserAlias || '
  FROM REZERVATS R
    INNER JOIN COMANDA1 C1   ON C1.CODCOMANDA1 = R.CODCOMANDA1
    INNER JOIN COMANDA  C    ON C.CODCOMANDA   = C1.CODCOMANDA
    INNER JOIN NIRSTOC  NS   ON NS.CODNIRSTOC  = R.CODNIRSTOC
    LEFT  JOIN NARTOBJ  NAOR ON NAOR.CODOBIECT = NS.CODOBIECT
    LEFT  JOIN NARTOBJ  NAO  ON NAO.CODOBIECT  = C1.CODOBIECT
    LEFT  JOIN NART     A    ON A.CODARTICOL   = NAOR.CODARTICOL
    LEFT  JOIN NUM1          ON NUM1.CODUM1    = C1.UMSEC
    LEFT  JOIN NUM      U1   ON U1.CODUM       = A.UM1
    LEFT  JOIN NPART    NP   ON NP.CODPART     = C.PARTENER
    LEFT  JOIN NSUBUNIT NSU  ON NSU.CODSUBUNIT = C.SUBUNITATEA
    LEFT  JOIN NGEST    NG   ON NG.CODGEST     = C.CODGEST
    LEFT  JOIN NPART    PROD ON PROD.CODPART   = NAOR.CODPRODUCATOR
    LEFT  JOIN STOCART  SA   ON SA.CODOBIECT   = NAOR.CODOBIECT
    LEFT  JOIN NPERS    NPE  ON NPE.CODPERS    = C.AGENT
    LEFT  JOIN NIRSER   NSER ON NSER.CODNIRSER = R.CODNIRSER
    LEFT  JOIN NSERII   S    ON S.CODSERIE     = NSER.CODSERIE' || gSuplJoins || '
  WHERE R.REST &gt; 0 AND R.CODNIRSTOC &gt; 0 AND coalesce(R.CODOBIECT, 0) = 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('', '(case when C.TipDoc=44 then c.subunitsursa else c.subunitatea end)',NULL,NULL)::varchar ,'');

  IF  NOT btoateart THEN
    sInsert := coalesce(sInsert,'') || '
      AND NS.CODOBIECT::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')';
  END IF;

  sInsert := sInsert || '
  UNION ALL
  SELECT
    (case C.TipDoc when 44 then NSU.Den_Subunit  when 53 then NG.Den_Gest else NP.Den_Part end) BENEFICIAR,
    C.NRDOC, C.DATADOC, NAOR.DENUMIRE, NAO.DENUMIRE, C1.RESTACCEPTAT CANT, C1.PU PRET, (C1.RESTACCEPTAT * C1.PU) VALOARE,
    R.REST REZERVAT, SA.STOC , C1.TERMEN,
    (NPE.NUME || ''  ''||NPE.PRENUME) AGENT, NAOR.CODEXTERN, NAOR.CODINTERN, PROD.DEN_PART, C1.CANTUM1, U1.DEN_UM, S.SERIE' || gUserAlias || '
  FROM REZERVATS R
    INNER JOIN COMANDA1 C1   ON C1.CODCOMANDA1 = R.CODCOMANDA1
    INNER JOIN COMANDA  C    ON C.CODCOMANDA   = C1.CODCOMANDA
    INNER JOIN NIRSTOC  NS   ON NS.CODNIRSTOC  = R.CODNIRSTOC
    LEFT  JOIN NARTOBJ  NAOR ON NAOR.CODOBIECT = R.CODOBIECT
    LEFT  JOIN NARTOBJ  NAO  ON NAO.CODOBIECT  = C1.CODOBIECT
    LEFT  JOIN NART     A    ON A.CODARTICOL   = NAOR.CODARTICOL
    LEFT  JOIN NUM1          ON NUM1.CODUM1    = C1.UMSEC
    LEFT  JOIN NUM      U1   ON U1.CODUM       = A.UM1
    LEFT  JOIN NPART    NP   ON NP.CODPART     = C.PARTENER
    LEFT  JOIN NSUBUNIT NSU  ON NSU.CODSUBUNIT = C.SUBUNITATEA
    LEFT  JOIN NGEST    NG   ON NG.CODGEST     = C.CODGEST
    LEFT  JOIN NPART    PROD ON PROD.CODPART   = NAOR.CODPRODUCATOR
    LEFT  JOIN STOCART  SA   ON SA.CODOBIECT   = R.CODOBIECT
    LEFT  JOIN NPERS    NPE  ON NPE.CODPERS    = C.AGENT
    LEFT  JOIN NIRSER   NSER ON NSER.CODNIRSER = R.CODNIRSER
    LEFT  JOIN NSERII   S    ON S.CODSERIE     = NSER.CODSERIE' || gSuplJoins || '
  WHERE R.REST &gt; 0 AND coalesce(R.CODOBIECT, 0) &gt; 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('', '(case when C.TipDoc=44 then c.subunitsursa else c.subunitatea end)',NULL,NULL)::varchar ,'');

  IF  NOT btoateart THEN
    sInsert := coalesce(sInsert,'') || 'AND R.CODOBIECT::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')';
  END IF;

  sInsert := sInsert || '
  UNION ALL
  SELECT
    NG.Den_Gest,
    I.NRINVENTAR, I.DATAINVENTAR, NAOR.DENUMIRE, NAO.DENUMIRE, I1.FAPTIC, NS.PRET, (R.REST * NS.PRET) VALOARE,
    R.REST REZERVAT, SA.STOC , NULL TERMEN,
    (NPE.NUME || ''  ''||NPE.PRENUME) AGENT, NAOR.CODEXTERN, NAOR.CODINTERN, PROD.DEN_PART, 0, U1.DEN_UM, S.SERIE' || gUserAlias || '
  FROM REZERVATS R
    INNER JOIN INVENTAR1 I1   ON I1.CODINVENTAR1 = R.CODINVENTAR1
    INNER JOIN INVENTAR  I    ON I.CODINVENTAR   = I1.CODINVENTAR
    INNER JOIN NIRSTOC   NS   ON NS.CODNIRSTOC   = R.CODNIRSTOC
    INNER JOIN NPERS     NPE  ON NPE.CODPERS     = I.RESPONSABIL
    LEFT  JOIN NARTOBJ   NAOR ON NAOR.CODOBIECT  = NS.CODOBIECT
    LEFT  JOIN NARTOBJ   NAO  ON NAO.CODOBIECT   = NS.CODOBIECT
    LEFT  JOIN NART      A    ON A.CODARTICOL    = NAOR.CODARTICOL
    LEFT  JOIN NUM1           ON NUM1.CODUM1     = NS.UMSEC
    LEFT  JOIN NUM       U1   ON U1.CODUM        = A.UM1
    LEFT  JOIN NSUBUNIT  NSU  ON NSU.CODSUBUNIT  = I.SUBUNITATE
    LEFT  JOIN NGEST     NG   ON NG.CODGEST      = I.GESTIUNE
    LEFT  JOIN NPART     PROD ON PROD.CODPART    = NAOR.CODPRODUCATOR
    LEFT  JOIN STOCART   SA   ON SA.CODOBIECT    = R.CODOBIECT
    LEFT  JOIN NIRSER    NSER ON NSER.CODNIRSER  = R.CODNIRSER
    LEFT  JOIN NSERII    S    ON S.CODSERIE      = NSER.CODSERIE
    LEFT  JOIN COMANDA1  C1   ON C1.CODCOMANDA1  = R.CODCOMANDA1
    LEFT  JOIN COMANDA   C    ON C.CODCOMANDA    = C1.CODCOMANDA ' || gSuplJoins || '
  WHERE R.REST &gt; 0 AND coalesce(R.CODINVENTAR1, 0) &gt; 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('', 'I.SUBUNITATE',NULL,NULL),'');

  IF  NOT btoateart THEN
    sInsert := sInsert || 'AND NS.CODOBIECT::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')';
  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_stocvitrot_processlist</obj_name>
  <obj_hashval>27e584edde0e1167b5975d82c8ac3102</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocvitrot_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sWith           varchar := '';
  sWithSel1       varchar := '';
  sSelect         varchar := '';
  vPerioada       varchar := '';
  vFiltre         varchar := '';
  vCondVanz       varchar := '16,19,20,21,22';
  vJoinLivr       varchar := '';
  sNrZile         varchar := '';
  sLast           varchar := '';
  sJoinLM         varchar := '';
  gSuplCols       VARCHAR := 'NARTOBJ NAO, NART NA, NUM NUM, NGEST NG, IOART I, NCLASEA CA, NPART PRO, NPART FURN, NSUBUNIT SUB';
  gUserFields     VARCHAR := '';
  gUserAlias      VARCHAR := '';
  gNullAlias      VARCHAR := '';
  gSuplJoins      VARCHAR := '';
  vAnual          BOOLEAN := current_setting('PKG_LIST_BASE_STOCVITROT.vAnual'     , true)::boolean;
  vAvizeSub       BOOLEAN := current_setting('PKG_LIST_BASE_STOCVITROT.vAvizeSub'  , true)::boolean;
  vTransfVal      BOOLEAN := current_setting('PKG_LIST_BASE_STOCVITROT.vTransfVal' , true)::boolean;
  vIesConsum      BOOLEAN := current_setting('PKG_LIST_BASE_STOCVITROT.vIesConsum' , true)::boolean;
  vToateArt       BOOLEAN := current_setting('PKG_LIST_BASE_STOCVITROT.vToateArt'  , true)::boolean;
  vToateGest      BOOLEAN := current_setting('PKG_LIST_BASE_STOCVITROT.vToateGest' , true)::boolean;
  vToateIOArt     BOOLEAN := current_setting('PKG_LIST_BASE_STOCVITROT.vToateIOArt', true)::boolean;
  vCentr          BOOLEAN := current_setting('PKG_LIST_BASE_STOCVITROT.vCentr'     , true)::boolean;
  vData1          DATE    := to_date(current_setting('PKG_LIST_BASE_STOCVITROT.vData1',   true),'dd.mm.yyyy');
  vDataIni        DATE    := to_date(current_setting('PKG_LIST_BASE_STOCVITROT.vDataIni', true),'dd.mm.yyyy');
  vDataFin        DATE    := to_date(current_setting('PKG_LIST_BASE_STOCVITROT.vDataFin', true),'dd.mm.yyyy');
  sDataIni        VARCHAR(100) := 'To_Date('''||To_Char(vDataIni, 'dd.mm.yyyy')||''', ''dd.mm.yyyy'')';
  sDataFin        VARCHAR(100) := 'To_Date('''||To_Char(vDataFin, 'dd.mm.yyyy')||''', ''dd.mm.yyyy'')';
  sData1          VARCHAR(100) := 'To_Date('''||To_Char(vData1,   'dd.mm.yyyy')||''', ''dd.mm.yyyy'')';
BEGIN
  --Florin 17.11.2022 - fixat 56297
  --Florin 17.11.2022 - sinc. Oracle
  --Florin 23.06.2022 - sinc. Oracle
  --Florin 30.06.2021 - fixat 50692
  --Adina 09.04.2021 - alstart,alstop
  --Adina 04 septembrie 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_STOCVITROT.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  CALL PRC_AL_CHECK('ioart1',0);

  IF  NOT vToateArt THEN
    vFiltre := coalesce(vFiltre,'') || '
          AND NS.CODOBIECT::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'') ';
  END IF;

  IF  NOT vToateGest THEN
    vFiltre := coalesce(vFiltre,'') || '
          AND N.GEST::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
  END IF;

  IF  NOT vToateIOArt THEN
    vFiltre := coalesce(vFiltre,'') || '
          AND NS.CODIOART::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
  END IF;

  IF vAnual THEN
    sNrZile := '365';
  ELSE
    sNrZile := (vDataFin - vDataIni + 1)::varchar;
  END IF;

  IF  vData1 = vDataFin
    THEN vPerioada := '= '||sDataFin;
    ELSE vPerioada := 'BETWEEN '||sData1||' AND '||sDataFin;
  END IF;

  IF vAvizeSub THEN
    vCondVanz := vCondVanz || ',23';
  END IF;

  IF vIesConsum THEN
    vCondVanz := coalesce(vCondVanz,'') || ',24';
  END IF;

  vCondVanz := 'L.TIPLIVR IN (' || vCondVanz || ')';

  IF vTransfVal THEN
    vCondVanz := '(' || vCondVanz || ' OR (L.TIPLIVR = 12 AND coalesce(IOAD.MG,0) = 5))';
    vJoinLivr := '
          LEFT JOIN NIRSTOC NSD ON NSD.CODLIVR1  = L1.CODLIVR1
          LEFT JOIN IOART1 IOAD ON IOAD.CODIOART = NSD.CODIOART';
  END IF;

  sLast := '';
  sJoinLM := '';
  sInsert :=
  'INSERT INTO ' || tmpName || ' (
    Art, UM, Gest, IoArt, StocIni, StocFin, PretAchiz, IesTot,
    DenClasaA, CodIntern, CodExtern, Producator, Furnizor, ZilePer, VMRot, Subunitatea, ZileStoc';

   sWith :='
  WITH ';

  sWithSel1 := '
      SELECT
        CODOBIECT, GEST, CODIOART, PACHIZ, coalesce(FURN,0) FURN, Sum(STOCINI) StocIni, Sum(STOCFIN) StocFin, Sum(VANZARI) Vanzari,
        TRUNC(Least('||sDataFin||', MAX(Coalesce(DATALASTLIVR, '||sDataFin||'))) - Min(Coalesce(DATAACHIZ,'||sDataFin||'))) ZILESTOC
      FROM (
        SELECT
          NS.CODOBIECT, N.GEST, NS.CODIOART, NS.PRET-NS.ADAOS PACHIZ, NS.FURN,
          NL.REST STOCINI, NL.REST STOCFIN, 0 VANZARI,
          NS.DATAACHIZ,
          CASE
            WHEN NS.REST = 0
            THEN (SELECT MAX(LX.DATALIVR) FROM LIVR LX INNER JOIN LIVR1 LX1 ON LX.CODLIVR = LX1.CODLIVR WHERE LX1.CODNIRSTOC = NS.CODNIRSTOC)
            ELSE '||sDataFin||'
          END DATALASTLIVR
        FROM NIRLUNA NL
          INNER JOIN NIRSTOC NS  ON NS.CODNIRSTOC = NL.CODNIRSTOC
          INNER JOIN NIR     N   ON N.CODNIR      = NS.CODNIR
          INNER JOIN NGEST   NG  ON NG.CODGEST    = N.GEST '||coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG', 'CODSUBUNIT',NULL,NULL),'') || '
          INNER JOIN IOART1  IOA ON IOA.CODIOART  = NS.CODIOART AND '||getAnLunaLucru()::varchar||' BETWEEN IOA.ALStart and IOA.ALStop
        WHERE NL.AN = '||EXTRACT(YEAR FROM (vData1 - 1))||' AND NL.LUNA = '||EXTRACT(MONTH FROM (vData1 - 1))||'
          AND IOA.MG &lt;&gt; 5 '||vFiltre||'
        UNION ALL
        SELECT
          NS.CODOBIECT, N.GEST, NS.CODIOART, NS.PRET-NS.ADAOS PACHIZ, NS.FURN,
          CASE WHEN N.DATANIR &lt; '||sDataIni||' THEN CANTNIR ELSE 0 END STOCINI, CANTNIR STOCFIN, 0 VANZARI,
          NS.DATAACHIZ,
          CASE
            WHEN NS.REST = 0
            THEN (SELECT MAX(LX.DATALIVR) FROM LIVR LX INNER JOIN LIVR1 LX1 ON LX.CODLIVR = LX1.CODLIVR WHERE LX1.CODNIRSTOC = NS.CODNIRSTOC)
            ELSE '||sDataFin||'
          END DATALASTLIVR
        FROM NIRSTOC NS
          INNER JOIN NIR    N   ON N.CODNIR     = NS.CODNIR
          INNER JOIN NGEST  NG  ON NG.CODGEST   = N.GEST '||coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG', 'CODSUBUNIT',NULL,NULL),'') || '
          INNER JOIN IOART1 IOA ON IOA.CODIOART = NS.CODIOART AND '||getAnLunaLucru()::varchar||' BETWEEN IOA.ALStart and IOA.ALStop
        WHERE N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 12, 13) AND  N.ANULAT = 0 AND N.OPERAT = 1
          AND N.DATANIR '||vPerioada||'
          AND IOA.MG &lt;&gt; 5 '||vFiltre||'
        UNION ALL
        SELECT
          NS.CODOBIECT, N.GEST, NS.CODIOART, NS.PRET-NS.ADAOS PACHIZ, NS.FURN,
          CASE WHEN L.DATALIVR &lt; '||sDataIni||' THEN L1.CANT ELSE 0 END * (case when L.TIPLIVR=15 then 1 else -1 end) STOCINI, L1.CANT * (case when L.TIPLIVR=15 then 1 else -1 end) STOCFIN,
          CASE WHEN L.DATALIVR &gt;= '||sDataIni||' AND '||vCondVanz||' THEN L1.CANT ELSE 0 END VANZARI,
          NS.DATAACHIZ,
          NS.DATAACHIZ DATALASTLIVR
        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   NG  ON NG.CODGEST    = N.GEST '|| coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG', 'CODSUBUNIT',NULL,NULL),'') || '
          INNER JOIN IOART1  IOA ON IOA.CODIOART  = NS.CODIOART AND '||GETAnLunaLucru()::varchar||' BETWEEN IOA.ALStart and IOA.ALStop '
          ||vJoinLivr||'
        WHERE L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15 ,16, 19, 20, 21, 23, 24) AND L.OPERAT = 1 AND L.ANULAT = 0
          AND L.DATALIVR '||vPerioada||'
          AND IOA.MG &lt;&gt; 5 '||vFiltre||'
      ) a_pg
      GROUP BY CODOBIECT, GEST, CODIOART, PACHIZ, coalesce(FURN,0)';


  if vCentr then
    --insert into x(test) values('centralizare');
    sInsert := sInsert||',Last_furn,Last_DataAchiz,Last_PretAchiz';
    sWith := sWith ||'
    S AS (
      SELECT CODOBIECT, 0 GEST, 0 CODIOART, SUM(PACHIZ)/SUM(1) PACHIZ, 0 FURN, Sum(STOCINI) StocIni, Sum(STOCFIN) StocFin, Sum(VANZARI) Vanzari, max(zilestoc) zilestoc
      FROM ('||
      sWithSel1||'
      ) a_pg
      GROUP BY CODOBIECT
    ),
    LM AS (
      SELECT
       NS.CODOBIECT,
       (array_remove(array_agg(P.DEN_PART ORDER BY N.DATANIR DESC, N.CODNIR DESC), null))[1] AS LAST_FURN,  --AA= 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(PKG_LIST_BASE_UTILS_COND_SUBUNIT('G', 'CODSUBUNIT',NULL,NULL),'') || '
        GROUP BY NS.CODOBIECT  --AA= am scos DISTINCT-ul si partition by si am pus aici group by
        )';
    sLast := ',LM.LAST_FURN,LM.LAST_DATAACHIZ,LM.LAST_PRETACHIZ';
    sJoinLM := CHR(13)||'LEFT JOIN LM ON LM.CODOBIECT = S.CODOBIECT'||CHR(13);
  ELSE
    --insert into x(test) values('necentralizare');
    sWith := sWith ||'
    S AS ('||
      sWithSel1||'
    )';
  END IF;
  sInsert := sInsert||gUserFields||')';
  sSelect := '
  SELECT
    NAO.DENUMIRE, NUM.DEN_UM, NG.DEN_GEST, I.DEN_IOART, S.STOCINI, S.STOCFIN, S.PACHIZ, S.VANZARI,
    CA.DEN_CLASEA, NAO.CODINTERN, NAO.CODEXTERN, PROD.DEN_PART, FURN.DEN_PART, '||sNrZile||',
    CASE
      WHEN S.VANZARI = 0 THEN 0
      ELSE (S.STOCINI+S.STOCFIN)/2/S.VANZARI*'||sNrZile||'
    END,
    SUB.DEN_SUBUNIT, S.ZILESTOC '||sLast||gUserAlias||'
  FROM 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 NGEST    NG   ON NG.CODGEST     = S.GEST
    LEFT  JOIN IOART    I    ON I.CODIOART     = S.CODIOART
    LEFT  JOIN NCLASEA  CA   ON CA.CODCLASEA   = NA.CLASA
    LEFT  JOIN NPART    PROD ON PROD.CODPART   = NAO.CODPRODUCATOR
    LEFT  JOIN NPART    FURN ON FURN.CODPART   = S.FURN
    LEFT  JOIN NSUBUNIT SUB  ON SUB.CODSUBUNIT = NG.CODSUBUNIT'||sJoinLM||gSuplJoins;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_tehprod_make_mat</obj_name>
  <obj_hashval>2c461bef86cbe845ebc15c77fce60de0</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_tehprod_make_mat()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_rec record;
BEGIN
  --Florin 01.03.2023 - sinc. Oracle (28.02.2023)
  delete FROM manevra_prodcomp_clona;
  for v_rec in (select pc.codprodcomp
                from prodcomp pc
                where not exists (select mat.codobiect from prodmat mat where mat.codobiect = pc.codobiect)
                      and pc.implicit = 1 and coalesce(pc.inactiv,0) = 0
                ) loop
    PERFORM pkg_list_base_tehprod_make_mat1(v_rec.codprodcomp, v_rec.codprodcomp);
  end loop;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_tehprod_processlist</obj_name>
  <obj_hashval>aca375c357b3269d14b5194baf8059c1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_tehprod_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 := '';

  V_REC       RECORD;
  sInsert     varchar;
  sWith       varchar;
  sSelect     varchar;
  AnLunaLucru numeric;
  VUSERID     numeric;
BEGIN
  --Adina 27.04.2021 - alstart,alstop
  --Adina 19.04.2021 - sinc.Oracle - doar la zi
  --Bogdan 14.09.2020
  VUSERID := current_setting ('PKG_GLOBALS.USERID', true) ::numeric;
  IF current_setting ('PKG_LIST_BASE_TEHPROD.p_Sursa', true) ::numeric &lt;&gt; 2 then
      gSuplCols := 'prodmat mat,prodcomp pc,nartobj parinte, nartobj comp, num ump, num umc, nclasea clsp, nclasea clsc, nart artc, nart artp,NARTOBJ1  P1, NARTOBJ1  C1, NARTOBJ1 Par1, nartobjsubunit comps, nartobjsubunit prods';
  else
    gSuplCols := 'prodmat mat,prodcomp pc,nartobj nodp, nartobj comp,num ump,num umc,nclasea clsp,nclasea clsc,nart artc,nart artp,NARTOBJ1 P1,NARTOBJ1 C1, nartobjsubunit comps, nartobjsubunit prods';
  END IF;

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJEXT', 'OEXTP', 'OEXT.CODOBIECT = PARINTE.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJATR', 'OATRP', 'OATR.CODOBIECT = PARINTE.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJEXT', 'OEXTC', 'OEXT.CODOBIECT = COMP.CODOBIECT'   ,NULL);
  call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJATR', 'OATRC', 'OATR.CODOBIECT = COMP.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_TEHPROD.gSuplCols',gSuplCols,false);

  CALL PRC_AL_CHECK('tarifeman1',0);
  CALL PRC_AL_CHECK('nartobj1',0);

  AnLunaLucru := getAnLucru() * 12 + getLunaLucru();

  IF current_setting ('PKG_LIST_BASE_TEHPROD.p_flgAllArt', true) ::numeric = 1 THEN
    DELETE FROM tmp_prodcomp;
    DELETE FROM tmp_proiectnod;

    IF current_setting ('PKG_LIST_BASE_TEHPROD.p_Sursa', true) ::numeric = 0 THEN
      INSERT INTO tmp_prodcomp (codprodcomp, cant, pret)
      (SELECT PC.codprodcomp, PC.cant, PC.Pret
       FROM prodcomp PC
       WHERE COALESCE (pc.inactiv, 0) = 0 and coalesce (pc.ascuns, 0) = 0);
    ELSE
      IF current_setting ('PKG_LIST_BASE_TEHPROD.p_Sursa', true) ::numeric = 1 THEN
        INSERT INTO tmp_proiectnod (codproiectnod, necesar, cant, codobiect, codproiect)
        SELECT pn.codproiectnod, pn.cant, pn.cant, pn.codobiect, pn.codproiect
        FROM proiectnod pn INNER JOIN proiect p ON pn.codproiect = p.codproiect
        WHERE COALESCE (pn.nodoriginal, 0) = 0 and p.activ = 1 and coalesce (p.ascuns, 0) = 0;
      ELSE
        INSERT INTO tmp_prodcomp (codprodcomp, codobiect, cant)
        SELECT pc.codprodcomp, pc.codobiect, pc.cant
        FROM prodcomp pc INNER JOIN nartobj obj ON obj.codobiect = pc.codobiect
        WHERE COALESCE (pc.inactiv, 0) = 0 and coalesce (pc.ascuns, 0) = 0
        ORDER BY obj.denumire;
      END IF;
    END IF;
  ELSE
    DELETE FROM tmp_prodcomp;
    DELETE FROM tmp_proiectnod;

    IF current_setting ('PKG_LIST_BASE_TEHPROD.p_Sursa', true) ::numeric = 0 THEN
      INSERT INTO tmp_prodcomp (codprodcomp, cant, pret, codobiect)
      (SELECT PC.codprodcomp, man.cant, man.Pret, pc.codobiect
       FROM prodcomp PC
            INNER JOIN tmp_prodcomp_man man ON man.codprodcomp = pc.codprodcomp and man.userid = current_setting ('PKG_GLOBALS.USERID', true) ::numeric);
    ELSE
      IF current_setting ('PKG_LIST_BASE_TEHPROD.p_Sursa', true) ::numeric = 1 THEN
        INSERT INTO tmp_proiectnod (codproiectnod, necesar, cant, codobiect, codproiect)
        SELECT pn.codproiectnod, man.necesar, man.cant, pn.codobiect, pn.codproiect
        FROM proiectnod  pn
          INNER JOIN tmp_proiectnod_man man ON man.codproiectnod = pn.codproiectnod and man.userid = current_setting ('PKG_GLOBALS.USERID', true) ::numeric
        WHERE COALESCE (pn.nodoriginal, 0) = 0;
      ELSE
        INSERT INTO tmp_prodcomp (codprodcomp, codobiect, cant, pret)
        SELECT pc.codprodcomp, pc.codobiect, man.cant, man.pret
        FROM prodcomp                 pc
          INNER JOIN nartobj          obj ON obj.codobiect   = pc.codobiect
          INNER JOIN tmp_prodcomp_man man ON man.codprodcomp = pc.codprodcomp and man.userid = current_setting ('PKG_GLOBALS.USERID', true) ::numeric
        ORDER BY obj.denumire;
      END IF;
    END IF;
  END IF;

  IF current_setting ('PKG_LIST_BASE_TEHPROD.p_Sursa', true) ::numeric = 0 THEN
    FOR v_rec IN (SELECT codprodcomp FROM tmp_prodcomp) LOOP
      UPDATE tmp_prodcomp tmp
      SET totalprod = (SELECT sum (mat.valmat + man.valman)
                       FROM prodcomp pc
                            LEFT JOIN (SELECT sum (COALESCE (mat.pret, 0) * COALESCE (mat.cant, 0)) * COALESCE (pg.coefmat, COALESCE (g.coefcheltmat, 0)) VALMAT,
                                              mat.codprodgest, mat.codprodcomp
                                       FROM prodmat            mat
                                            LEFT JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                                            LEFT JOIN ngest    g  ON g.codgest       = pg.codgest
                                       GROUP BY mat.codprodgest, mat.codprodcomp, g.coefcheltmat, pg.coefmat
                                      )  mat ON mat.codprodcomp = pc.codprodcomp
                            LEFT JOIN (SELECT sum (COALESCE (pm.tu, 0) * COALESCE (t.tarif, 0)) * COALESCE (pg.coefman, COALESCE (g.coefcheltman, 0)) VALMAN,
                                              pm.codprodgest, pm.codprodcomp
                                       FROM prodman            pm
                                            LEFT JOIN prodgest pg ON pm.codprodgest = pg.codprodgest
                                            LEFT JOIN ngest    g  ON g.codgest      = pg.codgest
                                            LEFT JOIN (SELECT T1.codtarif, T1.Tarif, t.denumire
                                                       FROM TARIFEMAN1 T1 INNER JOIN tarifeman t ON t1.codtarif = t.codtarif AND AnLunaLucru BETWEEN T1.ALStart AND T1.ALStop
                                                      ) T ON PM.CODTARIF = T.CODTARIF
                                       GROUP BY pm.codprodgest, pm.codprodcomp, g.coefcheltman, pg.coefman
                                      ) man ON man.codprodcomp = pc.codprodcomp
                       WHERE v_rec.codprodcomp = pc.codprodcomp
                      )
      WHERE tmp.codprodcomp = v_rec.codprodcomp;
    END LOOP;
  ELSE
    IF current_setting ('PKG_LIST_BASE_TEHPROD.p_Sursa', true) ::numeric = 1 THEN
      INSERT INTO tmp_prodcomp (codprodcomp)
      SELECT  DISTINCT          pn.codreteta
      FROM tmp_proiectnod       tmp
        INNER JOIN proiectnod pn ON tmp.codproiect = pn.codproiect
        INNER JOIN prodcomp   pc ON pn.codreteta   = pc.codprodcomp;

      FOR v_rec IN (SELECT codprodcomp FROM tmp_prodcomp) LOOP
        UPDATE tmp_prodcomp tmp
        SET totalprod = (SELECT sum (mat.valmat + man.valman)
                         FROM prodcomp pc
                              LEFT JOIN (SELECT sum (COALESCE (mat.pret, 0) * COALESCE (mat.cant, 0)) * COALESCE (pg.coefmat, COALESCE (g.coefcheltmat, 0)) VALMAT,
                                                mat.codprodgest, mat.codprodcomp
                                         FROM prodmat           mat
                                              LEFT JOIN prodgest pg ON mat.codprodgest = pg.codprodgest
                                              LEFT JOIN ngest    g  ON g.codgest       = pg.codgest
                                         GROUP BY mat.codprodgest, mat.codprodcomp, g.coefcheltmat, pg.coefmat
                                        )  mat ON mat.codprodcomp = pc.codprodcomp
                              LEFT JOIN (SELECT sum (COALESCE (pm.tu, 0) * COALESCE (t.tarif, 0)) * COALESCE (pg.coefman, COALESCE (g.coefcheltman, 0)) VALMAN,
                                                pm.codprodgest, pm.codprodcomp
                                         FROM prodman           pm
                                              LEFT JOIN prodgest pg ON pm.codprodgest = pg.codprodgest
                                              LEFT JOIN ngest    g  ON g.codgest      = pg.codgest
                                              LEFT JOIN (SELECT T1.codtarif, T1.Tarif, t.denumire
                                                         FROM TARIFEMAN1 T1 INNER JOIN tarifeman t ON t1.codtarif = t.codtarif AND AnLunaLucru BETWEEN T1.ALStart AND T1.ALStop
                                                        ) T ON PM.CODTARIF = T.CODTARIF
                                         GROUP BY pm.codprodgest, pm.codprodcomp, g.coefcheltman, pg.coefman
                                        ) man ON man.codprodcomp = pc.codprodcomp
                         WHERE v_rec.codprodcomp = pc.codprodcomp
                        )
        WHERE tmp.codprodcomp = v_rec.codprodcomp;
      END LOOP;
    ELSE
      PERFORM PKG_LIST_BASE_TEHPROD_PregatesteStructura();
    END IF;
  END IF;

  sInsert := 'INSERT INTO '|| tmpName
  || '    (SYSCOD,
        NAV_CodDoc,
        NAV_TipDoc,
        Reteta,
        DenumireP,
        DenumireC,
        CodExternP,
        CodExternC,
        val_mat,
        val_man,
        Gestiune,
        CoefMat,
        CoefMan,
        Pret,
        PretRef,
        PretVanz,
        Inactiv,
        Implicit,
        Tip,
        TipProdus,
        LotOptim,
        Cant,
        PretC,
        Tarif,
        TU,
        Zecimale,
        Regie,
        Nivel,
        NodP,
        Ordine ';
  IF current_setting ('PKG_LIST_BASE_TEHPROD.p_Sursa', true) ::numeric = 2 THEN
    sInsert := coalesce (sInsert,'') || ', Prefix ';
  END IF;

  sInsert := coalesce (sInsert,'') || coalesce (gUserFields ,'') || ')  ';

  IF current_setting ('PKG_LIST_BASE_TEHPROD.p_Sursa', true) ::numeric = 0 THEN
    sWith := '
          with Regie as
            ( select sum (mat.valmat + man.valman) val, pc.codprodcomp
              from prodcomp pc
                inner join tmp_prodcomp tmp on tmp.codprodcomp = pc.codprodcomp
                left join (select sum (coalesce (mat.pret,0) * coalesce (mat.cant,0)) * coalesce (pg.coefmat, coalesce (g.coefcheltmat,0)) valmat,
                                  mat.codprodgest, mat.codprodcomp
                           from prodmat           mat
                                left join prodgest pg on mat.codprodgest = pg.codprodgest
                                left join ngest    g  on g.codgest       = pg.codgest
                           group by mat.codprodgest, mat.codprodcomp, g.coefcheltmat, pg.coefmat
                          ) mat on mat.codprodcomp = pc.codprodcomp
                left join (select sum (coalesce (pm.tu,0) * coalesce (t.tarif,0)) * coalesce (pg.coefman, coalesce (g.coefcheltman,0)) valman,
                                  pm.codprodgest, pm.codprodcomp
                           from prodman           pm
                                left join prodgest pg on pm.codprodgest = pg.codprodgest
                                left join ngest    g  on g.codgest      = pg.codgest
                                left JOIN (select T1.codtarif, T1.Tarif, t.denumire
                                           from TARIFEMAN1 T1 inner join tarifeman t on t1.codtarif = t.codtarif AND '||AnLunaLucru::varchar||' BETWEEN T1.ALStart AND T1.ALStop
                                          ) T ON PM.CODTARIF = T.CODTARIF
                           group by pm.codprodgest, pm.codprodcomp, g.coefcheltman, pg.coefman
                          ) man on man.codprodcomp = pc.codprodcomp
              group by pc.codprodcomp
            )
            ';
  ELSE
    sWith := '
          with Regie as
            ( select sum (mat.valmat + man.valman) val, pc.codprodcomp
              from tmp_proiect tmp
                INNER JOIN PROIECTNOD PN0 ON TMP.CODPROIECT = PN0.CODPROIECT and coalesce (PN0.nodoriginal,0) = 0
                inner join prodcomp   pc  on PN0.codreteta  = pc.codprodcomp
                left join (select sum (coalesce (mat.pret,0) * coalesce (mat.cant,0)) * coalesce (pg.coefmat,coalesce (g.coefcheltmat,0)) valmat,
                                  mat.codprodgest, mat.codprodcomp
                           from prodmat           mat
                                left join prodgest pg on mat.codprodgest = pg.codprodgest
                                left join ngest    g  on g.codgest       = pg.codgest
                           group by mat.codprodgest, mat.codprodcomp, g.coefcheltmat, pg.coefmat
                          ) mat on mat.codprodcomp = pc.codprodcomp
                left join (select sum (coalesce (pm.tu,0) * coalesce (t.tarif,0)) * coalesce (pg.coefman,coalesce (g.coefcheltman,0)) valman,
                                  pm.codprodgest, pm.codprodcomp
                           from prodman            pm
                                left join prodgest pg on pm.codprodgest = pg.codprodgest
                                left join ngest    g  on g.codgest      = pg.codgest
                                left JOIN (select T1.codtarif, T1.Tarif, t.denumire
                                           from TARIFEMAN1 T1 inner join tarifeman t on t1.codtarif = t.codtarif AND '||AnLunaLucru::varchar||' BETWEEN T1.ALStart AND T1.ALStop
                                          ) T ON PM.CODTARIF = T.CODTARIF
                           group by pm.codprodgest, pm.codprodcomp, g.coefcheltman, pg.coefman
                          ) man on man.codprodcomp = pc.codprodcomp
              group by pc.codprodcomp
            )
            ';
  END IF;

  IF current_setting ('PKG_LIST_BASE_TEHPROD.p_Sursa', true) ::numeric = 0 THEN
    sSelect := '
          select PC.CodProdComp,
            PC.CodProdComp,
            504,
            PC.Obs                                   Reteta,
            prod.denumire                            DenumireP,
            comp.denumire                            DenumireC,
            prod.codextern                           codexternp,
            comp.codextern                           codexternc,
            tmp.cant / pc.cant * mat.cant * mat.pret val_mat,
            0                                        val_man,
            ng.den_gest                              gestiune,
            coalesce (pg.coefmat,ng.coefcheltmat)    CoefMat,
            coalesce (pg.coefman,ng.coefcheltman)    CaoefMan,
            pc.Pret,
            p1.pretreferinta PretRef,
            pretm.lei        PretVanz,
            case when coalesce (pc.inactiv ,0) = 1 then ''DA'' else ''NU'' end Inactiv,
            case when coalesce (pc.implicit,0) = 1 then ''DA'' else ''NU'' end as Implicit,
            case when mat.tip = 3 then ''Material''
                else case when mat.tip = 2 then ''Reper'' else ''Complex'' end
            end                  Tip,
            ''Reteta''           TipProdus,
            pc.cant              LotOptim,
            tmp.Cant / pc.cant * mat.Cant,
            mat.Pret             PretC,
            0                    Tarif,
            0                    TU,
            ump.zecimale,
            tmp.cant / pc.cant * tmp.totalprod Regie,
            1                                  Nivel,
            prod.denumire,
            mat.indexlocal ' || coalesce (gUserAlias ,'') || '
          from prodcomp             pc
            inner join tmp_prodcomp tmp on tmp.codprodcomp = pc.codprodcomp
            left join prodgest      pg  on pc.codprodcomp  = pg.codprodcomp
            left join ngest         ng  on pg.codgest      = ng.codgest
            left join (select man.codprodgest, sum (man.valoare) valoare
                       from prodman man
                       group by man.codprodgest
                      ) valman                on valman.codprodgest = pg.codprodgest
            left join prodmat        mat      on pc.codprodcomp  = mat.codprodcomp and pg.codprodgest = mat.codprodgest
            left join nartobj        prod     on prod.codobiect  = pc.codobiect
            left join nart           artp     on prod.codarticol = artp.codarticol
            left join num            ump      on artp.um = ump.codum
            left join pretm                   on prod.codobiect = pretm.codobiect and coalesce (pretm.implicit,0) = 1 and pretm.subunitatea = getsubunitate()
            LEFT JOIN NARTOBJ1       P1       ON P1.CodObiect   = prod.CodObiect AND '||AnLunaLucru::varchar||' BETWEEN P1.ALStart   and P1.ALStop
            LEFT JOIN NARTOBJ1       Par1     ON Par1.CodObiect = prod.CodObiect AND '||AnLunaLucru::varchar||' BETWEEN Par1.ALStart and Par1.ALStop
            left join nartobj        comp     on comp.codobiect = mat.codobiect
            left join nartobjsubunit comps    on comp.codobiect = comps.codobiect
                                                      and (comps.codgest is null or comps.codgest = 0)
                                                      and comps.subunitate = getsubunitate()
            left join nartobjsubunit prods    on prod.codobiect = prods.codobiect
                                                      and (prods.codgest is null or prods.codgest = 0)
                                                      and prods.subunitate = getsubunitate()
            LEFT JOIN NARTOBJ1       C1       ON C1.CodObiect    = mat.CodObiect AND '||AnLunaLucru::varchar||' BETWEEN C1.ALStart   and C1.ALStop
            left join nart           artc     on comp.codarticol = artc.codarticol
            left join num            umc      on artc.um    = umc.codum
            left join nclasea        clsp     on artp.clasa = clsp.codclasea
            left join nclasea        clsc     on artc.clasa = clsc.codclasea
            left join nartobj        parinte  on parinte.codobiect = prod.codobiect'
                || coalesce (gSuplJoins ,'') || '
          where
            coalesce (mat.codmat,0) &gt; 0
            and coalesce (pc.anulat, 0) = 0
            and coalesce (pc.operat, 0) = 1
          union all
          select PC.CodProdComp,
            PC.CodProdComp,
            504,
            PC.Obs                                   Reteta,
            prod.denumire                            DenumireP,
            comp.denumire                            DenumireC,
            prod.codextern                           codexternp,
            comp.codextern                           codexternc,
            tmp.cant / pc.cant * rez.cant * rez.pret val_mat,
            0                                        val_man,
            ng.den_gest                              Gestiune,
            coalesce (pg.coefmat,ng.coefcheltmat)    CoefMat,
            coalesce (pg.coefman,ng.coefcheltman)    CaoefMan,
            pc.Pret,
            p1.pretreferinta PretRef,
            pretm.lei        PretVanz,
            case when coalesce (pc.inactiv ,0) = 1 then ''DA'' else ''NU'' end Inactiv,
            case when coalesce (pc.implicit,0) = 1 then ''DA'' else ''NU'' end as Implicit,
            ''Articol rezultat'' Tip,
            ''Reteta''           TipProdus,
            pc.Cant              LotOptim,
            tmp.Cant / pc.cant * rez.Cant,
            rez.Pret             PretC,
            0                    Tarif,
            0                    TU,
            ump.zecimale,
            tmp.cant / pc.cant * tmp.totalprod Regie,
            1                                  Nivel,
            prod.denumire,
            1 '
                || coalesce (gUserAlias ,'') || '
          from prodcomp               pc
            inner join tmp_prodcomp tmp on tmp.codprodcomp = pc.codprodcomp
            left join prodgest      pg  on pc.codprodcomp = pg.codprodcomp
            left join ngest         ng  on pg.codgest = ng.codgest
            left join (select man.codprodgest, sum (man.valoare) valoare
                       from prodman man
                       group by man.codprodgest
                      ) valman               on valman.codprodgest = pg.codprodgest
            left join prodrez        rez     on pc.codprodcomp  = rez.codprodcomp and pg.codprodgest = rez.codprodgest
            left join prodmat        mat     on mat.codmat      = pc.codprodcomp - pc.codprodcomp
            left join nartobj        prod    on prod.codobiect  = pc.codobiect
            left join nart           artp    on prod.codarticol = artp.codarticol
            left join num            ump     on artp.um         = ump.codum
            left join pretm                  on prod.codobiect  = pretm.codobiect and coalesce (pretm.implicit,0) = 1 and pretm.subunitatea = getsubunitate()
            LEFT JOIN NARTOBJ1       P1      ON P1.CodObiect    = prod.CodObiect AND '||AnLunaLucru::varchar||' BETWEEN P1.ALStart   and P1.ALStop
            LEFT JOIN NARTOBJ1       Par1    ON Par1.CodObiect  = prod.CodObiect AND '||AnLunaLucru::varchar||' BETWEEN Par1.ALStart and Par1.ALStop
            left join nartobj        comp    on comp.codobiect  = rez.codobiect
            left join nartobjsubunit comps   on comp.codobiect  = comps.codobiect
                                             and (comps.codgest is null or comps.codgest = 0)
                                             and comps.subunitate = getsubunitate()
            left join nartobjsubunit prods   on prod.codobiect = prods.codobiect
                                             and (prods.codgest is null or prods.codgest = 0)
                                             and prods.subunitate = getsubunitate()
            LEFT JOIN NARTOBJ1       C1      ON C1.CodObiect    = comp.CodObiect AND '||AnLunaLucru::varchar||' BETWEEN C1.ALStart and C1.ALStop
            left join nart           artc    on comp.codarticol = artc.codarticol
            left join num            umc     on artc.um         = umc.codum
            left join nclasea        clsp    on artp.clasa      = clsp.codclasea
            left join nclasea        clsc    on artc.clasa      = clsc.codclasea
            left join nartobj        parinte on parinte.codobiect = prod.codobiect'
                || coalesce (gSuplJoins ,'') || '
          where
            coalesce (rez.codrez,0) &gt; 0
            and coalesce (pc.anulat, 0) = 0
            and coalesce (pc.operat, 0) = 1
          union all
          select PC.CodProdComp,
            PC.CodProdComp,
            504,
            PC.Obs                                               Reteta,
            prod.denumire                                        DenumireP,
            op.denumire                                          DenumireC,
            prod.codextern                                       codexternp,
            ''''                                                 codexternc,
            0                                                    val_mat,
            tmp.cant / pc.cant * round (man.tu * t.tarif / 60,5) val_man,
            ng.den_gest                                          Gestiune,
            coalesce (pg.coefmat,ng.coefcheltmat)                CoefMat,
            coalesce (pg.coefman,ng.coefcheltman)                CaoefMan,
            pc.Pret,
            p1.pretreferinta PretRef,
            pretm.lei        PretVanz,
            case when coalesce (pc.inactiv ,0) = 1 then ''DA'' else ''NU'' end Inactiv,
            case when coalesce (pc.implicit,0) = 1 then ''DA'' else ''NU'' end as Implicit,
            ''Manopera'' Tip,
            ''Reteta''   TipProdus,
            pc.Cant      LotOptim,
            0            Cant,
            0            PretC,
            T.Tarif,
            tmp.cant / pc.cant * coalesce (man.TU,0) / 60 TU,
            ump.zecimale,
            tmp.cant / pc.cant * tmp.totalprod Regie,
            1 Nivel,
            prod.denumire,
            man.nrop '
                || coalesce (gUserAlias ,'') || '
          from prodcomp             pc
            inner join tmp_prodcomp tmp on tmp.codprodcomp = pc.codprodcomp
            left join prodgest      pg  on pc.codprodcomp  = pg.codprodcomp
            left join ngest         ng  on pg.codgest      = ng.codgest
            left join (select man.codprodgest, sum (round (man.tu * t.tarif / 60,5)) valoare
                       from prodman man
                            left JOIN (select T1.codtarif, T1.Tarif, t.denumire
                                       from TARIFEMAN1 T1 inner join tarifeman t on t1.codtarif = t.codtarif AND '||AnLunaLucru::varchar||' BETWEEN T1.ALStart and T1.ALStop
                                      ) T ON Man.CODTARIF = T.CODTARIF
                       group by man.codprodgest
                      ) valman                  on valman.codprodgest = pg.codprodgest
            left join prodmat            mat    on mat.codmat      = pc.codprodcomp - pc.codprodcomp
            left join prodman            man    on pc.codprodcomp  = man.codprodcomp and pg.codprodgest = man.codprodgest
            left join noper              op     on op.codop        = man.codop
            left join nartobj            prod   on prod.codobiect  = pc.codobiect
            left join nart               artp   on prod.codarticol = artp.codarticol
            left join num                ump    on artp.um         = ump.codum
            left join nartobj            comp   on comp.codobiect  = prod.codobiect - prod.codobiect
            left join nartobjsubunit     comps  on comp.codobiect  = comps.codobiect
                                                and (comps.codgest is null or comps.codgest = 0)
                                                and comps.subunitate = getsubunitate()
            left join nartobjsubunit     prods  on prod.codobiect  = prods.codobiect
                                                and (prods.codgest is null or prods.codgest = 0)
                                                and prods.subunitate = getsubunitate()
            LEFT JOIN NARTOBJ1           C1     ON C1.CodObiect    = comp.CodObiect AND '||AnLunaLucru::varchar||' BETWEEN C1.ALStart and C1.ALStop
            left join nart               artc   on artc.codarticol = 0
            left join num                umc    on umc.codum  = 0
            left join nclasea            clsp   on artp.clasa = clsp.codclasea
            left join nclasea            clsc   on artc.clasa = clsc.codclasea
            left join pretm                     on prod.codobiect = pretm.codobiect and coalesce (pretm.implicit,0) = 1 and pretm.subunitatea = getsubunitate()
            LEFT JOIN NARTOBJ1           P1     ON P1.CodObiect   = prod.CodObiect AND '||AnLunaLucru::varchar||' BETWEEN P1.ALStart and P1.ALStop
            LEFT JOIN NARTOBJ1           Par1   ON Par1.CodObiect = prod.CodObiect AND '||AnLunaLucru::varchar||' BETWEEN Par1.ALStart and Par1.ALStop
            left JOIN (select T1.codtarif, T1.Tarif, t.denumire
                       from TARIFEMAN1 T1 inner join tarifeman t on t1.codtarif = t.codtarif AND '||AnLunaLucru::varchar||' BETWEEN T1.ALStart and T1.ALStop
                      ) T                       ON Man.CODTARIF = T.CODTARIF
            left join nartobj           parinte on parinte.codobiect = prod.codobiect'
                || coalesce (gSuplJoins ,'') || '
          where
            coalesce (pc.anulat, 0) = 0
            and coalesce (pc.operat, 0) = 1 ';
  ELSE
    IF current_setting ('PKG_LIST_BASE_TEHPROD.p_Sursa', true) ::numeric = 1 THEN
      sSelect := '
          select p.codproiect,
            p.codproiect,
            507,
            p.versiune                                           Reteta,
            prod.denumire                                        DenumireP,
            op.denumire                                          DenumireC,
            prod.codextern                                       codexternp,
            ''''                                                 codexternc,
            0                                                    val_mat,
            round (PN.cant / pc.cant * (pm.tu * t.tarif) / 60,5) val_man,
            g.den_gest                                           Gestiune,
            coalesce (pg.coefmat,g.coefcheltmat)                 CoefMat,
            coalesce (pg.coefman,g.coefcheltman)                 CaoefMan,
            pc0.Pret,
            p1.pretreferinta PretRef,
            pretm.lei        PretVanz,
            case when 1 - coalesce (p.activ,0) = 1 then ''DA'' else ''NU'' end Inactiv,
            case when  coalesce (p.implicit,0) = 1 then ''DA'' else ''NU'' end as Implicit,
            ''Manopera'' Tip,
            ''Proiect''  TipProdus,
            pc0.Cant     LotOptim,
            0            Cant,
            0            PretC,
            T.Tarif,
            coalesce (PM.TU,0) / 60 TU,
            ump.zecimale,
            tmp.cant / PN0.Cant * PN.Cant / Pc.Cant * tmpr.totalprod Regie,
            coalesce (PN.Nivel,0)  Nivel,
            parinte.denumire,
            coalesce (PN.ordine,0) '
                  || coalesce (gUserAlias ,'') || '
          from TMP_PROIECTNOD          TMP
            INNER JOIN PROIECT       P       ON P.CodProiect      = TMP.CodProiect
            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 PN.codreteta      = pc.codprodcomp
            inner join prodcomp      pc0     on PN0.codreteta     = pc0.codprodcomp
            inner join nartobj       prod    on prod.codobiect    = p.codobiectprod
            INNER JOIN tmp_prodcomp  tmpr    on tmpr.codprodcomp  = pn.codreteta
            left join nartobj        parinte on parinte.codobiect = PN.codobiect
            left join nart           artp    on prod.codarticol   = artp.codarticol
            left join num            ump     on artp.um           = ump.codum
            left join nartobj        comp    on comp.codobiect    = prod.codobiect - prod.codobiect
            left join nartobjsubunit comps   on comp.codobiect    = comps.codobiect
                                             and (comps.codgest is null or comps.codgest = 0)
                                             and comps.subunitate = getsubunitate()
            left join nartobjsubunit prods   on prod.codobiect    = prods.codobiect
                                             and (prods.codgest is null or prods.codgest = 0)
                                             and prods.subunitate = getsubunitate()
            LEFT JOIN NARTOBJ1       C1      ON C1.CodObiect    = comp.CodObiect AND '||AnLunaLucru::varchar||' BETWEEN C1.ALStart and C1.ALStop
            left join nart           artc    on artc.codarticol = comp.codarticol
            left join num            umc     on umc.codum       = 0
            left join nclasea        clsp    on artp.clasa      = clsp.codclasea
            left join nclasea        clsc    on artc.clasa      = clsc.codclasea
            left join pretm                  on prod.codobiect  = pretm.codobiect and coalesce (pretm.implicit,0) = 1 and pretm.subunitatea = getsubunitate()
            left join prodgest pg            on pc.codprodcomp  = pg.codprodcomp
            LEFT JOIN NARTOBJ1 P1            ON P1.CodObiect    = prod.CodObiect AND '||AnLunaLucru::varchar||' BETWEEN P1.ALStart and P1.ALStop
            LEFT JOIN NARTOBJ1 Par1          ON Par1.CodObiect  = PN.codobiect   AND '||AnLunaLucru::varchar||' BETWEEN Par1.ALStart and Par1.ALStop
            left join (select man.codprodgest, sum (round (man.tu * t.tarif / 60,5)) valoare
                       from prodman man
                            left JOIN (select T1.codtarif, T1.Tarif, t.denumire
                                       from TARIFEMAN1 T1 inner join tarifeman t on t1.codtarif = t.codtarif AND '||AnLunaLucru::varchar||' BETWEEN T1.ALStart and T1.ALStop
                                      ) T ON Man.CODTARIF = T.CODTARIF
                       group by man.codprodgest
                      ) valman                  on valman.codprodgest       = pg.codprodgest
            left join ngest              g      on coalesce (pg.codgest, 0) = g.codgest
            left join prodman            pm     on pm.codprodcomp = pc.codprodcomp and pm.codprodgest = pg.codprodgest
            left join prodmat            mat    on mat.codmat     = p.codproiect - p.codproiect
            left join noper              op     on pm.codop       = op.codop
            left join locmunca           lm     on lm.codloc      = pm.codloc
            left JOIN (select T1.codtarif, T1.Tarif, t.denumire
                       from TARIFEMAN1 T1 inner join tarifeman t on t1.codtarif = t.codtarif AND '||AnLunaLucru::varchar||' BETWEEN T1.ALStart and T1.ALStop
                      ) T ON PM.CODTARIF = T.CODTARIF'
                  || coalesce (gSuplJoins ,'') || '
          where
            coalesce (pc.anulat, 0) = 0
            and pn.codreteta &gt; 0
            and coalesce (op.codop,0) &gt; 0 ';

      sSelect := coalesce (sSelect,'') || '
          union all
          SELECT p.codproiect,
            p.codproiect,
            507,
            P.versiune                               Reteta,
            OBJP.Denumire                            DenumireP,
            COMP.Denumire                            DenumireC,
            OBJP.codextern                           codexternp,
            COMP.codextern                           codexternc,
            tmp.cant / PN0.Cant * PN.cant * mat.pret val_mat,
            0                                        val_man,
            g.den_gest                               Gestiune,
            coalesce (pg.coefmat,g.coefcheltmat)     CoefMat,
            coalesce (pg.coefman,g.coefcheltman)     CaoefMan,
            mat.pret,
            p1.pretreferinta PretRef,
            pretm.lei        PretVanz,
            case when 1 - coalesce (p.activ,0) = 1 then ''DA'' else ''NU'' end Inactiv,
            case when coalesce (p.implicit,0)  = 1 then ''DA'' else ''NU'' end as Implicit,
            case when PN.tip = 3 then ''Material''
                 else case when PN.Tip = 2 then ''Reper'' else ''Complex'' end
            end                   Tip,
            ''Proiect''           TipProdus,
            pc0.Cant              LotOptim,
            tmp.cant / PN0.Cant * pn.Cant,
            mat.pret              PretC,
            0                     Tarif,
            0                     TU,
            ump.zecimale,
            tmp.cant / PN0.Cant * PN.Cant / Pc.Cant * tmpr.totalprod Regie,
            coalesce (PN.Nivel,0) Nivel,
            parinte.denumire,
            coalesce (Ppar.ordine,0) '
                  || coalesce (gUserAlias ,'') || '
          FROM TMP_PROIECTNOD          TMP
            INNER JOIN PROIECT       P       ON P.CodProiect       = TMP.CodProiect
            INNER JOIN PROIECTNOD    PN      ON P.CODPROIECT       = PN.CODPROIECT
            INNER JOIN PROIECTNOD    PN0     ON P.CODPROIECT       = PN0.CODPROIECT AND coalesce (PN0.NODORIGINAL, 0) = 0
            left JOIN PRODCOMP       PC      ON PN.CODRETETA       = PC.CODPRODCOMP
            left JOIN PRODCOMP       PC0     ON PN0.CODRETETA      = PC0.CODPRODCOMP
            left JOIN tmp_prodcomp   tmpr    on tmpr.codprodcomp   = pn.codreteta
            left JOIN PRODMAT        MAT     ON MAT.CODMAT         = PN.CODPRODMAT
            left JOIN PROIECTNOD     PPar    ON PPar.CODPROIECTNOD = coalesce (PN.nodoriginal,0)
            left join prodgest       pg      on mat.codprodgest    = pg.codprodgest
            left join ngest          g       on pg.codgest         = g.codgest
            left JOIN NARTOBJ        OBJP    ON P.CODOBIECTPROD    = OBJP.CODOBIECT
            left JOIN NARTOBJ        Prod    ON P.CODOBIECTPROD    = Prod.CODOBIECT
            left join nartobj        parinte on parinte.codobiect  = coalesce (ppar.CodObiect, objp.codobiect)
            left join nart           artp    on objp.codarticol    = artp.codarticol
            left join num            ump     on artp.um            = ump.codum
            left JOIN NARTOBJ        comp    ON PN.CODOBIECT       = comp.CODOBIECT
            left join nartobjsubunit comps   on comp.codobiect     = comps.codobiect
                                             and (comps.codgest is null or comps.codgest = 0)
                                             and comps.subunitate = getsubunitate()
            left join nartobjsubunit prods   on prod.codobiect     = prods.codobiect
                                             and (prods.codgest is null or prods.codgest = 0)
                                             and prods.subunitate = getsubunitate()
            LEFT JOIN NARTOBJ1       C1      ON C1.CodObiect    = comp.CodObiect AND '||AnLunaLucru::varchar||' BETWEEN C1.ALStart and C1.ALStop
            left join nart           artc    on comp.codarticol = artc.codarticol
            left join num            umc     on artc.um         = umc.codum
            left join nclasea        clsp    on artp.clasa      = clsp.codclasea
            left join nclasea        clsc    on artc.clasa      = clsc.codclasea
            LEFT JOIN NARTOBJ1       P1      ON P1.CodObiect    = OBJP.CodObiect                          AND '||AnLunaLucru::varchar||' BETWEEN P1.ALStart and P1.ALStop
            LEFT JOIN NARTOBJ1       Par1    ON Par1.CodObiect  = coalesce (ppar.CodObiect, PN.codobiect) AND '||AnLunaLucru::varchar||' BETWEEN Par1.ALStart and Par1.ALStop
            left join pretm                  on OBJP.codobiect  = pretm.codobiect and coalesce (pretm.implicit,0) = 1 and pretm.subunitatea = getsubunitate()'
                  || coalesce (gSuplJoins ,'') || '
          WHERE PN.TIP = 3';
        ELSE
          sSelect := '
              select tmp.CodProdComp,
                tmp.CodProdComp,
                504,
                PC.Obs                              Reteta,
                prod.denumire                       DenumireP,
                comp.denumire                       DenumireC,
                prod.codextern                      codexternp,
                comp.codextern                      codexternc,
                coalesce (tmp.cant,0) * coalesce (mat.pret,0) val_mat,
                0                                   val_man,
                ng.den_gest                         gestiune,
                coalesce (pg.coefmat,ng.coefcheltmat)    CoefMat,
                coalesce (pg.coefman,ng.coefcheltman)    CaoefMan,
                pc.Pret,
                p1.pretreferinta PretRef,
                pretm.lei        PretVanz,
                case when coalesce (pc.inactiv,0) = 1 then ''DA'' else ''NU'' end Inactiv,
                case when coalesce (pc.implicit,0) = 1 then ''DA'' else ''NU'' end as Implicit,
                case when mat.tip = 3 then ''Material''
                     else case when mat.tip = 2 then ''Reper'' else ''Complex'' end
                end        Tip,
                ''Reteta'' TipProdus,
                pc.cant    LotOptim,
                coalesce (tmp.Cant,0) ,
                mat.Pret PretC,
                0        Tarif,
                0        TU,
                ump.zecimale,
                tmp.cant / pc.cant * tmp.totalprod Regie,
                coalesce (tmp.NrCmd,0)                  Nivel,
                nodp.denumire,
                mat.indexlocal,
                tmp.observatii '
                      || coalesce (gUserAlias ,'') || '
              from tmp_prodcomp       tmp
                inner join prodcomp      pc    on tmp.codprodcomp = pc.codprodcomp
                left join prodmat        mat   on tmp.codproiect  = mat.codmat
                left join prodgest       pg    on mat.codprodgest = pg.codprodgest and pg.codprodcomp = pc.codprodcomp
                left join ngest          ng    on pg.codgest      = ng.codgest
                left join prodcomp       retp  on mat.codprodcomp = retp.codprodcomp
                left join nartobj        nodp  on retp.codobiect  = nodp.codobiect
                left join nartobj        prod  on prod.codobiect  = tmp.implicitold
                left join nart           artp  on prod.codarticol = artp.codarticol
                left join num            ump   on artp.um         = ump.codum
                left join pretm                on prod.codobiect  = pretm.codobiect and coalesce (pretm.implicit,0) = 1 and pretm.subunitatea = getsubunitate()
                LEFT JOIN NARTOBJ1       P1    ON P1.CodObiect    = prod.CodObiect AND '||AnLunaLucru::varchar||' BETWEEN P1.ALStart and P1.ALStop
                left join nartobj        comp  on comp.codobiect  = mat.codobiect
                left join nartobjsubunit comps on comp.codobiect  = comps.codobiect
                                               and (comps.codgest is null or comps.codgest = 0)
                                               and comps.subunitate = getsubunitate()
                left join nartobjsubunit prods on prod.codobiect  = prods.codobiect
                                               and (prods.codgest is null or prods.codgest = 0)
                                               and prods.subunitate = getsubunitate()
                LEFT JOIN NARTOBJ1       C1    ON C1.CodObiect    = mat.CodObiect AND '||AnLunaLucru::varchar||' BETWEEN C1.ALStart and C1.ALStop
                left join nart           artc  on comp.codarticol = artc.codarticol
                left join num            umc   on artc.um         = umc.codum
                left join nclasea        clsp  on artp.clasa      = clsp.codclasea
                left join nclasea        clsc  on artc.clasa      = clsc.codclasea'
                      || coalesce (gSuplJoins ,'') || ' ';
        END IF;
    END IF;

  DELETE FROM TMP_PRODCOMP_MAN   WHERE USERID = VUSERID;
  DELETE FROM TMP_PROIECTNOD_MAN WHERE USERID = VUSERID;
  DELETE FROM TMP_CMD             WHERE USERID = VUSERID;

  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_termedcli_processlist</obj_name>
  <obj_hashval>735db754281f39f4b4a95de1eaed5efb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_termedcli_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 := 'npart npart';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 16.10.2020 (??)
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_TERMEDCLI.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert := 'INSERT INTO '||tmpName ||'(PARTENER, MONEDA, '             ||chr(13)||
                                       'TOTAL, TERMED'||gUserFields||') '||chr(13);
   sSelect :=
   'with stingeri as
    (select stingere.*, general.codgeneral
     from stingere
          inner join obligpif on stingere.codstingatorpif = obligpif.codobligpif
          inner JOIN general  ON obligpif.codgeneral      = general.codgeneral
    ), '                              ||chr(13)||
    'stinsi as
    ( SELECT i.datadoc data_stins, '  ||chr(13)||
            'obstins.codobligpif, '   ||chr(13)||
            'obstins.codpart codpart '||chr(13)||
    'FROM iesiri i '                  ||chr(13)||
    '     INNER JOIN general g        ON g.coddoc     = i.codies and g.semnificatie &lt;&gt; 500 '||chr(13)||
    '     INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral '||chr(13)||
    'WHERE (coalesce(i.anulat, 0) = 0) and (coalesce(i.initializari, 0) = 1) and (g.tipdoc = i.tipdoc) '||chr(13)||
    '      AND i.datadoc &lt;= TO_DATE('''||to_char(pkg_list_alegperioada_getDataF(),'dd/mm/yyyy')||''',''DD/MM/YYYY'') '||chr(13)||
    'UNION ALL
     SELECT '                         ||chr(13)||
            'i.datadoc data_stins, '  ||chr(13)||
            'obstins.codobligpif, '   ||chr(13)||
            'obstins.codpart codpart '||chr(13)||
    'FROM iesiri i '                  ||chr(13)||
    '     INNER JOIN general g        ON g.coddoc     = i.codies and g.semnificatie &lt;&gt; 500 '||chr(13)||
    '     INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral '||chr(13)||
    'WHERE (coalesce(i.anulat, 0) = 0) and (coalesce(i.initializari, 0) = 0) and (g.tipdoc = i.tipdoc) '||chr(13)||
    '      AND i.datadoc &lt;= TO_DATE('''||to_char(pkg_list_alegperioada_getDataF(),'dd/mm/yyyy')||''',''DD/MM/YYYY'') '||chr(13)||
    'UNION ALL
     SELECT '                         ||chr(13)||
            'i.datadoc data_stins, '  ||chr(13)||
            'obstins.codobligpif, '   ||chr(13)||
            'obstins.codpart codpart '||chr(13)||
    'FROM intrari i '                 ||chr(13)||
    '     INNER JOIN general g        ON g.coddoc     = i.codintr and g.semnificatie = 100 '||chr(13)||
    '     INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral '||chr(13)||
    'WHERE (coalesce(i.anulat, 0) = 0) and (coalesce(i.initializari, 0) = 0) and (g.tipdoc = i.tipdoc) '||chr(13)||
    '      AND i.datadoc &lt;= TO_DATE('''||to_char(pkg_list_alegperioada_getDataF(),'dd/mm/yyyy')||''',''DD/MM/YYYY'') '||chr(13)||
    'UNION ALL '                      ||chr(13)||
    'SELECT  nc.datadoc data_stins, ' ||chr(13)||
            'obstins.codobligpif, '   ||chr(13)||
            'obstins.codpart codpart '||chr(13)||
    'FROM nc1 '                       ||chr(13)||
    '     INNER JOIN general g        ON g.coddoc     = nc1.codnc1 and g.semnificatie &lt;&gt; 500 '||chr(13)||
    '     INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral '||chr(13)||
    '     INNER JOIN nc               ON nc1.codnc    = nc.codnc '          ||chr(13)||
    'WHERE g.tipdoc = 35 AND '                                              ||chr(13)||
    '      nc.datadoc &lt;= TO_DATE('''||to_char(pkg_list_alegperioada_getDataF(),'dd/mm/yyyy')||''',''DD/MM/YYYY'') '||chr(13)||
    'UNION ALL '                      ||chr(13)||
    'SELECT  tr1.datadoc data_stins, '||chr(13)||
            'obstins.codobligpif, '   ||chr(13)||
            'obstins.codpart codpart '||chr(13)||
    'FROM trezor1 tr1 '               ||chr(13)||
    '     INNER JOIN general g        ON g.coddoc      = tr1.codtrezor1 and g.semnificatie &lt;&gt; 500 '||chr(13)||
    '     INNER JOIN obligpif obstins ON g.codgeneral  = obstins.codgeneral '||chr(13)||
    '     INNER JOIN trezor tr        ON tr1.codtrezor = tr.codtrezor '      ||chr(13)||
    'WHERE (g.tipdoc in (30, 31)) AND (coalesce(tr1.anulat, 0) = 0) AND '    ||chr(13)||
    '      tr1.datadoc &lt;= TO_DATE('''||to_char(pkg_list_alegperioada_getDataF(),'dd/mm/yyyy')||''',''DD/MM/YYYY'') '||chr(13)||
    'UNION ALL '                         ||chr(13)||
    'SELECT  cstins.datadoc data_stins, '||chr(13)||
            'obstins.codobligpif, '      ||chr(13)||
            'obstins.codpart codpart '   ||chr(13)||
    'FROM compens cstins '               ||chr(13)||
    '     INNER JOIN general g        ON g.coddoc     = cstins.codcompens and g.semnificatie &lt;&gt; 500 '||chr(13)||
    '     INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral '                         ||chr(13)||
    'WHERE g.tipdoc = 28  AND '                                                                      ||chr(13)||
    '      cstins.datadoc &lt;= TO_DATE('''||to_char(pkg_list_alegperioada_getDataF(),'dd/mm/yyyy')||''',''DD/MM/YYYY'')
    ),'                                ||chr(13)||
    'stingatori as ('                  ||chr(13)||
       '  SELECT '                     ||chr(13)||
       '    o.codobligpif CodObligPIF,'||chr(13)||
       '    t1.datadoc as DATA, '      ||chr(13)||
       '    t.Subunitatea, '           ||chr(13)||
       '    g.moneda '                 ||chr(13)||
       '  FROM trezor1 t1 '            ||chr(13)||
       '       INNER JOIN general g  ON t1.codtrezor1 = g.coddoc '    ||chr(13)||
       '       INNER JOIN obligpif o ON o.codgeneral  = g.codgeneral '||chr(13)||
       '       INNER JOIN trezor t   ON t1.codtrezor  = t.codtrezor'  ||chr(13)||
       '  WHERE T1.DATADOC BETWEEN TO_DATE('''||to_char(pkg_list_alegperioada_getDataS(),'dd/mm/yyyy')||''',''DD/MM/YYYY'') AND TO_DATE('''||to_char(pkg_list_alegperioada_getDataF(),'dd/mm/yyyy')||''',''DD/MM/YYYY'') AND ((G.TipDoc IN (29, 30, 31) AND t1.TipTranz = 1) OR (t1.TipTranz = 1 AND t1.ObiectTranz = 1)) '||chr(13)||
       'UNION ALL '                    ||chr(13)||
       '  SELECT '                     ||chr(13)||
       '    o.codobligpif CodObligPIF,'||chr(13)||
       '    c.datadoc as DATA, '       ||chr(13)||
       '    C.Subunitatea, '           ||chr(13)||
       '    g.moneda '                 ||chr(13)||
       '  FROM compens c '                                                                       ||chr(13)||
       '       INNER JOIN general  g ON g.coddoc     = c.codcompens '                            ||chr(13)||
       '       INNER JOIN obligpif o ON o.codgeneral = g.codgeneral '                            ||chr(13)||
       '  WHERE C.DATADOC BETWEEN TO_DATE('''||to_char(pkg_list_alegperioada_getDataS(),'dd/mm/yyyy')||''',''DD/MM/YYYY'') AND TO_DATE('''||to_char(pkg_list_alegperioada_getDataF(),'dd/mm/yyyy')||''',''DD/MM/YYYY'') AND G.TipDoc = 28 '||chr(13)||
       ')'                                                                                       ||chr(13)||
       'SELECT centralizare.partener, centralizare.Simbolmoneda, sum(centralizare.val_stingator) TOTAL,
               sum(centralizare.val_stingator*centralizare.difzile)/sum(centralizare.val_stingator) TERMED'||gUserAlias||
       'FROM ( '                                                                                 ||chr(13)||
             'select  stingeri.valoare VAL_STINGATOR, '                                          ||chr(13)||
                     'npart.den_part PARTENER,'                                                  ||chr(13)||
                     'stingatori.Data as DATA, '                                                 ||chr(13)||
                     'stinsi.Data_stins DATA_STINS, '                                            ||chr(13)||
                     'date_trunc(''day'',stingatori.Data - stinsi.data_stins) DIFZILE, '         ||chr(13)||
                     'mon.simbol simbolmoneda '                                                  ||chr(13)||
              ' FROM stingatori '                                                                 ||chr(13)||
             '      INNER JOIN stingeri    on stingeri.codstingatorpif = stingatori.codobligpif '||chr(13)||
             '      INNER JOIN stinsi      on stingeri.codstinspif     = stinsi.codobligpif '    ||chr(13)||
             '      LEFT  JOIN npart npart on stinsi.codpart           = npart.codpart '         ||chr(13)||
             '      LEFT  JOIN nmonede MON ON stingatori.moneda        = MON.CodMoneda' || gSuplJoins || PKG_LIST_BASE_UTILS.COND_SUBUNIT('stingatori','subunitatea',' WHERE',null);

   sSelect := sSelect||'  ) CENTRALIZARE GROUP BY centralizare.partener, centralizare.simbolmoneda ';

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topclientiold_conditieincludereioart</obj_name>
  <obj_hashval>96739160a7c8c7f5785d81e6eec3c114</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topclientiold_conditieincludereioart(acodioart numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  aCount  numeric;
BEGIN
  --Adina 19.10.2020
  IF current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vAllIOArt',true)::boolean
  THEN RETURN 1;
  ELSE
    SELECT count(*) INTO aCount
    FROM IOART IOA
    WHERE ioa.codioart = aCodIOArt AND
          EXISTS (SELECT tmp.valoare FROM tmp_manevra_liste tmp WHERE tmp.filtru = 'CODIOART' and tmp.valoare = ioa.codioart::varchar);
    RETURN aCount;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topclientiold_getallioart_n</obj_name>
  <obj_hashval>568a3ff86f78f5565cd42fdafb652cb6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topclientiold_getallioart_n()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 19.10.2020
  IF current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vAllIOArt',true)::boolean THEN RETURN 1; ELSE RETURN 0; END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topfurn_getallcls_n</obj_name>
  <obj_hashval>e3f7f5dd681c41596d674eeaf245a3f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topfurn_getallcls_n()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 07 septembrie 2020
  IF current_setting('PKG_LIST_BASE_TOPFURN.vAllCls', true)::boolean THEN
    RETURN  1;
  ELSE
    RETURN  0;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_tras_makesqlmiscari</obj_name>
  <obj_hashval>a4717d1d2d3cfb8b11423e84fba4dfb5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_tras_makesqlmiscari(pinsert text, ptipc text, pgest text)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  pInterval TEXT := PKG_LIST_SELTRAS_GetInterval();
  sqlWith1  TEXT;
  sqlWith2  TEXT;
  sqlWith3  TEXT;
  sqlWith4  TEXT;
  sqlWith5  TEXT;
  sqlSelect TEXT;
BEGIN
  --Florin 09,12,2024 - sinc. Oracle
  -- Stef 16.06.2023

  --intrari
  sqlWith1 := '
  WITH crs_miscari AS (
    SELECT
      ns.codnirstoc, ns.codobiect,nser.codnirser,nser.codserie, COALESCE(ns.tg,nser.tg) dataexp,
      n.codintr coddoc, 1 tipd, intr.prefixdoc, intr.seriadoc, intr.nrdoc, intr.datadoc, n.datanir datamisc,
      ns.codintr1, ns.coddvi1, ns.codlivr1, ns.codtransf1, NULL::numeric codies1,
      Coalesce(nser.cantnir,ns.cantnir) intrare, 0 iesire,
      n.tipnir tipmiscare,
      1 ordine, (ns.pret - ns.adaos) PAchiz, ns.pret pInreg, ns.pumaximal, ns.furn, n.gest,
      intr.partener, intr.codsubunit, Coalesce(intr.codgestprod,ns.codgestprod) codgestprod,
      intr.an, intr.luna, ns.codioart, ns.codlocatie, intr.subunitatea subunitatea_doc,
      ns.d1, ns.d2, ns.d3, c1int.codcomanda codcmdint, intr.codlocatie codslivr
    FROM nirstoc ns
      INNER JOIN nir n ON ns.codnir = n.codnir
      INNER JOIN NGEST G ON G.CODGEST = N.GEST
      LEFT JOIN intrari1 intr1 ON ns.codintr1 = intr1.codintr1
      LEFT JOIN dvi1 ON ns.coddvi1 = dvi1.coddvi1
      LEFT JOIN intrari intr ON intr.codintr = n.codintr
      LEFT JOIN nirser nser ON nser.codnirstoc = ns.codnirstoc
      LEFT JOIN comanda1 c1int ON c1int.codcomanda1 = intr1.codcmdint1
    WHERE NS.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')
      AND n.tipnir BETWEEN 1 AND 9 AND INTR.OPERAT = 1
      AND n.datanir BETWEEN '||pInterval||
      pTipC || pGest ||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT')||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT('intr')||'
  )';

  --iesiri, intrari in rosu(pe acelasi codnirstoc), monetare, mariri si diminuare
  sqlWith2 := '
  WITH crs_miscari AS (
    SELECT
      ns.codnirstoc,ns.codobiect,nser.codnirser,nser.codserie,COALESCE(ns.tg,nser.tg) dataexp,
      CASE WHEN l.tiplivr in (1,2,5,6,7) THEN intr.codintr ELSE ies.codies END coddoc,
      CASE WHEN l.tiplivr in (1,2,5,6,7, 15) THEN 1 ELSE 2 END tipd,
      CASE WHEN l.tiplivr in (1,2,5,6,7) THEN intr.prefixdoc ELSE ies.prefixdoc END prefixdoc,
      CASE WHEN l.tiplivr in (1,2,5,6,7) THEN intr.seriadoc ELSE ies.seriadoc END seriadoc,
      CASE WHEN l.tiplivr in (1,2,5,6,7) THEN intr.nrdoc ELSE ies.nrdoc END nrdoc,
      CASE WHEN l.tiplivr in (1,2,5,6,7) THEN intr.datadoc ELSE ies.datadoc END datadoc,
      CASE WHEN l.tiplivr in (1,2,5,6,7) THEN n.datanir ELSE l.DATALIVR END datamisc,
      ns.codintr1,ns.coddvi1,L1.codlivr1,ns.codtransf1,ies1.codies1,
      CASE WHEN l.tiplivr in (1,2,5,6,7) THEN -l1.cant WHEN L.TIPLIVR = 15 THEN l1.cant ELSE 0 END intrare,
      CASE WHEN l.tiplivr in (1,2,5,6,7) THEN 0 WHEN L.TIPLIVR = 15 THEN 0 ELSE l1.cant END iesire,
      l.tiplivr AS tipmiscare,
      CASE WHEN l.tiplivr in (1,2,5,6,7) THEN 1 ELSE 2 END ordine, (ns.pret - ns.adaos) pAchiz, ns.pret pInreg ,ns.pumaximal, ns.furn, n.gest,
      CASE WHEN l.tiplivr in (1,2,5,6,7) THEN intr.partener ELSE ies.partener END partener,
      CASE WHEN l.tiplivr in (1,2,5,6,7) THEN intr.codsubunit ELSE ies.codsubunit END codsubunit,
      Coalesce(ies.codgestprod,ns.codgestprod) codgestprod,
      CASE WHEN l.tiplivr in (1,2,5,6,7) THEN intr.an   ELSE ies.an   END an,
      CASE WHEN l.tiplivr in (1,2,5,6,7) THEN intr.luna ELSE ies.luna END luna,
      ns.codioart,ns.codlocatie, Coalesce(intr.subunitatea, ies.subunitatea) subunitatea_doc,
      ns.d1, ns.d2, ns.d3, c1int.codcomanda codcmdint, COALESCE(intr.codlocatie, ies.codlocatie) codslivr
    FROM livr1 l1
      INNER JOIN nirstoc ns ON l1.codnirstoc = ns.codnirstoc
      LEFT JOIN iesvallink ivl ON ivl.codies1 = l1.codies1
      LEFT JOIN livr1 lx1 ON lx1.codlivr1 = ivl.codlivr1
      LEFT JOIN livr l ON l.codlivr = Coalesce(lx1.codlivr, l1.codlivr)
      LEFT JOIN iesiri ies ON ies.codies = l.codies
      LEFT JOIN intrari intr ON intr.codintr = l.codintr
      LEFT JOIN nir n ON n.codnir = ns.codnir
      LEFT JOIN NGEST G ON G.CODGEST = N.GEST
      LEFT JOIN nirser nser ON nser.codnirser = l1.codnirser
      LEFT JOIN intrari1 intr1 ON intr1.codintr = intr.codintr AND intr1.codintr1 = l1.codintr1
      LEFT JOIN iesiri1 ies1 ON ies1.codies = ies.codies AND ies1.codies1 = Coalesce(lx1.codies1,l1.codies1)
      LEFT JOIN comanda1 c1int ON c1int.codcomanda1 = Coalesce(intr1.codcmdint1,ies1.codcmdint1)
    WHERE NS.CODOBIECT::varchar IN (SELECT DISTINCT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')
      AND ((l.tiplivr BETWEEN 19 AND 26 AND l1.cant &gt; 0 ) OR ( l.tiplivr IN ( 1,2,5,6,7,14,15,16) )) AND COALESCE(ies.operat,intr.operat,0) = 1
      AND Coalesce(l.datalivr,n.datanir) BETWEEN '||pInterval||
      pTipC || pGest ||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT')||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT('','Coalesce(intr.subunitatea,ies.subunitatea)')||'
  )';

  -- iesiri in rosu pe codnirstocuri noi
  sqlWith3 := '
  WITH crs_miscari AS (
    SELECT
      ns.codnirstoc,ns.codobiect,nser.codnirser,nser.codserie,COALESCE(ns.tg,nser.tg) dataexp,
      ies.codies coddoc, 2 tipd, ies.prefixdoc, ies.seriadoc, ies.nrdoc, ies.datadoc, l.datalivr datamisc,
      ns.codintr1,ns.coddvi1,l1.codlivr1,ns.codtransf1,ies1.codies1,
      0 intrare, l1.cant iesire,
      l.tiplivr tipmiscare,
      1 ordine, (ns.pret - ns.adaos) pAchiz, ns.pret pInreg, ns.pumaximal, ns.furn, n.gest,
      ies.partener, ies.codsubunit, Coalesce(ies.codgestprod,ns.codgestprod) codgestprod,
      ies.an,ies.luna,ns.codioart,ns.codlocatie, ies.subunitatea subunitatea_doc,
      ns.d1, ns.d2, ns.d3, c1int.codcomanda codcmdint, ies.codlocatie codslivr
    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 nir n ON n.codnir = ns.codnir
      LEFT JOIN NGEST G ON G.CODGEST = N.GEST
      LEFT JOIN NIRSER NSER ON NSER.CODNIRSER = L1.CODNIRSER
      LEFT JOIN iesiri1 ies1 ON ies1.codies = ies.codies AND ies1.codies1 = l1.codies1
      LEFT JOIN comanda1 c1int ON c1int.codcomanda1 = ies1.codcmdint1
    WHERE NS.CODOBIECT::varchar IN (SELECT DISTINCT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')
      AND (l.tiplivr BETWEEN 19 AND 26 AND l1.cant &lt; 0 )
      AND IES.OPERAT = 1
      AND l.datalivr BETWEEN '||pInterval||
      pTipC || pGest ||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT')||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT('ies')||'
  )';

  -- transferuri destinatii
  sqlWith4 := '
  WITH crs_miscari AS (
    SELECT
      ns.codnirstoc,ns.codobiect,nser.codnirser,nser.codserie,Coalesce(ns.tg,nser.tg) dataexp,
      t.codtransf coddoc, 1 tipd, t.prefixdoc, t.seriadoc, t.nrdoc, t.datadoc, n.datanir datamisc,
      ns.codintr1,ns.coddvi1,ns.codlivr1,ns.codtransf1,NULL::numeric codies1,
      Coalesce(nser.cantnir,ns.cantnir) intrare, 0 iesire,
      n.tipnir AS tipmiscare,
      8 ordine ,(ns.pret - ns.adaos) pAchiz, ns.pret pInreg, ns.pumaximal, ns.furn, n.gest,
      nirs.gest partener, NULL::numeric codsubunit, ns.codgestprod,
      t.an, t.luna, ns.codioart,ns.codlocatie, t.subunitatea subunitatea_doc,
      ns.d1, ns.d2, ns.d3, NULL::numeric codcmdint, NULL::numeric codslivr
    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 nirstoc nss ON nss.codnirstoc = ns.codnirstocparinte
      LEFT JOIN nir nirs ON nirs.codnir = nss.codnir
      LEFT JOIN NIRSER NSER ON NSER.CODNIRSTOC = NS.CODNIRSTOC
    WHERE NS.CODOBIECT::varchar IN (SELECT DISTINCT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')
      AND T.OPERAT = 1
      AND n.datanir BETWEEN '||pInterval||
      pTipC || pGest ||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT')||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT('t')||'
  )';

  -- transferuri surse
  sqlWith5 := '
  WITH crs_miscari AS (
    SELECT
      ns.codnirstoc,ns.codobiect,nsd.codnirser,nsd.codserie,COALESCE(nsd.tg, ns.tg) dataexp,
      t.codtransf coddoc, 2 tipd, t.prefixdoc, t.seriadoc, t.nrdoc, t.datadoc,nsd.datalivr datamisc,
      ns.codintr1, ns.coddvi1, nsd.codlivr1, nsd.codtransf1, NULL::numeric codies1,
      0 intrare, nsd.cant iesire,
      t.tipdoc tipmiscare,
      7 ordine, (ns.pret - ns.adaos) pAchiz, ns.pret pInreg, ns.pumaximal, ns.furn, n.gest,
      nsd.gest partener, NULL::numeric codsubunit, ns.codgestprod,
      t.an,t.luna,ns.codioart,ns.codlocatie, t.subunitatea SUBUNITATEA_DOC,
      ns.d1, ns.d2, ns.d3, NULL::numeric codcmdint, NULL::numeric codslivr
    FROM (
      SELECT
        ns.codnirstoc, ns.codnirstocparinte, n.tipnir, ns.codtransf1, ns.codlivr1, Coalesce(nser.cantnir,ns.cantnir) cant,
        l.datalivr, t.codtransf, n.gest, nser.codnirser, nser.codserie, nser.tg
      FROM transf t
        INNER JOIN nir n ON n.codtransf = t.codtransf AND n.tipnir = t.tipdoc
        INNER JOIN nirstoc ns ON ns.codnir = n.codnir
        INNER JOIN livr1 l1 ON l1.codlivr1 = ns.codlivr1
        INNER JOIN livr l ON l.codlivr = l1.codlivr
        LEFT JOIN NIRSER NSER ON NSER.CODNIRSTOC = NS.CODNIRSTOC
      WHERE NS.CODOBIECT::varchar IN (SELECT DISTINCT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')
        AND T.OPERAT = 1
        AND l.datalivr BETWEEN '||pInterval||
        PKG_LIST_BASE_UTILS_COND_SUBUNIT('t')||'
    ) nsd
      INNER JOIN nirstoc ns ON ns.codnirstoc = nsd.codnirstocparinte
      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 = nsd.codtransf
    WHERE 1=1 '||
      pTipC||pGest||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT('G','CODSUBUNIT')||'
  )';

  sqlSelect := '
  SELECT
    crs.coddoc, crs.tipmiscare, crs.codnirstoc, nobj.denumire, crs.intrare, crs.iesire, crs.intrare - crs.iesire stoc_fake, crs.pAchiz, crs.pInreg, crs.pumaximal, crs.dataexp,
    CASE crs.furn WHEN 0 THEN gestprod.den_gest ELSE furn.den_part END denfurn, prod.den_part denprod,
    crs.PrefixDoc, crs.SeriaDoc, crs.NrDoc, crs.DataDoc, crs.DataMisc,
    CASE crs.tipd WHEN 1 THEN crs.prefixdoc END DIntrPrefix, CASE crs.tipd WHEN 1 THEN crs.seriadoc END DIntrSeria, CASE crs.tipd WHEN 1 THEN crs.nrdoc END DIntrNR, CASE crs.tipd WHEN 1 THEN crs.datadoc END DIntrData,
    CASE crs.tipd WHEN 2 THEN crs.prefixdoc END DIesPrefix , CASE crs.tipd WHEN 2 THEN crs.seriadoc END DIesSeria,  CASE crs.tipd WHEN 2 THEN crs.nrdoc END DIesNr,  CASE crs.tipd WHEN 2 THEN crs.datadoc END DIesData,
    crs.ordine, COALESCE( nsub.den_subunit, gestprod.den_gest, gestdest.den_gest, part.den_part) partener, ng.den_gest, io.den_ioart,ncont.simbol,loc.denumire denlocatie,
    ser.serie serii, crs.codlivr1, sub.den_subunit,crs.d1, crs.d2, crs.d3, ncls.den_claseas, nobj.codextern, um.den_um, um1.den_um, um2.den_um, cint.nrdoc, cint.datadoc '||
    current_setting('PKG_LIST_BASE_TRAS.gUserAlias', true)||'
  FROM crs_miscari crs
    INNER JOIN nartobj nobj  ON nobj.codobiect    = crs.codobiect
    INNER JOIN nart n        ON n.codarticol      = nobj.codarticol
    LEFT JOIN npart furn     ON furn.codpart      = crs.furn
    LEFT JOIN npart prod     ON prod.codpart      = nobj.codproducator
    LEFT JOIN npart part     ON part.codpart      = crs.partener AND NOT crs.tipmiscare IN (6, 23, 7, 24, 12, 13)
    LEFT JOIN ngest gestdest ON gestdest.codgest  = crs.partener AND crs.tipmiscare IN (12,13)
    LEFT JOIN nsubunit nsub  ON nsub.codsubunit   = crs.codsubunit AND crs.tipmiscare IN (6,23)
    LEFT JOIN ngest gestprod ON gestprod.codgest  = crs.codgestprod AND crs.tipmiscare IN (7,24)
    LEFT JOIN ngest ng       ON ng.codgest        = crs.gest
    LEFT JOIN ioart io       ON io.codioart       = crs.codioart
    LEFT JOIN ioart1 io1     ON io1.codioart      = crs.codioart AND crs.an*12+crs.luna BETWEEN io1.alstart AND io1.alstop
    LEFT JOIN ncont ncont    ON ncont.codcont     = io1.cont
    LEFT JOIN nlocatii loc   ON loc.codlocatie    = crs.codlocatie
    LEFT JOIN nirstoc ns     ON ns.codnirstoc     = crs.codnirstoc
    LEFT JOIN nirstoc1 ns1   ON ns1.codnirstoc    = crs.codnirstoc
    LEFT JOIN nirstoc nsroot ON nsroot.codnirstoc = ns1.codnirstocorig
    LEFT JOIN nirser nser    ON nser.codnirser    = crs.codnirser
    LEFT JOIN nserii ser     ON ser.codserie      = crs.codserie
    LEFT JOIN nsubunit sub   ON sub.codsubunit    = crs.subunitatea_doc
    LEFT JOIN nclaseas ncls  ON ncls.codclaseas   = n.clasastatist
    LEFT JOIN num um         ON um.codum          = n.um
    LEFT JOIN num um1        ON um1.codum         = n.um1
    LEFT JOIN num um2        ON um2.codum         = n.um2
    LEFT JOIN num1           ON num1.codum        = n.um and num1.secundara = 0
    LEFT JOIN nartamb aa     ON aa.codobiect      = crs.codobiect and aa.umsec = num1.codum1
    LEFT JOIN comanda cint   ON cint.codcomanda   = crs.codcmdint'||
    current_setting('PKG_LIST_BASE_TRAS.gSuplJoins', true)||'
  WHERE io1.mg &lt;&gt; 5
    AND EXISTS (
      SELECT 1
      FROM TMP_MANEVRA_LISTE
      WHERE FILTRU  = ''CODOBIECT'' AND VALOARE = To_Char(CRS.CODOBIECT)
        AND FILTRU1 = ''CODSERIE''  AND Coalesce(VALOARE1,''-1'') = CASE WHEN Coalesce(VALOARE1,''-1'') = ''-1'' THEN Coalesce(VALOARE1,''-1'') ELSE TO_CHAR(CRS.CODSERIE) END
        AND FILTRU2 = ''SERIELOT''  AND Coalesce(VALOARE2,''-1'') = CASE WHEN Coalesce(VALOARE2,''-1'') = ''-1'' THEN Coalesce(VALOARE2,''-1'') ELSE NS.SERIELOT           END
        AND FILTRU3 = ''TG''        AND Coalesce(VALOARE3,''-1'') = CASE WHEN Coalesce(VALOARE3,''-1'') = ''-1'' THEN Coalesce(VALOARE3,''-1'') ELSE TO_CHAR(COALESCE(NSER.TG,NS.TG),''DD.MM.YYYY'') END
    )';

  PERFORM LIST_EXECUTE_IMMEDIATE(pInsert||sqlwith1||sqlSelect, 0, 0);
SET ENABLE_NESTLOOP TO FALSE;
  PERFORM LIST_EXECUTE_IMMEDIATE(pInsert||sqlwith2||sqlSelect, 0, 0);
  PERFORM LIST_EXECUTE_IMMEDIATE(pInsert||sqlwith3||sqlSelect, 0, 0);
SET ENABLE_NESTLOOP TO TRUE;
  PERFORM LIST_EXECUTE_IMMEDIATE(pInsert||sqlwith4||sqlSelect, 0, 0);
  PERFORM LIST_EXECUTE_IMMEDIATE(pInsert||sqlwith5||sqlSelect, 0, 0);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_jurnvanz_processlist</obj_name>
  <obj_hashval>a53736e10d6097a8642d1abf641d5e81</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_jurnvanz_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC            RECORD;

  sSelWith        TEXT;

  sSelTranz1      TEXT;
  sSelTranz2      TEXT;
  sSelTranz3      TEXT;
  sSelTranz4      TEXT;
  sSelTranz5      TEXT;
  sSelTranz6      TEXT;

  sSelTranzX      TEXT;

  sInsert         TEXT;
  sSelA           TEXT;
  sSelX           TEXT;
  sTIPTVADOC      TEXT;
  sCondLuna       TEXT;
  sPjTva          VARCHAR;
  vISIVB          BOOLEAN;
  vCodTvaImplicit numeric;

  sIDisc          VARCHAR;
  sXDisc          VARCHAR;
  sDRTVAInc       VARCHAR;
  auxWhere        VARCHAR;
  sWhere          VARCHAR := '';
  cModEditJurn    NUMERIC;
  vTVA0FaraJurnal VARCHAR;
  sFiltruCodArt   VARCHAR;
  vCountArt       NUMERIC := 0;
  gSuplCols       VARCHAR := '';
  gUserFields     VARCHAR := '';
  gUserAlias      VARCHAR := '';
  gNullAlias      VARCHAR := '';
  gSuplJoins      VARCHAR := '';
  vTip            NUMERIC;
  vAnLista        NUMERIC;
  vLunaLista      NUMERIC;
  vSubunit        NUMERIC;
  vZileTVAInc     INTEGER;
  sAnLunaIni      VARCHAR;
  sAnLunaFin      VARCHAR;
  vCountDebug     INTEGER;
BEGIN
  --Stef 23.12.2025 - sinc. Oracle
  --Florin 09.12.2025 - sinc. Oracle
  --Florin 02.12.2025 - sinc. Oracle
  --Stef 22.08.2025 - sinc. Oracle
  --Florin 19.08.2025 - sinc. Oracle
  --Florin 14.01.2024 - fixat 64457
  --Florin 27.12.2024 - sinc. Oracle
  --Stef 20.12.2024 - sinc. Oracle
  CALL create_wm_temps_flag('JURNVANZ');

  CREATE TEMPORARY TABLE if not EXISTS bulk_codies (codies NUMERIC(20)) ON COMMIT PRESERVE ROWS;

  sTIPTVADOC := ',
    CASE
      WHEN Coalesce(intr.tiptva, 0) = 1 THEN ''Taxare normala''
      WHEN Coalesce(intr.tiptva, 0) = 2 THEN ''Taxare inversa''
      WHEN Coalesce(intr.tiptva, 0) = 3 THEN ''Tranzactie triunghiulara''
      WHEN Coalesce(intr.tiptva, 0) = 4 THEN ''Suspendare temporara''
      WHEN Coalesce(ies.tiptva,  0) = 1 THEN ''Taxare normala''
      WHEN Coalesce(ies.tiptva,  0) = 2 THEN ''Taxare inversa''
      WHEN Coalesce(ies.tiptva,  0) = 3 THEN ''Taxare triunghiulara''
      WHEN Coalesce(ies.tiptva,  0) = 4 THEN ''Prestari in afara Romaniei''
      WHEN Coalesce(ies.tiptva,  0) = 5 THEN ''intracom.,scutit, cu drept de ded.(lit.a/d)''
      WHEN Coalesce(ies.tiptva,  0) = 6 THEN ''intracom.,scutit, cu drept de ded.(lit.b/c)''
      WHEN Coalesce(ies.tiptva,  0) = 7 THEN ''regim special(art.1521, 1522)''
      ELSE NULL
    END TIPTVADOC ';

  gSuplCols := 'NPART NP, NPARTCODFISC FISCD, NPARTCODFISC FISCP, NCONT N, NSUBUNIT SUB, NAGENDA SDOC, NAGENDA SSOC, NLOCALIT L, NTARI T, DOCCARNETE DC, INTRARI INTR, IESIRI IES';
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_JURNVANZ.gSuplCols', gSuplCols, false);

  PERFORM pkg_globals_SetSeparator(',');
  CALL PRC_AL_CHECK('nsubunit1',0);
  IF aLISTID &gt; 0 THEN
    vSubunit := getsubunitate();
    BEGIN
      SELECT Coalesce(ModEditareJurnal, 0)
      INTO cModEditJurn
      FROM NSUBUNIT1
      WHERE CodSubunit = vSubunit AND getanlunalucru() BETWEEN ALSTART AND ALSTOP;
    EXCEPTION
      WHEN NO_DATA_FOUND THEN cModEditJurn := 0;
    END;
    cModEditJurn := Coalesce(cModEditJurn,0);
    IF cModEditJurn = 0 THEN
      cModEditJurn := fnc_GetValConstanta('ModEditareJurnal', getanlucru(), getlunalucru())::numeric;
      cModEditJurn := Coalesce(cModEditJurn,0);
    END IF;
    vTip := CASE WHEN cModEditJurn = 2 AND Mod(getlunalucru(),3) = 0 THEN 1 ELSE 0 END;
    PERFORM PKG_LIST_BASE_JURNVANZ_SetPerioada(getanlucru(), getlunalucru(), vTip, vSubunit, 0);
  END IF;

  vAnLista   := case when current_setting('PKG_LIST_BASE_JURNVANZ.vAnLista'  , true) is null or current_setting('PKG_LIST_BASE_JURNVANZ.vAnLista'  , true) = '' then 0 else current_setting('PKG_LIST_BASE_JURNVANZ.vAnLista'  , true)::NUMERIC end;
  vLunaLista := case when current_setting('PKG_LIST_BASE_JURNVANZ.vLunaLista', true) is null or current_setting('PKG_LIST_BASE_JURNVANZ.vLunaLista', true) = '' then 0 else current_setting('PKG_LIST_BASE_JURNVANZ.vLunaLista', true)::NUMERIC end;
  vSubunit   := case when current_setting('PKG_LIST_BASE_JURNVANZ.vSubunit',   true) is null or current_setting('PKG_LIST_BASE_JURNVANZ.vSubunit',  true)  = '' then 0 else current_setting('PKG_LIST_BASE_JURNVANZ.vSubunit',   true)::NUMERIC end;
  sAnLunaIni := current_setting('PKG_LIST_BASE_JURNVANZ.vAnLunaIni', true);
  sAnLunaFin := current_setting('PKG_LIST_BASE_JURNVANZ.vAnLunaFin', true);
  vISIVB          := Coalesce(NULLIF(fnc_GetValConstanta('InclServInValBunuri',vAnLista,vLunaLista), ''), '0') = '1';
  vTVA0FaraJurnal := Coalesce(NULLIF(fnc_GetValConstanta('TVA0FaraJurnal', vAnLista, vLunaLista), ''), '-1');
  vCodTvaImplicit := Coalesce(nullif(fnc_GetValConstanta('TIPTVAImplicit', vAnLista,vLunaLista), ''), '0');
  SELECT To_Char(Coalesce(Max(PROCENT),0)) INTO sPjTva FROM NTVA1 WHERE CODTVA = vCodTvaImplicit AND vAnLista*12+vLunaLista BETWEEN ALSTART AND ALSTOP;
  IF  vTVA0FaraJurnal &lt;&gt; '-1' THEN
    IF sAnLunaIni = sAnLunaFin
      THEN sCondLuna := ' AND '||sAnLunaFin||' BETWEEN ALSTART AND ALSTOP';
      ELSE sCondLuna := ' AND '||sAnLunaFin||' &gt;= ALSTART AND '||sAnLunaIni||' &lt;= ALSTOP';
    END IF;
    CALL PRC_AL_CHECK('nart1');

    DELETE FROM TMP_MANEVRA;
    PERFORM LIST_EXECUTE_IMMEDIATE('INSERT INTO TMP_MANEVRA SELECT DISTINCT CodArticol FROM NART1 WHERE CodTva IN (' || Coalesce(vTVA0FaraJurnal,'') || ')', aListID, aListVer);

    FOR vRec IN (SELECT CodUnic FROM TMP_MANEVRA) LOOP
      IF  vCountArt = 0 THEN
        sFiltruCodArt := (vrec.CodUnic)::varchar;
      ELSE
        sFiltruCodArt := Coalesce(sFiltruCodArt,'') || ',' || Coalesce((vrec.CodUnic)::varchar ,'');
      END IF;

      vCountArt := vCountArt + 1;
    END LOOP;

    IF  vCountArt &gt; 0 THEN
      sFiltruCodArt := '
        AND NOT Coalesce(o.CodArticol,0) IN (' || Coalesce(sFiltruCodArt::varchar ,'') || ')';
    ELSE
      sFiltruCodArt := '';
    END IF;
  END IF;
  sFiltruCodArt := Coalesce(sFiltruCodArt, '');

  auxWhere := '
    WHERE ';

  IF current_setting('PKG_LIST_BASE_JURNVANZ.bExclNEA', true) THEN
    sWhere := Coalesce(sWhere,'') || Coalesce(auxWhere,'') || 'Coalesce(SUB.NoEconomicActiv, 0) = 0';
    auxWhere := '
        AND ';
  END IF;
  IF  sAnLunaIni = sAnLunaFin THEN
    sCondLuna := '= ' || sAnLunaFin;
  ELSE
    sCondLuna := 'BETWEEN ' || sAnLunaIni||' AND '||sAnLunaFin;
  END IF;

  sIDisc := '
  SELECT DISTINCT i.codies
  FROM iesiri i INNER JOIN iesiri1 i1 ON i1.codies = i.codies
  WHERE I.TIPDOC IN (16,19,26) AND Coalesce(I.INFOCM,0) = 0 AND I.ANULAT = 0 AND I.OPERAT = 1 AND Coalesce(I.TIPFACTURA,0) &lt;&gt; 7 AND BITAND(Coalesce(i.Flags, 0), 1) = 0
    AND I1.TIPLINIE IN (''G'',''T'')
    AND Coalesce(I1.TVA,0) &lt;&gt; 0
    AND I.AN*12+I.LUNA '||sCondLuna||'
    AND NOT EXISTS (SELECT J1.CODDOC FROM TMP_JURNAL1 J1 WHERE J1.TIPDOC = I.TIPDOC AND J1.CODDOC = I.CODIES) '||
    PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', NULL, NULL, vSubunit);

  sXDisc :='
  SELECT DISTINCT i.codies
  FROM iesiri i INNER JOIN iesiri1 i1 ON i1.codies = i.codies
  WHERE I.TIPDOC IN (16,19,26) AND Coalesce(I.INFOCM,0) = 0 AND I.ANULAT = 0 AND I.OPERAT = 1 AND Coalesce(I.TIPFACTURA,0) &lt;&gt; 7 AND BITAND(Coalesce(i.Flags, 0), 1) = 0
    AND I.CODIES IN (SELECT DISTINCT CODDOC FROM TMP_LST_TVAINCAS WHERE TIPDOC IN (16,19,26))
    AND I1.TIPLINIE IN (''G'',''T'') '||
    PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', NULL, NULL, vSubunit);

  sInsert := 'INSERT INTO ' || Coalesce(tmpname,'') || '(
    NAV_CODDOC,NAV_CodDoc1,NAV_TIPDOC,ORDDOC,
    DATADOC,NRDOC,NRI,PREFIXDOC,SERIADOC,
    DEN_PART,
    CODFISCAL,
    VALDOC,
    BAZA_MED, TVA_MED,
    BAZA_MIN, TVA_MIN,
    BAZA_MAX, TVA_MAX,
    BAZA_REGMIN, TVA_REGMIN,
    BAZA_REGMAX, TVA_REGMAX,
    BAZA_REG, TVA_REG,
    BAZA_REG2,TVA_REG2,
    BAZA_REG3,TVA_REG3,
    BAZA_REG4,TVA_REG4,
    BAZA_REG5,TVA_REG5,
    BUNURI_CU_TI, TVA_BUNURI_CU_TI,
    BUNURI_CU_TI_BMED, BUNURI_CU_TI_TMED,
    BUNURI_CU_TI_BMIN, BUNURI_CU_TI_TMIN,
    BUNURI_CU_TI_BMAX, BUNURI_CU_TI_TMAX,
    BUNURI_CU_TI_BREG, BUNURI_CU_TI_TREG,
    BUNURI_CU_TI_BREG2,BUNURI_CU_TI_TREG2,
    BUNURI_CU_TI_BREG3,BUNURI_CU_TI_TREG3,
    BUNURI_CU_TI_BREG4,BUNURI_CU_TI_TREG4,
    BUNURI_CU_TI_BREG5,BUNURI_CU_TI_TREG5,
    NONRO_DED,   SERV_NONRO_DED,
    NONRO_NONDED,SERV_NONRO_NONDED,
    RO_DED,RO_NONDED,
    A_1521_22, TVA_A_311_322, A_311_322_BMED, A_311_322_TMED, A_311_322_BMIN, A_311_322_TMIN, A_311_322_BMAX, A_311_322_TMAX,
    ART143AD, ART143BC, SERV143BC,
    ART294AB, ART294CD,
    ART292,
    BAZA_SERV_278, TVA_SERV_278,
    BAZA_OSS, TVA_OSS,
    OPER_NEIMP, OBS,
    SUBUNITATEA,UE,TI,DATACDOC,OPERATOR,ANDOC,LUNADOC,TVALAINC,
    RESTOL,
    BAZAOBLIG,
    TVANOBLIG,
    INCPREFIX, INCTIP, INCNR, INCDATA,
    INCVAL, INCVFT, INCTVA,
    RESTVAL, RESTTVA,
    SOLDVAL,
    SOLDTVA,
    DOCVAL, DOCBAZA, DOCTVA,
    TIPTVADOC ' || gUserFields || ')';
  sSelWith := '
  WITH
  CRS_JV_TRANZACTII AS (';

  sSelTranz1 := '
    SELECT
      I1.codies coddoc, NULL::NUMERIC coddoc1, I.tipdoc, I.datadoc, I.nrdoc, I.Nri, I.prefixdoc, I.carnetdoc, I.seriadoc, I.partener, I.codlocatie, I.codfiscal, CASE WHEN I.tipdoc IN (19, 26) THEN Coalesce(i.tvaincasare,0) ELSE 0 END tvainc,
      Coalesce(
        CASE
          WHEN I.TIPTVA IN (7,8) AND I.AN*12+I.LUNA&gt;=2016*12+7 AND I.TIPDOC = 19
          THEN (
            SELECT SUM(L1.CANT * Coalesce(LV.PRETACHIZ,NS.PRET - NS.ADAOS,0))
            FROM livr1 l1
              INNER JOIN livr    l  ON l1.codlivr    = l.codlivr
              LEFT  JOIN nirstoc ns ON ns.codnirstoc = l1.codnirstoc
              LEFT  JOIN livrval lv ON lv.codlivr1   = l1.codlivr1
            WHERE L1.CODIES1 = I1.CODIES1 AND L.CODIES = I.CODIES AND L.TIPLIVR = I.TIPDOC
          )
          WHEN I.TIPTVA IN (7,8) AND I.AN*12+I.LUNA&gt;=2016*12+7 AND I.TIPDOC = 26
          THEN (
            SELECT SUM(L1.CANT * Coalesce(LV.PRETACHIZ,NS.PRET - NS.ADAOS,0))
            FROM ieslink ilae
              INNER JOIN iesiri1 ae1  ON ae1.codies1   = ilae.codlinieaviz
              INNER JOIN livr1   l1   ON l1.codies1    = ae1.codies1
              INNER JOIN livr    l    ON l.codlivr     = l1.codlivr AND l.codies = ae1.codies AND l.tiplivr = 20
              LEFT  JOIN nirstoc ns   ON ns.codnirstoc = l1.codnirstoc
              LEFT  JOIN livrval lv   ON lv.codlivr1   = l1.codlivr1
            WHERE ilae.codies1  = i1.codies1
          )
          ELSE 0
        END, 0
      ) VA_311_312,
      CASE
        WHEN I.TIPDOC IN (14)    THEN L1.BAZA
        WHEN I.TIPDOC IN (16,21) THEN Coalesce(I1.VALFIN,I1.CANT*I1.PU,0) - Coalesce(I1.TVAFIN,I1.TVA,0)
        ELSE                          Coalesce(I1.VALFIN,I1.CANT*I1.PU,0)
      END *
      CASE WHEN I1.VALFIN IS NULL THEN 1+Coalesce(i1.procdisc/100,0) ELSE 1 END *
      Coalesce(NULLIF(CASE WHEN CL.VAL = 1 THEN I1.CursFacturaAvans END,0), NULLIF(I.Curs,0),1) baza,
      CASE
        WHEN I.TipDoc = 14 AND L1.NR_L1 = 1 THEN Coalesce(I1.TVA,0)
        WHEN I.TipDoc = 14 AND L1.NR_LX = 0 THEN Coalesce(I1.TVA,0)
        WHEN I.TipDoc = 14 AND L1.BAZATOT &lt;&gt; 0 THEN Coalesce(I1.TVA,0) * L1.Baza/L1.BAZATOT
        WHEN I.TipDoc = 14 THEN Coalesce(I1.TVA,0)/L1.NR_L1
        ELSE Coalesce(I1.TVAFIN, I1.TVA,0)
      END *
      CASE WHEN I1.VALFIN IS NULL THEN 1+Coalesce(i1.procdisc/100,0) ELSE 1 END *
      Coalesce(NULLIF(CASE WHEN CL.VAL = 1 THEN I1.CursFacturaAvans END,0), NULLIF(I.Curs,0),1) tva,
      PKG_LIST_BASE_UTILS_MATCH_TVA(
        CASE
          WHEN I.TIPDOC = 14                AND L1.Baza = 0               THEN '||sPjTva||'
          WHEN I.TipDoc = 14                AND L1.NR_L1 = 1              THEN Coalesce(I1.TVA,0) * 100 /L1.BAZA
          WHEN I.TipDoc = 14                AND L1.BAZATOT &lt;&gt; 0           THEN Coalesce(I1.TVA,0) * 100 /L1.BAZATOT
          WHEN I.TIPDOC = 14                                              THEN Coalesce(I1.TVA,0)/L1.NR_LX * 100 / L1.BAZA
          WHEN I.TIPTVA IN (7,8)            AND I.AN*12+I.LUNA&gt;=2016*12+7 THEN T1.PROCENT
          ELSE PKG_LIST_BASE_UTILS_CALC_PROC_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, T1.PROCENT, I.ROTEFACT)
        END,
        '||sAnLunaFin||'
      ) CAZTVA,
      I1.tiplinie,  Coalesce(i1.taxa, 0) taxa,
      CASE WHEN I.tipdoc = 14 AND Coalesce(I1.TVA,0)&lt;&gt;0 THEN 1 ELSE I.tiptva        END tiptva,
      CASE WHEN I.tipdoc = 14 AND Coalesce(I1.TVA,0)&lt;&gt;0 THEN 1 ELSE I.tiptranzactie END tiptranzactie,
      CASE
        WHEN (Coalesce(I1.TVA,0) = 0) AND (I1.tiplinie IN (''='',''S'',''V'',''R'')) THEN PKG_LIST_BASE_UTILS_getTipTVA0(I1.codobiect,I.an,I.luna)
        ELSE 0
      END TIPTVA0,
      CASE
        WHEN I.TIPDOC = 14 THEN SUM( (L1.BAZATOT + Coalesce(I1.TVA,0)) / l1.nr_l1) OVER (PARTITION BY I.CODIES)
        ELSE '||CASE
                  WHEN vCountArt = 0
                  THEN 'I.VALDOC'
                  ELSE 'Sum((I1.CANT*I1.PU+Coalesce(I1.TVA,0)) * I1.COEFDISCMAJ * CASE WHEN I1.PU = 0 THEN 0 WHEN I1.PU = I1.PRETORIG THEN 1 ELSE I1.PRETORIG / I1.PU END) OVER (PARTITION BY I.CODIES)'
                END::varchar||'
      END * Coalesce(NULLIF(I.Curs,0),1) valdoc,
      i.obs, 0 codcont, i.subunitatea, i.datacreare, i.userid, i.an, i.luna,
      i.valdoc            * Coalesce(NULLIF(I.Curs,0),1) docval,
      (i.valdoc-i.tvadoc) * Coalesce(NULLIF(I.Curs,0),1) docbaza,
      i.tvadoc            * Coalesce(NULLIF(I.Curs,0),1) doctva,
      CASE WHEN CL.VAL = 1 THEN 1 ELSE 0 END calc,
      0 CAZ_B_CU_TI,
      '||CASE WHEN vISIVB THEN 'Max(CASE WHEN I1.tiplinie = ''='' THEN 1 ELSE 0 END) OVER (PARTITION BY i.codies)' ELSE '0' END||' DoServCaStoc,
      CASE
        WHEN I1.tiplinie &lt;&gt; ''V''
        THEN I1.tiplinie
        ELSE
          CASE Max(CASE WHEN I1.tiplinie = ''S'' THEN 1 ELSE 0 END) OVER (PARTITION BY i.codies) +
               Max(CASE WHEN I1.tiplinie = ''='' THEN 2 ELSE 0 END) OVER (PARTITION BY i.codies)
            WHEN 1 THEN ''S''
            WHEN 2 THEN I1.tiplinie
            WHEN 3 THEN '||CASE WHEN vISIVB THEN 'I1.tiplinie' ELSE '''B''' END ||'
            ELSE I1.tiplinie
          END
      END TipLinieEXTRA,
      CASE WHEN Coalesce(i.an*100+i.luna, 0) = To_Number(Coalesce(To_Char(Coalesce(i.datatva, i.datadoc), ''yyyymm''),''0'')) THEN 0 ELSE 1 END DOC_REG
    FROM iesiri i
      INNER JOIN iesiri1 i1   ON i1.codies     = i.codies
      LEFT  JOIN iesiri1 i1st ON i1st.codies1  = i1.codies1storno
      LEFT  JOIN iesiri  ist  ON ist.codies    = i1st.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
      LEFT  JOIN (
        SELECT
          I.NrDoc, I.CodIes, L1.Codies1, L1.CANT * Coalesce(LV.PRETACHIZ,NS.PRET - NS.ADAOS,0) BAZA,
          SUM(L1.CANT * Coalesce(LV.PRETACHIZ,NS.PRET - NS.ADAOS,0)) OVER (PARTITION BY I.CodIes, L1.Codies1) BAZATOT,
          SUM(CASE WHEN Coalesce(LV.PRETACHIZ,NS.PRET - NS.ADAOS,0) = 0 THEN 0 ELSE 1 END) OVER (PARTITION BY I.CodIes, L1.Codies1) NR_LX,
          COUNT(1) OVER (PARTITION BY I.CodIes, L1.Codies1) NR_L1
        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 NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
          LEFT JOIN LIVRVAL LV ON LV.CODLIVR1 = L1.CODLIVR1
        WHERE I.TIPDOC = 14 AND I.AN*12+I.LUNA '||sCondLuna||' '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', NULL, NULL, vSubunit)|| '
      ) L1 ON L1.CODIES1 = I1.CODIES1 AND L1.Codies = I1.CODIES
      LEFT  JOIN (
        SELECT I.CodIes, SUM(Coalesce(i1.valdiscpret, 0)) valdisclin
        FROM IESIRI I INNER JOIN IESIRI1 I1 ON i1.codies = i.codies
        WHERE I.TIPDOC = 16 AND I.AN*12+I.LUNA '||sCondLuna||' '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', NULL, NULL, vSubunit)|| '
        GROUP BY I.CodIes
      ) MD ON MD.CODIES = I.CODIES
      LEFT  JOIN tmp_al_curslinie cl ON cl.AL = i.an*12+i.luna
    WHERE Coalesce(I.INFOCM,0) = 0 AND I.ANULAT = 0 AND I.OPERAT = 1 AND Coalesce(I.TIPFACTURA,0) &lt;&gt; 7
      AND I.AN*12+I.LUNA '||sCondLuna||' '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', NULL, NULL, vSubunit)||
      sFiltruCodArt||'
      AND NOT EXISTS (SELECT J1.CODDOC FROM TMP_JURNAL1 J1 WHERE J1.TIPDOC = I.TIPDOC AND J1.CODDOC = I.CODIES)
      AND I1.TIPLINIE IN (''='',''S'',''V'',''R'')
      AND I.TIPDOC IN (14,16,19,21,22,26)
      AND CASE I.TIPDOC WHEN 14 THEN Coalesce(I1.TVA,0) ELSE 1 END &lt;&gt; 0
      AND CASE I.TIPDOC WHEN 14 THEN L1.NR_L1           ELSE 1 END &lt;&gt; 0
      AND TO_CHAR(Coalesce(I1.CODOBIECT,-100)) &lt;&gt; CASE WHEN I.TIPDOC = 16 THEN Coalesce(fnc_getvalconstanta(''ArtIncasUlterior'',I.AN,I.LUNA),''0'') ELSE ''0'' END
      AND NOT I.CODIES IN (SELECT DISTINCT CODDOC FROM TMP_LST_TVAINCAS WHERE TIPDOC IN (14,16,19,21,22,26))
      AND Coalesce(i.tiptranzactie, 0) &lt;&gt; 5 AND Coalesce(i1.impozabil, 0) &lt;&gt; 4';

  sSelTranz2 := '
    SELECT
      I1.codintr coddoc, NULL::NUMERIC coddoc1, I.tipdoc, I.datadoc, I.nrdoc, I.nri, I.prefixdoc, I.carnetdoc, I.seriadoc, I.partener, I.codlocatie, I.codfiscal, CASE WHEN I.tipdoc IN (1, 9) THEN Coalesce(i.tvaincasare,0) ELSE 0 END tvainc,
      0 VA_311_312,
      CASE
        WHEN I.TIPDOC = 5 AND D1.TIPLINIE IN (''X'', ''A'', ''C'')    THEN Coalesce(D1.VALOARETAXA,0)
        WHEN I.TIPDOC = 5 AND I.TIPTRANZACTIE = 2                     THEN Coalesce(D1.CANT * D1.PRETIMPORT,0)
        WHEN I.TIPDOC = 5                                             THEN Coalesce(D1.CANT * D1.PRETIMPORT,0)
        WHEN I1.TIPLINIE IN (''G'',''T'')                             THEN (I1.RESTFACT - Coalesce(CASE WHEN I.TIPDOC= 3 THEN Coalesce(I1.TVA,0) END, 0))*Coalesce(NULLIF(CASE WHEN CL.VAL = 1 THEN I1.CursFacturaAvans END,0), NULLIF(I.Curs,0),1)
        ELSE (Coalesce(I1.PU*I1.CANT,0)-Coalesce(CASE WHEN I.TIPDOC=3 THEN Coalesce(I1.TVA,0) END,0)) * Coalesce(NULLIF(CASE WHEN CL.VAL = 1 THEN I1.CursFacturaAvans END,0), NULLIF(I.Curs,0),1)
      END BAZA,
      CASE WHEN I.TIPDOC = 5 THEN Coalesce(d1.TVA,0) ELSE Coalesce(I1.TVA,0) * Coalesce(NULLIF(CASE WHEN CL.VAL = 1 THEN I1.CursFacturaAvans END,0), NULLIF(I.Curs,0),1) END tva,
      PKG_LIST_BASE_UTILS_MATCH_TVA(
        CASE
          WHEN I1.TIPLINIE IN (''='',''S'',''V'',''R'') AND (I1.CANT * Coalesce(I1.PU,0) = 0)               THEN T1.PROCENT
          WHEN I1.TIPLINIE IN (''G'',''T'')             AND Coalesce(I1.RESTFACT,0) = 0                     THEN '||sPjTva||'
          WHEN I1.TIPLINIE IN (''G'',''T'')                                                                 THEN Coalesce(I1.TVA,0)/I1.RESTFACT*100
          WHEN I.TIPDOC = 5 AND D1.TIPLINIE IN (''X'', ''A'', ''C'') AND Coalesce(D1.VALOARETAXA,0) = 0     THEN '||sPjTva||'
          WHEN I.TIPDOC = 5 AND D1.TIPLINIE IN (''X'', ''A'', ''C'')                                        THEN Coalesce(d1.TVA,0)/ D1.VALOARETAXA*100
          WHEN I.TIPDOC = 5 AND Coalesce(D1.CANT * D1.PRETIMPORT,0) = 0                                     THEN T1.PROCENT
          WHEN I.TIPDOC = 5                                                                                 THEN Coalesce(d1.TVA,0) / (D1.CANT * D1.PRETIMPORT) *100
          ELSE PKG_LIST_BASE_UTILS_CALC_PROC_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, T1.PROCENT, I.ROTEFACT)
        END,
        '||sAnLunaFin||'
      ) CAZTVA,
      I1.tiplinie, 0 taxa, /*I.tiptva*/ 2 TIPTVA, I.tiptranzactie, 0 tiptva0,
      CASE
        WHEN I.VALDOC = 0 THEN 1'||
      CASE
        WHEN vCountArt &lt;&gt; 0 THEN ''
        ELSE '
        WHEN I.TIPTVA IN (2,8) THEN 1'
      END ||'
        ELSE Sum( (I1.CANT*I1.PU+Coalesce(I1.TVA,0)) * I1.COEFDISCMAJ * CASE WHEN I1.PU = 0 THEN 0 WHEN I1.PU = I1.PRETORIG THEN 1 ELSE I1.PRETORIG / I1.PU END) OVER (PARTITION BY I.CODINTR)/I.VALDOC
      END *
      (I.VALDOC * Coalesce(NULLIF(CASE WHEN CL.VAL = 1 THEN I1.CursFacturaAvans END,0), NULLIF(I.Curs,0),1) + CASE WHEN Coalesce(I.TIPTRANZACTIE, 0) = 2 THEN Coalesce(d.TVADOCVAMA,0) ELSE Coalesce(d.VALSUPLIM,0) + Coalesce(d.VALDOCVAMA,0) END) valdoc,
      i.obs,0 codcont, i.subunitatea, i.datacreare, i.userid, i.an, i.luna,
      i.valdoc            * Coalesce(NULLIF(I.Curs,0),1) docval,
      (i.valdoc-i.tvadoc) * Coalesce(NULLIF(I.Curs,0),1) docbaza,
      i.tvadoc            * Coalesce(NULLIF(I.Curs,0),1) doctva,
      CASE WHEN CL.VAL = 1 THEN 1 ELSE 0 END calc,
      1 CAZ_B_CU_TI,
      '||CASE WHEN vISIVB THEN 'Max(CASE WHEN I1.tiplinie = ''='' THEN 1 ELSE 0 END) OVER (PARTITION BY i.codintr)' ELSE '0' END||' DoServCaStoc,
      CASE
        WHEN I1.tiplinie &lt;&gt; ''V''
        THEN I1.tiplinie
        ELSE
          CASE Max(CASE WHEN I1.tiplinie = ''S'' THEN 1 ELSE 0 END) OVER (PARTITION BY i.codintr) +
               Max(CASE WHEN I1.tiplinie = ''='' THEN 2 ELSE 0 END) OVER (PARTITION BY i.codintr)
            WHEN 1 THEN ''S''
            WHEN 2 THEN I1.tiplinie
            WHEN 3 THEN '||CASE WHEN vISIVB THEN 'I1.tiplinie' ELSE '''B''' END ||'
            ELSE I1.tiplinie
          END
      END TipLinieEXTRA,
      CASE WHEN Coalesce(i.an*100+i.luna, 0) = To_Number(Coalesce(To_Char(Coalesce(i.datatva, i.datadoc), ''yyyymm''),''0'')) THEN 0 ELSE 1 END DOC_REG
    FROM intrari i
      INNER JOIN intrari1 i1   ON I1.codintr    = I.codintr
      LEFT  JOIN intrari1 i1st ON i1st.codintr1 = i1.codintr1storno
      LEFT  JOIN intrari  ist  ON ist.codintr   = i1st.codintr
      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
      LEFT  JOIN dvi1     d1   ON d1.codintr1   = i1.codintr1
      LEFT  JOIN dvi      d    ON d.codintr     = i.codintr
      LEFT  JOIN tmp_al_curslinie cl ON cl.AL = i.an*12+i.luna
    WHERE I.AN*12+I.LUNA '||sCondLuna||' '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', NULL, NULL, vSubunit)||sFiltruCodArt|| '
      AND I.ANULAT = 0 AND I.OPERAT = 1
      AND (I.TIPTVA IN (2,8) OR Coalesce(i1.impozabil, 0) = 3)
      AND I.TIPDOC NOT IN (2,6)
      AND Coalesce(D.TIPIMPORT,0) = 0
      AND NOT (I.TIPTRANZACTIE = 4 AND I1.TIPLINIE NOT IN (''G''))
      AND NOT (Coalesce(I1.TIPLINIE,''~'') IN (''G'',''T'') AND Coalesce(I1.CONTDISCOUNT,0) = 0)
      AND NOT (Coalesce(I1.TIPLINIE,''~'') IN (''G'',''T'') AND Coalesce(I1.RESTFACT,0) = 0)
      AND NOT (Coalesce(D1.TIPLINIE,''~'') IN (''X'', ''A'', ''C'') AND Coalesce(D.TAXEINCLUSE,0) = 1)
      AND NOT (Coalesce(D1.TIPLINIE,''~'') IN (''X'', ''A'', ''C'') AND Coalesce(D.TAXEPECHELT,0) = 1)
      AND Coalesce(i.tiptranzactie, 0) &lt;&gt; 5 AND Coalesce(i1.impozabil, 0) &lt;&gt; 4';

  sSelTranz3 := '
    SELECT
      I.codintr coddoc, NULL::NUMERIC coddoc1, I.tipdoc, I.datadoc, I.nrdoc, I.nri, I.prefixdoc, I.carnetdoc, I.seriadoc, I.partener, I.codlocatie, I.codfiscal, CASE WHEN I.tipdoc IN (1, 9) THEN Coalesce(i.tvaincasare,0) ELSE 0 END tvainc,
      0 VA_311_312,
      Coalesce(D1.VALOARETAXA,0) BAZA,
      Coalesce(d1.TVA,0) tva,
      PKG_LIST_BASE_UTILS_MATCH_TVA(CASE WHEN Coalesce(D1.VALOARETAXA,0) = 0 THEN '||sPjTva||' ELSE Coalesce(d1.TVA,0)/ D1.VALOARETAXA*100 END, '||sAnLunaFin||') CAZTVA,
      D1.tiplinie, 0 taxa, 2 TIPTVA, I.tiptranzactie, 0 tiptva0,
      (I.VALDOC * Coalesce(NULLIF(CASE WHEN CL.VAL = 1 THEN I1.CursFacturaAvans END,0), NULLIF(I.Curs,0),1) + CASE WHEN Coalesce(I.TIPTRANZACTIE, 0) = 2 THEN Coalesce(d.TVADOCVAMA,0) ELSE Coalesce(d.VALSUPLIM,0) + Coalesce(d.VALDOCVAMA,0) END) valdoc,
      i.obs,0 codcont, i.subunitatea, i.datacreare, i.userid, i.an, i.luna,
      i.valdoc            * Coalesce(NULLIF(I.Curs,0),1) docval,
      (i.valdoc-i.tvadoc) * Coalesce(NULLIF(I.Curs,0),1) docbaza,
      i.tvadoc            * Coalesce(NULLIF(I.Curs,0),1) doctva,
      CASE WHEN CL.VAL = 1 THEN 1 ELSE 0 END calc,
      1 CAZ_B_CU_TI,
      '||CASE WHEN vISIVB THEN 'Max(CASE WHEN D1.tiplinie = ''='' THEN 1 ELSE 0 END) OVER (PARTITION BY i.codintr)' ELSE '0' END||' DoServCaStoc,
      CASE
        WHEN D1.tiplinie &lt;&gt; ''V''
        THEN D1.tiplinie
        else
          CASE Max(CASE WHEN D1.tiplinie = ''S'' THEN 1 ELSE 0 END) OVER (PARTITION BY i.codintr) +
               Max(CASE WHEN D1.tiplinie = ''='' THEN 2 ELSE 0 END) OVER (PARTITION BY i.codintr)
            WHEN 1 THEN ''S''
            WHEN 2 THEN D1.tiplinie
            WHEN 3 THEN '||CASE WHEN vISIVB THEN 'D1.tiplinie' ELSE '''B''' END ||'
            ELSE D1.tiplinie
        END
       END TipLinieEXTRA,
      CASE WHEN Coalesce(i.an*100+i.luna, 0) = To_Number(Coalesce(To_Char(Coalesce(i.datatva, i.datadoc), ''yyyymm''),''0'')) THEN 0 ELSE 1 END DOC_REG
    FROM intrari i
      INNER JOIN dvi      d    ON d.codintr     = i.codintr
      LEFT  JOIN dvi1     d1   ON d1.coddvi     = d.coddvi
      LEFT  JOIN intrari1 i1   ON i1.codintr1   = d1.codintr1 AND i1.codintr = i.codintr
      LEFT  JOIN nartobj  o    ON o.codobiect   = d1.codobiect
      LEFT  JOIN tmp_al_curslinie cl ON cl.AL = i.an*12+i.luna
    WHERE I.AN*12+I.LUNA ' ||sCondLuna||' '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', NULL, NULL, vSubunit)||sFiltruCodArt|| '
      AND I.ANULAT = 0 AND I.OPERAT = 1
      AND I.TIPTVA IN (2,8)
      AND D1.TIPLINIE IN (''X'', ''A'', ''C'') AND Coalesce(D.TAXEINCLUSE,0) = 0 AND Coalesce(D.TAXEPECHELT,0) = 1
      AND d1.codintr1 IS NULL';

  sSelTranz4 := '
    SELECT
      nc.codnc coddoc, NULL::numeric coddoc1, 35 tipdoc, nc.datadoc, nc.nrdoc, NULL nri, ''NC'' prefixdoc, nc.carnetdoc, NULL seriadoc, liniiNC.part as partener, 0 codlocatie, 0 codfiscal, 0 tvainc,
      0 VA_311_312,
      liniinc.baza * Coalesce(NULLIF(nc.curs,0),1) baza,
      liniinc.tva  * Coalesce(NULLIF(nc.curs,0),1) tva,
      CASE
        WHEN liniiNC.Scutit = 1 THEN 0
        ELSE PKG_LIST_BASE_UTILS_MATCH_TVA( CASE WHEN Coalesce(liniinc.baza, 0) = 0 THEN '||sPjTva||' ELSE liniinc.tva * 100/liniinc.baza END, '||sAnLunaFin||')
      END CAZTVA,
      NULL tiplinie, 0 taxa, nc.tiptva, nc.tiptranz as tiptranzactie, 0 tiptva0,
      ( LINIINC.BAZA * Coalesce(NULLIF(nc.curs,0),1)) + (LINIINC.TVA * Coalesce(NULLIF(nc.curs,0),1)) valdoc,
      nc.obs, 0 codcont, nc.subunitatea, nc.datacreare, nc.userid, nc.an, nc.luna,
      nc.valoare * Coalesce(NULLIF(nc.curs,0),1) DOCVAL, 0 DOCBAZA, 0 DOCTVA, 1 CALC,
      CASE WHEN nc.tiptva = 2 AND nc.tiptranz IN (2,3) THEN 1 ELSE 0 END CAZ_B_CU_TI,
      0 DoServCaStoc,
      ''~'' TipLinieEXTRA,
      0 DOC_REG
    FROM (
      SELECT X.CODNC, X.PART, X.SCUTIT, SUM(X.BAZA) baza, SUM(X.TVA) tva
      FROM (
        SELECT
          NC1.CODNC, Coalesce(NULLIF(NC.PART,0), NC1.CODPART) PART,
          CASE WHEN NC1.TIPLINIETVA IN (6)     THEN 1           ELSE 0 END SCUTIT,
          CASE WHEN NC1.TIPLINIETVA IN (2,4,6) THEN NC1.VALOARE ELSE 0 END BAZA,
          CASE WHEN NC1.TIPLINIETVA IN (3,5)   THEN NC1.VALOARE ELSE 0 END TVA
        FROM NC INNER JOIN NC1 ON nc.codnc = nc1.codnc
        WHERE NC.AN*12+NC.LUNA ' || Coalesce(sCondLuna,'') || '
          AND Coalesce(NC.SABLON,0) = 0 ' || PKG_LIST_BASE_UTILS_COND_SUBUNIT('NC', NULL, NULL, vSubunit) || '
          AND ((NC.JURNALTVA = 3) OR (NC.JURNALTVA = 2 AND NC.TIPTVA = 2))
      ) X
      GROUP BY X.CODNC, X.PART, X.SCUTIT
    ) liniiNC LEFT JOIN nc ON nc.codnc = liniiNC.codnc';

  sSelTranz5 := '
    SELECT
      t.codtrezor coddoc, t1.codtrezor1 coddoc1, t.tipdoc, t1.datadoc, t1.nrdoc, t1.nri, t1.doc as prefixdoc, t1.carnetdoc, t1.seriedoc seriadoc, t1.codpart as partener, 0 codlocatie, 0 codfiscal, 0 tvainc,
      0 VA_311_312,
      (o.valoare - Coalesce(g.tva,0)) * Coalesce(NULLIF(g.curs,0),1) * (case when g.semnificatie IN (330, 420) then -1 else 1 end) baza,
      Coalesce(g.tva,0) * Coalesce(NULLIF(g.curs,0),1) * (case when g.semnificatie IN (330, 420) then -1 else 1 end) tva,
      PKG_LIST_BASE_UTILS_MATCH_TVA(Coalesce(Coalesce(g.tva*100,0)/NULLIF(o.valoare-Coalesce(g.tva,0),0),'||sPjTva||'), '||sAnLunaFin||') CAZTVA,
      NULL tiplinie, 0 taxa, 1 tiptva ,1 tiptranzactie, 0 tiptva0, o.valoare * Coalesce(NULLIF(g.curs,0),1) * (case when g.semnificatie in(330, 420) then -1 else 1 end) valdoc,
      T1.OBS, CASE WHEN G.SEMNIFICATIE = 901 THEN O.ICONT ELSE 0 END CODCONT, t.subunitatea, t.datacreare, t.userid, t.an, t.luna,
      t1.valdoc * Coalesce(NULLIF(t1.curs,0),1) DOCVAL, 0 DOCBAZA, 0 DOCTVA, 1 CALC,
      0 CAZ_B_CU_TI,
      0 DoServCaStoc,
      ''~'' TipLinieEXTRA,
      0 DOC_REG
    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 ostins ON ostins.codobligpif = s.codstinspif
    WHERE T.OPERAT = 1 AND T1.ANULAT = 0  '|| PKG_LIST_BASE_UTILS_COND_SUBUNIT('T', NULL, NULL, vSubunit) ||'
      AND T.AN*12+T.LUNA '||sCondLuna||'
      AND ( (O.SEMNIFICATIE IN (330,410,420) AND Coalesce(G.TVA,0) &gt; 0) OR
            (O.SEMNIFICATIE = 901) OR
            (O.SEMNIFICATIE = 320 AND OSTINS.SEMNIFICATIE = 330)
          )';

  sSelTranz6 := '
    SELECT
      c.codcompens coddoc,
      CASE
        WHEN G.SEMNIFICATIE = 1300 AND Coalesce(C.TIPCOMPENS,0) = 5 THEN 1
        WHEN G.SEMNIFICATIE = 1350 AND Coalesce(C.TIPCOMPENS,0) = 5 THEN 2
        ELSE NULL::NUMERIC
      END coddoc1,
      28 tipdoc, c.datadoc, c.nrdoc, NULL nri, ''PV'' prefixdoc, c.carnetdoc, NULL seriadoc, o.codpart as partener, 0 codlocatie, 0 codfiscal, 0 tvainc,
      0 VA_311_312,
      CASE
        WHEN OS.SEMNIFICATIE = 210 AND O.SEMNIFICATIE = 1350 THEN 1
        WHEN OS.SEMNIFICATIE = 330                           THEN 1
        ELSE -1
      END * Sign(O.VALOARE) * (ABS(o.valoare)-ABS(g.tva)) * Coalesce(NULLIF(g.curs,0),1) baza,
      CASE
        WHEN OS.SEMNIFICATIE = 210 AND O.SEMNIFICATIE = 1350 THEN 1
        WHEN OS.SEMNIFICATIE = 330                           THEN 1
        ELSE -1
      END * Sign(O.VALOARE) * ABS(g.tva) * Coalesce(NULLIF(g.curs,0),1) TVA ,
      PKG_LIST_BASE_UTILS_MATCH_TVA(CASE WHEN Coalesce(Abs(o.valoare) - Abs(g.tva),0) = 0 THEN '||sPjTva||' ELSE Abs(G.TVA)*100/(Abs(O.VALOARE)-Abs(G.TVA)) END,'||sAnLunaFin||') CAZTVA,
      NULL tiplinie, 0 taxa, 1 tiptva, 1 tiptranzactie, 0 tiptva0,
      Sum(
        o.valoare * Sign(O.VALOARE) *
        CASE
          WHEN OS.SEMNIFICATIE = 210 AND O.SEMNIFICATIE = 1350 THEN 1
          WHEN OS.SEMNIFICATIE = 330                           THEN 1
          ELSE -1
        END *
        Coalesce(NULLIF(g.curs,0),1)
      ) OVER (PARTITION BY c.codcompens) valdoc,
      c.obsd||'' ; ''||c.obsc obs, 0 codcont,c.subunitatea, c.datacreare, c.userid, c.an, c.luna,
      0 DOCVAL, 0 DOCBAZA, 0 DOCTVA, 1 CALC,
      0 CAZ_B_CU_TI,
      0 DoServCaStoc,
      ''~'' TipLinieEXTRA,
      0 DOC_REG
    FROM compens c
      INNER JOIN general  g  ON c.codcompens      = g.coddoc AND g.tipdoc = 28
      INNER JOIN obligpif o  ON g.codgeneral      = o.codgeneral
      LEFT  JOIN STINGERE S  ON S.CODSTINGATORPIF = O.CODOBLIGPIF
      LEFT  JOIN OBLIGPIF OS ON OS.CODOBLIGPIF    = S.CODSTINSPIF
      INNER JOIN NPART    P  ON P.CODPART         = CASE WHEN O.SEMNIFICATIE = 1350 THEN C.PARTC ELSE C.PARTD END
    WHERE C.AN*12+C.LUNA '||sCondLuna||'
      AND G.SEMNIFICATIE IN (1300,1350)
      AND CASE
            WHEN G.SEMNIFICATIE = 1300 AND Coalesce(C.TIPCOMPENS,0) = 5 AND     OS.SEMNIFICATIE IN (110)      THEN 0
            WHEN G.SEMNIFICATIE = 1300                                  AND NOT OS.SEMNIFICATIE IN (430,1353) THEN 1
            WHEN G.SEMNIFICATIE = 1350                                  AND     OS.SEMNIFICATIE IN (330,410)  THEN 1
            WHEN G.SEMNIFICATIE = 1350 AND Coalesce(C.TIPCOMPENS,0) = 5 AND     OS.SEMNIFICATIE IN (210)      THEN 1
            WHEN G.SEMNIFICATIE = 1350 AND Coalesce(C.TIPCOMPENS,0) = 2                                       THEN 1
            ELSE 0
          END = 1
      AND Coalesce(G.TVA,0) &lt;&gt; 0
      AND P.CODPART &lt;&gt; 0 '||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT('C', NULL, NULL, vSubunit);

 sSelA := '
  ),
  CRS AS (
    SELECT
      CODDOC, CODDOC1, TIPDOC, DATADOC, NRDOC, NRI, PREFIXDOC, CARNETDOC, SERIADOC, PARTENER, OBS, CODCONT, SUBUNITATEA, CODLOCATIE, CODFISCAL, TVAINC, TIPTVA,
      SUM(baza) baza, SUM(CASE WHEN tva = 0 THEN 0 ELSE baza END) bazax, SUM(tva) tva, CASE WHEN TIPDOC = 16 THEN SUM(baza) + SUM(tva) ELSE valdoc END valdoc, -- din cauza ArtIncasUlterior
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN tva = 0 THEN 0                         ELSE baza END) bunuri_cu_ti,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN tva = 0 THEN 0                         ELSE tva  END) tva_bunuri_cu_ti,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN tva = 0 THEN 0 WHEN CAZTVA &lt;&gt; 1 THEN 0 ELSE baza END) BUNURI_CU_TI_BMED,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN tva = 0 THEN 0 WHEN CAZTVA &lt;&gt; 1 THEN 0 ELSE tva  END) BUNURI_CU_TI_TMED,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN tva = 0 THEN 0 WHEN CAZTVA &lt;&gt; 2 THEN 0 ELSE baza END) BUNURI_CU_TI_BMIN,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN tva = 0 THEN 0 WHEN CAZTVA &lt;&gt; 2 THEN 0 ELSE tva  END) BUNURI_CU_TI_TMIN,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN tva = 0 THEN 0 WHEN CAZTVA &lt;&gt; 3 THEN 0 ELSE baza END) BUNURI_CU_TI_BMAX,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN tva = 0 THEN 0 WHEN CAZTVA &lt;&gt; 3 THEN 0 ELSE tva  END) BUNURI_CU_TI_TMAX,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN tva = 0 THEN 0 WHEN CAZTVA &lt;&gt; 4 THEN 0 ELSE baza END) BUNURI_CU_TI_BREG,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN tva = 0 THEN 0 WHEN CAZTVA &lt;&gt; 4 THEN 0 ELSE tva  END) BUNURI_CU_TI_TREG,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN tva = 0 THEN 0 WHEN CAZTVA &lt;&gt; 5 THEN 0 ELSE baza END) BUNURI_CU_TI_BREG2,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN tva = 0 THEN 0 WHEN CAZTVA &lt;&gt; 5 THEN 0 ELSE tva  END) BUNURI_CU_TI_TREG2,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN tva = 0 THEN 0 WHEN CAZTVA &lt;&gt; 6 THEN 0 ELSE baza END) BUNURI_CU_TI_BREG3,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN tva = 0 THEN 0 WHEN CAZTVA &lt;&gt; 6 THEN 0 ELSE tva  END) BUNURI_CU_TI_TREG3,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN tva = 0 THEN 0 WHEN CAZTVA &lt;&gt; 7 THEN 0 ELSE baza END) BUNURI_CU_TI_BREG4,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN tva = 0 THEN 0 WHEN CAZTVA &lt;&gt; 7 THEN 0 ELSE tva  END) BUNURI_CU_TI_TREG4,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN tva = 0 THEN 0 WHEN CAZTVA &lt;&gt; 8 THEN 0 ELSE baza END) BUNURI_CU_TI_BREG5,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN tva = 0 THEN 0 WHEN CAZTVA &lt;&gt; 8 THEN 0 ELSE tva  END) BUNURI_CU_TI_TREG5,
      SUM(CASE WHEN tiptranzactie in (1,2,4) AND tiptva =  5     THEN baza ELSE 0 END) art143ad,
      SUM(CASE WHEN tiptranzactie in (1,2,4) AND tiptva =  6     THEN baza ELSE 0 END) art143bc,
      SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') = ''S'' AND DoServCaStoc = 0
                AND tiptranzactie in (1,2,4) AND tiptva =  6     THEN baza ELSE 0 END) +
      CASE
        WHEN SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') &lt;&gt; ''B''                      AND tiptranzactie in (1,2,4) AND tiptva = 6 THEN baza ELSE 0 END) = 0 THEN 1
        ELSE SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'')  = ''S'' AND DoServCaStoc = 0 AND tiptranzactie in (1,2,4) AND tiptva = 6 THEN baza ELSE 0 END) /
             SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') &lt;&gt; ''B''                      AND tiptranzactie in (1,2,4) AND tiptva = 6 THEN baza ELSE 0 END)
      END *
      SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') = ''B'' AND DoServCaStoc = 0
                AND tiptranzactie in (1,2,4) AND tiptva =  6     THEN baza ELSE 0 END) serv143bc,
      SUM(CASE WHEN tiptranzactie in (1,2)   AND tiptva =  7     AND AN*12+LUNA &lt;2016*12+7 THEN baza
               WHEN tiptranzactie in (1,2)   AND tiptva IN (7,8) AND AN*12+LUNA&gt;=2016*12+7 THEN baza+tva
               ELSE 0
          END )                                                                            rss_311_322,
      SUM(CASE WHEN tiptranzactie in (1,2)   AND tiptva IN (7,8) AND AN*12+LUNA&gt;=2016*12+7 THEN tva
               ELSE 0
          END)                                                                         tva_rss_311_322,
      SUM(CASE WHEN tiptranzactie in (1,2) AND tiptva IN (7,8) AND AN*12+LUNA&gt;=2016*12+7 AND CAZTVA = 1 THEN baza - VA_311_312 ELSE 0 END) A_311_322_BMED,
      SUM(CASE WHEN tiptranzactie in (1,2) AND tiptva IN (7,8) AND AN*12+LUNA&gt;=2016*12+7 AND CAZTVA = 1 THEN tva               ELSE 0 END) A_311_322_TMED,
      SUM(CASE WHEN tiptranzactie in (1,2) AND tiptva IN (7,8) AND AN*12+LUNA&gt;=2016*12+7 AND CAZTVA = 2 THEN baza - VA_311_312 ELSE 0 END) A_311_322_BMIN,
      SUM(CASE WHEN tiptranzactie in (1,2) AND tiptva IN (7,8) AND AN*12+LUNA&gt;=2016*12+7 AND CAZTVA = 2 THEN tva               ELSE 0 END) A_311_322_TMIN,
      SUM(CASE WHEN tiptranzactie in (1,2) AND tiptva IN (7,8) AND AN*12+LUNA&gt;=2016*12+7 AND CAZTVA = 3 THEN baza - VA_311_312 ELSE 0 END) A_311_322_BMAX,
      SUM(CASE WHEN tiptranzactie in (1,2) AND tiptva IN (7,8) AND AN*12+LUNA&gt;=2016*12+7 AND CAZTVA = 3 THEN tva               ELSE 0 END) A_311_322_TMAX,
      SUM(CASE WHEN tiptranzactie = 2        AND tiptva =  9     THEN baza ELSE 0 END) serv278b,
      SUM(CASE WHEN tiptranzactie = 2        AND tiptva =  9     THEN tva  ELSE 0 END) serv278t,
      SUM(CASE WHEN tiptranzactie = 2        AND tiptva = 10     THEN baza ELSE 0 END) baza_oss,
      SUM(CASE WHEN tiptranzactie = 2        AND tiptva = 10     THEN tva  ELSE 0 END) tva_oss,
      SUM(CASE WHEN                              tiptva = 11     THEN baza ELSE 0 END) art294ab,
      SUM(CASE WHEN                              tiptva = 12     THEN baza ELSE 0 END) art294cd,
      SUM(CASE WHEN tiptranzactie = 1        AND tiptva = 13     THEN baza ELSE 0 END) art292,
      SUM(CASE WHEN CAZTVA = 1 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN baza ELSE 0 END) baza_med,
      SUM(CASE WHEN CAZTVA = 1 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN tva  ELSE 0 END) tva_med,
      SUM(CASE WHEN CAZTVA = 2 AND tiptranzactie in (1,2,4) AND tiptva = 1 AND doc_reg = 0 THEN baza ELSE 0 END) baza_min,
      SUM(CASE WHEN CAZTVA = 2 AND tiptranzactie in (1,2,4) AND tiptva = 1 AND doc_reg = 0 THEN tva  ELSE 0 END) tva_min,
      SUM(CASE WHEN CAZTVA = 3 AND tiptranzactie in (1,2,4) AND tiptva = 1 AND doc_reg = 0 THEN baza ELSE 0 END) baza_max,
      SUM(CASE WHEN CAZTVA = 3 AND tiptranzactie in (1,2,4) AND tiptva = 1 AND doc_reg = 0 THEN tva  ELSE 0 END) tva_max,
      SUM(CASE WHEN CAZTVA = 2 AND tiptranzactie in (1,2,4) AND tiptva = 1 AND doc_reg = 1 THEN baza ELSE 0 END) baza_regmin,
      SUM(CASE WHEN CAZTVA = 2 AND tiptranzactie in (1,2,4) AND tiptva = 1 AND doc_reg = 1 THEN tva  ELSE 0 END) tva_regmin,
      SUM(CASE WHEN CAZTVA = 3 AND tiptranzactie in (1,2,4) AND tiptva = 1 AND doc_reg = 1 THEN baza ELSE 0 END) baza_regmax,
      SUM(CASE WHEN CAZTVA = 3 AND tiptranzactie in (1,2,4) AND tiptva = 1 AND doc_reg = 1 THEN tva  ELSE 0 END) tva_regmax,
      SUM(CASE WHEN CAZTVA = 4 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN baza ELSE 0 END) baza_reg,
      SUM(CASE WHEN CAZTVA = 4 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN tva  ELSE 0 END) tva_reg,
      SUM(CASE WHEN CAZTVA = 5 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN baza ELSE 0 END) baza_reg2,
      SUM(CASE WHEN CAZTVA = 5 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN tva  ELSE 0 END) tva_reg2,
      SUM(CASE WHEN CAZTVA = 6 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN baza ELSE 0 END) baza_reg3,
      SUM(CASE WHEN CAZTVA = 6 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN tva  ELSE 0 END) tva_reg3,
      SUM(CASE WHEN CAZTVA = 7 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN baza ELSE 0 END) baza_reg4,
      SUM(CASE WHEN CAZTVA = 7 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN tva  ELSE 0 END) tva_reg4,
      SUM(CASE WHEN CAZTVA = 8 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN baza ELSE 0 END) baza_reg5,
      SUM(CASE WHEN CAZTVA = 8 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN tva  ELSE 0 END) tva_reg5,
      SUM(CASE WHEN CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 0 THEN baza ELSE 0 END) nonro_ded,
      SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') = ''S'' AND DoServCaStoc = 0
                AND CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 0 THEN baza ELSE 0 END) +
      CASE
        WHEN SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') &lt;&gt; ''B''                      AND CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 0 THEN baza ELSE 0 END) = 0 THEN 1
        ELSE SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') =  ''S'' AND DoServCaStoc = 0 AND CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 0 THEN baza ELSE 0 END) /
             SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') &lt;&gt; ''B''                      AND CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 0 THEN baza ELSE 0 END)
      END *
      SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') = ''B'' AND DoServCaStoc = 0
                AND CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 0 THEN baza ELSE 0 END) serv_nonro_ded,
      SUM(CASE WHEN CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 1 THEN baza ELSE 0 END) nonro_nonded,
      SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') = ''S'' AND DoServCaStoc = 0
                AND CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 1 THEN baza ELSE 0 END) +
      CASE
        WHEN SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') &lt;&gt; ''B''                      AND CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 1 THEN baza ELSE 0 END) = 0 THEN 1
        ELSE SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') =  ''S'' AND DoServCaStoc = 0 AND CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 1 THEN baza ELSE 0 END) /
             SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') &lt;&gt; ''B''                      AND CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 1 THEN baza ELSE 0 END)
      END *
      SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') = ''B'' AND DoServCaStoc = 0
                AND CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 1 THEN baza ELSE 0 END) serv_nonro_nonded,
      SUM(
        CASE
          WHEN CAZTVA = 0
           AND NOT tipdoc in (5,14,35)
           AND Coalesce(tiptva0,0) = 0
           AND (
                 (tiptranzactie IN (1,2,3) AND tiptva = 1) OR
                 (tiptranzactie IN (1,2,3) AND tiptva = 2) OR
                 (tiptranzactie IN (1,2)   AND tiptva = 3)
               )
          THEN baza
          ELSE 0
        END
      ) ro_ded,
      SUM(
        CASE
          WHEN CAZTVA = 0 AND tipdoc = 35 THEN baza
          WHEN CAZTVA = 0
           AND tipdoc &lt;&gt; 14
           AND Coalesce(tiptva0,0) = 1
           AND (
                 (tiptranzactie IN (1,2,3) AND tiptva IN (1,2)) OR
                 (tiptranzactie = 2        AND tiptva = 3     )
               )
           AND NOT taxa IN (3,4,5)
          THEN baza
          ELSE 0
        END
      ) ro_nonded,
      SUM(CASE WHEN CAZTVA = 0 AND (tipdoc = 14 OR Coalesce(tiptva0,0) = 2) THEN baza ELSE 0 END) oper_neimp,
      SUM(CASE WHEN CAZTVA = 0 THEN baza ELSE 0 END) baza_0,
      datacreare, userid, an, luna,
      CASE WHEN tipdoc = 28 THEN SUM(baza+tva) ELSE docval END docval, CASE Calc WHEN 1 THEN SUM(baza) ELSE docbaza END docbaza, CASE Calc WHEN 1 THEN SUM(tva) ELSE doctva END doctva,
      DOC_REG
    FROM CRS_JV_TRANZACTII
    GROUP BY
      CODDOC, CODDOC1, TIPDOC, DATADOC, NRDOC, NRI, PREFIXDOC, CARNETDOC, SERIADOC, PARTENER, VALDOC, OBS, CODCONT, SUBUNITATEA, CODLOCATIE, CODFISCAL, TVAINC, TIPTVA,
      DATACREARE, USERID, AN, LUNA, DOCVAL, DOCBAZA, DOCTVA, CALC, DOC_REG
  )
  SELECT
    crs.CODDOC, crs.CODDOC1, crs.TIPDOC, 1 ORDDOC,
    crs.DATADOC, crs.NRDOC, crs.NRI, crs.PREFIXDOC, Coalesce(crs.SERIADOC,dc.SERIE) SERIADOC,
    CASE WHEN CRS.TIPDOC = 16 THEN ''Borderou vanzari zilnice '' WHEN CRS.TIPDOC = 14 THEN ''Diminuare de stoc '' ELSE Coalesce(NP.den_part,N.DEN_CONT) END DEN_PART,
    substr(CASE
      WHEN crs.TIPDOC IN (29,33) AND crs.obs LIKE ''%/%'' AND INSTR(crs.OBS,''/'',1,2) = 0 THEN SUBSTR(crs.OBS,INSTR(crs.OBS,''/'')+1)
      WHEN crs.TIPDOC IN (29,33) AND crs.obs LIKE ''%/%'' THEN SUBSTR(crs.OBS,INSTR(crs.OBS,''/'')+1,INSTR(crs.OBS,''/'',1,2)-INSTR(crs.OBS,''/'')-1)
      WHEN Coalesce(CRS.CODFISCAL,0) = 0 THEN fiscp.codfiscal
      ELSE fiscd.codfiscal
    END, 1, 100) CODFISCAL,
    CASE WHEN CRS.TVAINC = 0 THEN Coalesce(NULLIF(crs.valdoc,0),crs.baza+crs.tva) ELSE crs.ro_ded+crs.ro_nonded END VALDOC,
    CASE WHEN CRS.TVAINC = 0 THEN crs.baza_med END  BAZA_MED,  CASE WHEN CRS.TVAINC = 0 THEN crs.tva_med END  TVA_MED,
    CASE WHEN CRS.TVAINC = 0 THEN crs.baza_min END  BAZA_MIN,  CASE WHEN CRS.TVAINC = 0 THEN crs.tva_min END  TVA_MIN,
    CASE WHEN CRS.TVAINC = 0 THEN crs.baza_max END  BAZA_MAX,  CASE WHEN CRS.TVAINC = 0 THEN crs.tva_max END  TVA_MAX,
    CASE WHEN CRS.TVAINC = 0 THEN crs.baza_regmin END BAZA_REGMIN, CASE WHEN CRS.TVAINC = 0 THEN crs.tva_regmin END TVA_REGMIN,
    CASE WHEN CRS.TVAINC = 0 THEN crs.baza_regmax END BAZA_REGMAX, CASE WHEN CRS.TVAINC = 0 THEN crs.tva_regmax END TVA_REGMAX,
    CASE WHEN CRS.TVAINC = 0 THEN crs.baza_reg END  BAZA_REG,  CASE WHEN CRS.TVAINC = 0 THEN crs.tva_reg END  TVA_REG,
    CASE WHEN CRS.TVAINC = 0 THEN crs.baza_reg2 END BAZA_REG2, CASE WHEN CRS.TVAINC = 0 THEN crs.tva_reg2 END TVA_REG2,
    CASE WHEN CRS.TVAINC = 0 THEN crs.baza_reg3 END BAZA_REG3, CASE WHEN CRS.TVAINC = 0 THEN crs.tva_reg3 END TVA_REG3,
    CASE WHEN CRS.TVAINC = 0 THEN crs.baza_reg4 END BAZA_REG4, CASE WHEN CRS.TVAINC = 0 THEN crs.tva_reg4 END TVA_REG4,
    CASE WHEN CRS.TVAINC = 0 THEN crs.baza_reg5 END BAZA_REG5, CASE WHEN CRS.TVAINC = 0 THEN crs.tva_reg5 END TVA_REG5,
    CASE WHEN CRS.TVAINC = 0 THEN crs.bunuri_cu_ti END BUNURI_CU_TI, CASE WHEN CRS.TVAINC = 0 THEN crs.tva_bunuri_cu_ti END TVA_BUNURI_CU_TI,
    CASE WHEN CRS.TVAINC = 0 THEN crs.BUNURI_CU_TI_BMED END  BUNURI_CU_TI_BMED,  CASE WHEN CRS.TVAINC = 0 THEN crs.BUNURI_CU_TI_TMED END  BUNURI_CU_TI_TMED,
    CASE WHEN CRS.TVAINC = 0 THEN crs.BUNURI_CU_TI_BMIN END  BUNURI_CU_TI_BMIN,  CASE WHEN CRS.TVAINC = 0 THEN crs.BUNURI_CU_TI_TMIN END  BUNURI_CU_TI_TMIN,
    CASE WHEN CRS.TVAINC = 0 THEN crs.BUNURI_CU_TI_BMAX END  BUNURI_CU_TI_BMAX,  CASE WHEN CRS.TVAINC = 0 THEN crs.BUNURI_CU_TI_TMAX END  BUNURI_CU_TI_TMAX,
    CASE WHEN CRS.TVAINC = 0 THEN crs.BUNURI_CU_TI_BREG END  BUNURI_CU_TI_BREG,  CASE WHEN CRS.TVAINC = 0 THEN crs.BUNURI_CU_TI_TREG END  BUNURI_CU_TI_TREG,
    CASE WHEN CRS.TVAINC = 0 THEN crs.BUNURI_CU_TI_BREG2 END BUNURI_CU_TI_BREG2, CASE WHEN CRS.TVAINC = 0 THEN crs.BUNURI_CU_TI_TREG2 END BUNURI_CU_TI_TREG2,
    CASE WHEN CRS.TVAINC = 0 THEN crs.BUNURI_CU_TI_BREG3 END BUNURI_CU_TI_BREG3, CASE WHEN CRS.TVAINC = 0 THEN crs.BUNURI_CU_TI_TREG3 END BUNURI_CU_TI_TREG3,
    CASE WHEN CRS.TVAINC = 0 THEN crs.BUNURI_CU_TI_BREG4 END BUNURI_CU_TI_BREG4, CASE WHEN CRS.TVAINC = 0 THEN crs.BUNURI_CU_TI_TREG4 END BUNURI_CU_TI_TREG4,
    CASE WHEN CRS.TVAINC = 0 THEN crs.BUNURI_CU_TI_BREG5 END BUNURI_CU_TI_BREG5, CASE WHEN CRS.TVAINC = 0 THEN crs.BUNURI_CU_TI_TREG5 END BUNURI_CU_TI_TREG5,
    CASE WHEN CRS.TVAINC = 0 THEN crs.nonro_ded    END NONRO_DED,    CASE WHEN CRS.TVAINC = 0 THEN crs.serv_nonro_ded    END SERV_NONRO_DED,
    CASE WHEN CRS.TVAINC = 0 THEN crs.nonro_nonded END NONRO_NONDED, CASE WHEN CRS.TVAINC = 0 THEN crs.serv_nonro_nonded END SERV_NONRO_NONDED,
    crs.RO_DED, crs.RO_NONDED,
    CASE WHEN CRS.TVAINC = 0 THEN crs.rss_311_322     END a_1521_22,
    CASE WHEN CRS.TVAINC = 0 THEN crs.tva_rss_311_322 END tva_rss_311_322,
    CASE WHEN CRS.TVAINC = 0 THEN crs.A_311_322_BMED  END A_311_322_BMED,
    CASE WHEN CRS.TVAINC = 0 THEN crs.A_311_322_TMED  END A_311_322_TMED,
    CASE WHEN CRS.TVAINC = 0 THEN crs.A_311_322_BMIN  END A_311_322_BMIN,
    CASE WHEN CRS.TVAINC = 0 THEN crs.A_311_322_TMIN  END A_311_322_TMIN,
    CASE WHEN CRS.TVAINC = 0 THEN crs.A_311_322_BMAX  END A_311_322_BMAX,
    CASE WHEN CRS.TVAINC = 0 THEN crs.A_311_322_TMAX  END A_311_322_TMAX,
    CASE WHEN CRS.TVAINC = 0 THEN crs.art143ad END ART143AD, CASE WHEN CRS.TVAINC = 0 THEN crs.art143bc END ART143BC, CASE WHEN CRS.TVAINC = 0 THEN crs.serv143bc END SERV143BC,
    CASE WHEN CRS.TVAINC = 0 THEN crs.art294ab END ART294AB, CASE WHEN CRS.TVAINC = 0 THEN crs.art294cd END ART294CD,
    CASE WHEN CRS.TVAINC = 0 THEN crs.art292   END ART292,
    crs.serv278b, crs.serv278t,
    crs.baza_oss, crs.tva_oss,
    CASE WHEN CRS.TVAINC = 0 THEN crs.oper_neimp END OPER_NEIMP, crs.obs,
    sub.den_subunit SUBUNITATEA, CASE t.statcomunitar WHEN 1 THEN ''DA'' ELSE ''NU'' END UE, CASE crs.tiptva WHEN 2 THEN ''DA'' ELSE ''NU'' END TI, crs.datacreare DATACDOC, ut.username, crs.an ANDOC, crs.luna LUNADOC, CASE CRS.TVAINC WHEN 1 THEN ''DA'' ELSE ''NU'' END TVALAINC,
    CASE CRS.TVAINC WHEN 1 THEN crs.bazax + crs.tva END RESTOL,
    CASE CRS.TVAINC WHEN 1 THEN crs.baza-crs.ro_ded-crs.ro_nonded END BAZAOBLIG,
    CASE CRS.TVAINC WHEN 1 THEN crs.tva END TVANOBLIG,
    NULL INCPREFIX, NULL INCTIP, NULL INCNR, NULL INCDATA,
    NULL INCVAL, NULL INCVFT, NULL INCTVA,
    CASE CRS.TVAINC WHEN 1 THEN crs.bazax + crs.tva END RESTVAL, CASE CRS.TVAINC WHEN 1 THEN crs.tva END RESTTVA,
    CASE CRS.TVAINC WHEN 1 THEN crs.bazax + crs.tva END SOLDVAL,
    CASE CRS.TVAINC WHEN 1 THEN crs.tva END SOLDTVA,
    CRS.DOCVAL, CRS.DOCBAZA, CRS.DOCTVA'||
    sTIPTVADOC||gUserAlias||'
  FROM CRS
    LEFT JOIN NPART          NP    ON NP.CODPART       = CRS.PARTENER
    LEFT JOIN NPARTCODFISC   FISCD ON FISCD.COD_CODFISCAL = CRS.CODFISCAL
    LEFT JOIN NPARTCODFISC   FISCP ON FISCP.CODPART    = CRS.PARTENER AND FISCP.PRINCIPAL = 1
    LEFT JOIN NCONT          N     ON N.CODCONT        = CRS.CODCONT
    LEFT JOIN NSUBUNIT       SUB   ON SUB.CODSUBUNIT   = CRS.SUBUNITATEA
    LEFT JOIN NAGENDA        SDOC  ON SDOC.CODAGENDA   = CRS.CODLOCATIE
    LEFT JOIN NAGENDA        SSOC  ON SSOC.CODPART     = CRS.PARTENER AND Coalesce(SSOC.INACTIV,0) = 0 AND ssoc.SEDIUSOCIAL between 4 and 7 AND SSOC.TIP = 0
    LEFT JOIN NLOCALIT       L     ON L.CODLOCALIT     = Coalesce(SDOC.CODLOCALIT, SSOC.CODLOCALIT)
    LEFT JOIN NTARI          T     ON T.CODTARA        = Coalesce(L.CODTARA, 0)
    LEFT JOIN DOCCARNETE     DC    ON DC.CODCARNET     = CRS.CARNETDOC
    LEFT JOIN TMP_UTILIZATOR UT    ON UT.CODUTILIZATOR = CRS.USERID
    LEFT JOIN INTRARI        INTR  ON INTR.CODINTR     = crs.CODDOC AND INTR.TIPDOC = crs.TIPDOC
    LEFT JOIN IESIRI         IES   ON IES.CODIES       = crs.CODDOC AND IES.TIPDOC = crs.TIPDOC '||
    gSuplJoins;

  vZileTVAInc := Coalesce(NULLIF(fnc_getvalconstanta('ZileTVAIncasare',vAnLista,vLunaLista),''), '0')::INTEGER;
  vZileTVAInc := CASE WHEN vZileTVAInc &lt; 0 THEN 0 WHEN vZileTVAInc &gt; 9999 THEN 9999 ELSE vZileTVAInc END;
  sDRTVAInc := To_Char( Trunc(To_Date(vAnLista::varchar||'.'||vLunaLista::varchar,'yyyy.mm'),'mm') - 1 - vZileTVAInc , 'dd.mm.yyyy');
  perform set_config('PKG_LIST_BASE_JURNVANZ.sDRTVAInc',sDRTVAInc,false);

  sSelTranzX := '
    SELECT
      I1.codies coddoc, NULL::numeric coddoc1, I.tipdoc, I.datadoc, I.nrdoc, I.nri, I.prefixdoc, I.carnetdoc, I.seriadoc, I.partener, I.codlocatie, I.codfiscal, NULL TVAINC,
      CASE
        WHEN I.TIPTVA IN (7,8) AND I.AN*12+I.LUNA&gt;=2016*12+7 AND I.TIPDOC = 19
        THEN (
          SELECT SUM(L1.CANT * Coalesce(LV.PRETACHIZ,NS.PRET - NS.ADAOS,0))
          FROM livr1 l1
            INNER JOIN livr    l  ON l1.codlivr    = l.codlivr
            LEFT  JOIN nirstoc ns ON ns.codnirstoc = l1.codnirstoc
            LEFT  JOIN livrval lv ON lv.codlivr1   = l1.codlivr1
          WHERE L1.CODIES1 = I1.CODIES1 AND L.CODIES = I.CODIES AND L.TIPLIVR = I.TIPDOC
        )
        WHEN I.TIPTVA IN (7,8) AND I.AN*12+I.LUNA&gt;=2016*12+7 AND I.TIPDOC = 26
        THEN (
          SELECT SUM(L1.CANT * Coalesce(LV.PRETACHIZ,NS.PRET - NS.ADAOS,0))
          FROM ieslink ilae
            INNER JOIN iesiri1 ae1  ON ae1.codies1   = ilae.codlinieaviz
            INNER JOIN livr1   l1   ON l1.codies1    = ae1.codies1
            INNER JOIN livr    l    ON l.codlivr     = l1.codlivr AND l.codies = ae1.codies AND l.tiplivr = 20
            LEFT  JOIN nirstoc ns   ON ns.codnirstoc = l1.codnirstoc
            LEFT  JOIN livrval lv   ON lv.codlivr1   = l1.codlivr1
          WHERE ilae.codies1  = i1.codies1
        )
        ELSE 0
      END VA_311_312,
      CASE
        WHEN I.TIPDOC IN (14)    THEN L1.BAZA
        WHEN I.TIPDOC IN (16,21) THEN Coalesce(I1.VALFIN,I1.CANT*I1.PU,0) - Coalesce(I1.TVAFIN,I1.TVA,0)
        ELSE                          Coalesce(I1.VALFIN,I1.CANT*I1.PU,0)
      END *
      CASE WHEN I1.VALFIN IS NULL THEN 1+Coalesce(i1.procdisc/100,0) ELSE 1 END *
      Coalesce(NULLIF(CASE WHEN CL.VAL = 1 THEN I1.CursFacturaAvans END,0), NULLIF(I.Curs,0),1) baza,
      CASE
        WHEN I.TipDoc = 14 AND L1.NR_L1 = 1 THEN Coalesce(I1.TVA,0)
        WHEN I.TipDoc = 14 AND L1.NR_LX = 0 THEN Coalesce(I1.TVA,0)
        WHEN I.TipDoc = 14 AND L1.BAZATOT &lt;&gt; 0 THEN Coalesce(I1.TVA,0) * L1.Baza/L1.BAZATOT
        WHEN I.TipDoc = 14 THEN Coalesce(I1.TVA,0)/L1.NR_L1
        ELSE Coalesce(I1.TVAFIN, I1.TVA,0)
      END *
      CASE WHEN I1.VALFIN IS NULL THEN 1+Coalesce(i1.procdisc/100,0) ELSE 1 END *
      Coalesce(NULLIF(CASE WHEN CL.VAL = 1 THEN I1.CursFacturaAvans END,0), NULLIF(I.Curs,0),1) tva,
      PKG_LIST_BASE_UTILS_MATCH_TVA(
        CASE
          WHEN I.TIPDOC = 14 AND L1.Baza = 0                              THEN '||sPjTva||'
          WHEN I.TipDoc = 14 AND L1.NR_L1 = 1                             THEN Coalesce(I1.TVA,0) * 100 /L1.BAZA
          WHEN I.TipDoc = 14 AND L1.BAZATOT &lt;&gt; 0                          THEN Coalesce(I1.TVA,0) * 100 /L1.BAZATOT
          WHEN I.TIPDOC = 14                                              THEN Coalesce(I1.TVA,0)/L1.NR_LX * 100 / L1.BAZA
          WHEN I1.TIPLINIE IN (''G'',''T'') AND Coalesce(I1.RESTFACT,0)=0 THEN '||sPjTva||'
          WHEN I1.TIPLINIE IN (''G'',''T'')                               THEN Coalesce(I1.TVA,0)/I1.RESTFACT*100
          WHEN I.TIPTVA IN (7,8)            AND I.AN*12+I.LUNA&gt;=2016*12+7 THEN T1.PROCENT
          ELSE PKG_LIST_BASE_UTILS_CALC_PROC_TVA(I.TIPDOC, I.AN, I.LUNA, I1.CANT, I1.PU, I1.TVA, I1.CODOBIECT, T1.PROCENT, I.ROTEFACT)
        END,
        '||sAnLunaFin||'
      ) CAZTVA,
      I1.tiplinie,
      CASE WHEN I.tipdoc = 14 AND Coalesce(I1.TVA,0)&lt;&gt;0 THEN 1 ELSE Coalesce(I.tiptva,1) END tiptva,
      CASE WHEN I.tipdoc = 14 AND Coalesce(I1.TVA,0)&lt;&gt;0 THEN 1 ELSE Coalesce(I.tiptranzactie,1) END tiptranzactie,
      CASE
        WHEN (Coalesce(I1.TVA,0) = 0) AND (I1.tiplinie IN (''='',''S'',''V'',''R'')) THEN PKG_LIST_BASE_UTILS_getTipTVA0(I1.codobiect,I.an,I.luna)
        ELSE 0
      END TIPTVA0,
      CASE
        WHEN I.TIPDOC = 14 THEN SUM( (L1.BAZATOT + Coalesce(I1.TVA,0)) / l1.nr_l1) OVER (PARTITION BY I.CODIES)
        ELSE I.VALDOC
      END * Coalesce(NULLIF(CASE WHEN CL.VAL = 1 THEN I1.CursFacturaAvans END,0), NULLIF(I.Curs,0),1) valdoc,
      i.obs, 0 codcont, i.subunitatea, i.datacreare, i.userid, i.an, i.luna,
      i.valdoc            * Coalesce(NULLIF(I.Curs,0),1) docval,
      (i.valdoc-i.tvadoc) * Coalesce(NULLIF(I.Curs,0),1) docbaza,
      i.tvadoc            * Coalesce(NULLIF(I.Curs,0),1) doctva,
      CASE WHEN CL.VAL = 1 THEN 1 ELSE 0 END CALC,
      0 CAZ_B_CU_TI,
      '||CASE WHEN vISIVB THEN 'Max(CASE WHEN I1.tiplinie = ''='' THEN 1 ELSE 0 END) OVER (PARTITION BY i.codies)' ELSE '0' END||' DoServCaStoc,
      CASE
        WHEN I1.tiplinie &lt;&gt; ''V''
        THEN I1.tiplinie
        ELSE
          CASE Max(CASE WHEN I1.tiplinie = ''S'' THEN 1 ELSE 0 END) OVER (PARTITION BY i.codies) +
               Max(CASE WHEN I1.tiplinie = ''='' THEN 2 ELSE 0 END) OVER (PARTITION BY i.codies)
            WHEN 1 THEN ''S''
            WHEN 2 THEN I1.tiplinie
            WHEN 3 THEN '||CASE WHEN vISIVB THEN 'I1.tiplinie' ELSE '''B''' END ||'
            ELSE I1.tiplinie
          END
      END TipLinieEXTRA,
      CASE WHEN Coalesce(i.an*100+i.luna, 0) = To_Number(Coalesce(To_Char(Coalesce(i.datatva, i.datadoc), ''yyyymm''),''0'')) THEN 0 ELSE 1 END DOC_REG
    FROM iesiri i
      INNER JOIN iesiri1 i1   ON i1.codies     = i.codies
      LEFT  JOIN iesiri1 i1st ON i1st.codies1  = i1.codies1storno
      LEFT  JOIN iesiri  ist  ON ist.codies    = i1st.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
      LEFT  JOIN (
        SELECT
          I.nrdoc, I.CodIes, L1.Codies1, L1.CANT * Coalesce(LV.PRETACHIZ,NS.PRET - NS.ADAOS,0) BAZA,
          SUM(L1.CANT * Coalesce(LV.PRETACHIZ,NS.PRET - NS.ADAOS,0)) OVER (PARTITION BY I.CodIes, L1.Codies1) BAZATOT,
          SUM(CASE WHEN Coalesce(LV.PRETACHIZ,NS.PRET - NS.ADAOS,0) = 0 THEN 0 ELSE 1 END) OVER (PARTITION BY I.CodIes, L1.Codies1) NR_LX,
          COUNT(1) OVER (PARTITION BY I.CodIes, L1.Codies1) NR_L1
        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 NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
          LEFT  JOIN LIVRVAL LV ON LV.CODLIVR1   = L1.CODLIVR1
        WHERE I.TIPDOC = 14
          AND I.AN*12+I.LUNA '||sCondLuna||' '|| PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', NULL, NULL, vSubunit) || '
      ) L1 ON L1.CODIES1 = I1.CODIES1 AND L1.Codies = I1.CODIES
      LEFT  JOIN tmp_al_curslinie cl ON cl.AL = i.an*12+i.luna
    WHERE I.TIPDOC IN (14,16,19,21,22,26)
      AND Coalesce(I.INFOCM,0) = 0 AND I.ANULAT = 0 AND I.OPERAT = 1 AND Coalesce(I.TIPFACTURA,0) &lt;&gt; 7
      AND I.CODIES IN (SELECT DISTINCT CODDOC FROM TMP_LST_TVAINCAS WHERE TIPDOC IN (14,16,19,21,22,26))
      AND I1.TIPLINIE IN (''='',''S'',''V'',''R'')
      AND CASE I.TIPDOC WHEN 14 THEN Coalesce(I1.TVA,0) ELSE 1 END &lt;&gt; 0
      AND CASE I.TIPDOC WHEN 14 THEN L1.NR_L1           ELSE 1 END &lt;&gt; 0
      AND Coalesce(I1.CODOBIECT,-100)::VARCHAR &lt;&gt; CASE WHEN I.TIPDOC = 16 THEN Coalesce(fnc_getvalconstanta(''ArtIncasUlterior'',I.AN,I.LUNA),''0'') ELSE ''0'' END ' ||
      PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', NULL, NULL, vSubunit)||
      sFiltruCodArt;

  sSelX := '
  ),
  CRS AS (
    SELECT
      CODDOC, CODDOC1, TIPDOC, DATADOC, NRDOC, NRI, PREFIXDOC, CARNETDOC, SERIADOC, PARTENER, OBS, CODCONT, SUBUNITATEA, CODLOCATIE, CODFISCAL, TIPTVA,
      SUM(baza) baza, SUM(CASE WHEN tva = 0 THEN 0 ELSE baza END) bazax, SUM(tva) tva, CASE WHEN TIPDOC = 16 THEN SUM(baza) + SUM(tva) ELSE valdoc END valdoc, -- din cauza ArtIncasUlterior
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0                         ELSE baza END) bunuri_cu_ti,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0                         ELSE tva  END) tva_bunuri_cu_ti,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN CAZTVA &lt;&gt; 1 THEN 0 ELSE baza END) BUNURI_CU_TI_BMED,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN CAZTVA &lt;&gt; 1 THEN 0 ELSE tva  END) BUNURI_CU_TI_TMED,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN CAZTVA &lt;&gt; 2 THEN 0 ELSE baza END) BUNURI_CU_TI_BMIN,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN CAZTVA &lt;&gt; 2 THEN 0 ELSE tva  END) BUNURI_CU_TI_TMIN,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN CAZTVA &lt;&gt; 3 THEN 0 ELSE baza END) BUNURI_CU_TI_BMAX,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN CAZTVA &lt;&gt; 3 THEN 0 ELSE tva  END) BUNURI_CU_TI_TMAX,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN CAZTVA &lt;&gt; 4 THEN 0 ELSE baza END) BUNURI_CU_TI_BREG,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN CAZTVA &lt;&gt; 4 THEN 0 ELSE tva  END) BUNURI_CU_TI_TREG,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN CAZTVA &lt;&gt; 5 THEN 0 ELSE baza END) BUNURI_CU_TI_BREG2,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN CAZTVA &lt;&gt; 5 THEN 0 ELSE tva  END) BUNURI_CU_TI_TREG2,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN CAZTVA &lt;&gt; 6 THEN 0 ELSE baza END) BUNURI_CU_TI_BREG3,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN CAZTVA &lt;&gt; 6 THEN 0 ELSE tva  END) BUNURI_CU_TI_TREG3,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN CAZTVA &lt;&gt; 7 THEN 0 ELSE baza END) BUNURI_CU_TI_BREG4,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN CAZTVA &lt;&gt; 7 THEN 0 ELSE tva  END) BUNURI_CU_TI_TREG4,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN CAZTVA &lt;&gt; 8 THEN 0 ELSE baza END) BUNURI_CU_TI_BREG5,
      SUM(CASE WHEN caz_b_cu_ti = 0 THEN 0 WHEN CAZTVA &lt;&gt; 8 THEN 0 ELSE tva  END) BUNURI_CU_TI_TREG5,
      SUM(CASE WHEN tiptranzactie in (1,2,4) AND tiptva =  5     THEN baza ELSE 0 END) art143ad,
      SUM(CASE WHEN tiptranzactie in (1,2,4) AND tiptva =  6     THEN baza ELSE 0 END) art143bc,
      SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') = ''S'' AND DoServCaStoc = 0
                AND tiptranzactie in (1,2,4) AND tiptva =  6     THEN baza ELSE 0 END) +
      CASE
        WHEN SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') &lt;&gt; ''B''                      AND tiptranzactie in (1,2,4) AND tiptva = 6 THEN baza ELSE 0 END) = 0 THEN 1
        ELSE SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'')  = ''S'' AND DoServCaStoc = 0 AND tiptranzactie in (1,2,4) AND tiptva = 6 THEN baza ELSE 0 END) /
             SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') &lt;&gt; ''B''                      AND tiptranzactie in (1,2,4) AND tiptva = 6 THEN baza ELSE 0 END)
      END *
      SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') = ''B'' AND DoServCaStoc = 0
                AND tiptranzactie in (1,2,4) AND tiptva =  6     THEN baza ELSE 0 END) serv143bc,
      SUM(CASE WHEN tiptranzactie in (1,2)   AND tiptva =  7     AND AN*12+LUNA &lt;2016*12+7 THEN baza
               WHEN tiptranzactie in (1,2)   AND tiptva IN (7,8) AND AN*12+LUNA&gt;=2016*12+7 THEN baza+tva
               ELSE 0
          END )                                                                        rss_311_322,
      SUM(CASE WHEN tiptranzactie in (1,2)   AND tiptva IN (7,8) AND AN*12+LUNA&gt;=2016*12+7 THEN tva
               ELSE 0
          END)                                                                         tva_rss_311_322,
      SUM(CASE WHEN tiptranzactie in (1,2) AND tiptva IN (7,8) AND AN*12+LUNA&gt;=2016*12+7 AND CAZTVA = 1 THEN baza - VA_311_312 ELSE 0 END) A_311_322_BMED,
      SUM(CASE WHEN tiptranzactie in (1,2) AND tiptva IN (7,8) AND AN*12+LUNA&gt;=2016*12+7 AND CAZTVA = 1 THEN tva               ELSE 0 END) A_311_322_TMED,
      SUM(CASE WHEN tiptranzactie in (1,2) AND tiptva IN (7,8) AND AN*12+LUNA&gt;=2016*12+7 AND CAZTVA = 2 THEN baza - VA_311_312 ELSE 0 END) A_311_322_BMIN,
      SUM(CASE WHEN tiptranzactie in (1,2) AND tiptva IN (7,8) AND AN*12+LUNA&gt;=2016*12+7 AND CAZTVA = 2 THEN tva               ELSE 0 END) A_311_322_TMIN,
      SUM(CASE WHEN tiptranzactie in (1,2) AND tiptva IN (7,8) AND AN*12+LUNA&gt;=2016*12+7 AND CAZTVA = 3 THEN baza - VA_311_312 ELSE 0 END) A_311_322_BMAX,
      SUM(CASE WHEN tiptranzactie in (1,2) AND tiptva IN (7,8) AND AN*12+LUNA&gt;=2016*12+7 AND CAZTVA = 3 THEN tva               ELSE 0 END) A_311_322_TMAX,
      SUM(CASE WHEN tiptranzactie = 2        AND tiptva =  9     THEN baza ELSE 0 END) serv278b,
      SUM(CASE WHEN tiptranzactie = 2        AND tiptva =  9     THEN tva  ELSE 0 END) serv278t,
      SUM(CASE WHEN tiptranzactie = 2        AND tiptva = 10     THEN baza ELSE 0 END) baza_oss,
      SUM(CASE WHEN tiptranzactie = 2        AND tiptva = 10     THEN tva  ELSE 0 END) tva_oss,
      SUM(CASE WHEN                              tiptva = 11     THEN baza ELSE 0 END) art294ab,
      SUM(CASE WHEN                              tiptva = 12     THEN baza ELSE 0 END) art294cd,
      SUM(CASE WHEN tiptranzactie = 1        AND tiptva = 13     THEN baza ELSE 0 END) art292,
      SUM(CASE WHEN CAZTVA = 1 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN baza ELSE 0 END) baza_med,
      SUM(CASE WHEN CAZTVA = 1 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN tva  ELSE 0 END) tva_med,
      SUM(CASE WHEN CAZTVA = 2 AND tiptranzactie in (1,2,4) AND tiptva = 1 AND doc_reg = 0 THEN baza ELSE 0 END) baza_min,
      SUM(CASE WHEN CAZTVA = 2 AND tiptranzactie in (1,2,4) AND tiptva = 1 AND doc_reg = 0 THEN tva  ELSE 0 END) tva_min,
      SUM(CASE WHEN CAZTVA = 3 AND tiptranzactie in (1,2,4) AND tiptva = 1 AND doc_reg = 0 THEN baza ELSE 0 END) baza_max,
      SUM(CASE WHEN CAZTVA = 3 AND tiptranzactie in (1,2,4) AND tiptva = 1 AND doc_reg = 0 THEN tva  ELSE 0 END) tva_max,
      SUM(CASE WHEN CAZTVA = 2 AND tiptranzactie in (1,2,4) AND tiptva = 1 AND doc_reg = 1 THEN baza ELSE 0 END) baza_regmin,
      SUM(CASE WHEN CAZTVA = 2 AND tiptranzactie in (1,2,4) AND tiptva = 1 AND doc_reg = 1 THEN tva  ELSE 0 END) tva_regmin,
      SUM(CASE WHEN CAZTVA = 3 AND tiptranzactie in (1,2,4) AND tiptva = 1 AND doc_reg = 1 THEN baza ELSE 0 END) baza_regmax,
      SUM(CASE WHEN CAZTVA = 3 AND tiptranzactie in (1,2,4) AND tiptva = 1 AND doc_reg = 1 THEN tva  ELSE 0 END) tva_regmax,
      SUM(CASE WHEN CAZTVA = 4 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN baza ELSE 0 END) baza_reg,
      SUM(CASE WHEN CAZTVA = 4 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN tva  ELSE 0 END) tva_reg,
      SUM(CASE WHEN CAZTVA = 5 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN baza ELSE 0 END) baza_reg2,
      SUM(CASE WHEN CAZTVA = 5 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN tva  ELSE 0 END) tva_reg2,
      SUM(CASE WHEN CAZTVA = 6 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN baza ELSE 0 END) baza_reg3,
      SUM(CASE WHEN CAZTVA = 6 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN tva  ELSE 0 END) tva_reg3,
      SUM(CASE WHEN CAZTVA = 7 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN baza ELSE 0 END) baza_reg4,
      SUM(CASE WHEN CAZTVA = 7 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN tva  ELSE 0 END) tva_reg4,
      SUM(CASE WHEN CAZTVA = 8 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN baza ELSE 0 END) baza_reg5,
      SUM(CASE WHEN CAZTVA = 8 AND tiptranzactie in (1,2,4) AND tiptva = 1 THEN tva  ELSE 0 END) tva_reg5,
      SUM(CASE WHEN CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 0 THEN baza ELSE 0 END) nonro_ded,
      SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') = ''S'' AND DoServCaStoc = 0
                AND CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 0 THEN baza ELSE 0 END) +
      CASE
        WHEN SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') &lt;&gt; ''B''                      AND CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 0 THEN baza ELSE 0 END) = 0 THEN 1
        ELSE SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') =  ''S'' AND DoServCaStoc = 0 AND CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 0 THEN baza ELSE 0 END) /
             SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') &lt;&gt; ''B''                      AND CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 0 THEN baza ELSE 0 END)
      END *
      SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') = ''B'' AND DoServCaStoc = 0
                AND CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 0 THEN baza ELSE 0 END) serv_nonro_ded,
      SUM(CASE WHEN CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 1 THEN baza ELSE 0 END) nonro_nonded,
      SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') = ''S'' AND DoServCaStoc = 0
                AND CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 1 THEN baza ELSE 0 END) +
      CASE
        WHEN SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') &lt;&gt; ''B''                      AND CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 1 THEN baza ELSE 0 END) = 0 THEN 1
        ELSE SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') =  ''S'' AND DoServCaStoc = 0 AND CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 1 THEN baza ELSE 0 END) /
             SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') &lt;&gt; ''B''                      AND CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 1 THEN baza ELSE 0 END)
      END *
      SUM(CASE WHEN Coalesce(TipLinieExtra, ''~'') = ''B'' AND DoServCaStoc = 0
                AND CAZTVA = 0 AND tiptva = 4 AND Coalesce(tiptva0,0) = 1 THEN baza ELSE 0 END) serv_nonro_nonded,
      SUM(CASE WHEN CAZTVA = 0 AND tipdoc not in (5,14) AND Coalesce(tiptva0,0) = 0 AND ((tiptranzactie IN (1,2,3) AND tiptva IN (1,2)) OR (tiptranzactie IN (1,2) AND tiptva = 3)) THEN baza ELSE 0 END) ro_ded,
      SUM(CASE WHEN CAZTVA = 0 AND tipdoc &lt;&gt; 14 AND Coalesce(tiptva0,0) = 1 AND ((tiptranzactie IN (1,2,3) AND tiptva IN (1,2)) OR (tiptranzactie = 2 AND tiptva = 3)) THEN baza ELSE 0 END) ro_nonded,
      SUM(CASE WHEN CAZTVA = 0 AND (tipdoc = 14 OR Coalesce(tiptva0,0) = 2) THEN baza ELSE 0 END) oper_neimp,
      SUM(CASE WHEN CAZTVA = 0 THEN baza ELSE 0 END) baza_0,
      datacreare, userid, an, luna,
      docval, docbaza, doctva
    FROM CRS_JV_TRANZACTII
    GROUP BY CODDOC, CODDOC1, TIPDOC, DATADOC, NRDOC, NRI, PREFIXDOC, CARNETDOC, SERIADOC, PARTENER, VALDOC, OBS, CODCONT, SUBUNITATEA, CODLOCATIE, CODFISCAL,  TIPTVA, DATACREARE, USERID, AN, LUNA, DOCVAL, DOCBAZA, DOCTVA, DOC_REG)
  SELECT
    crs.CODDOC, crs.CODDOC1, crs.TIPDOC, TVAI.ORDDOC,
    crs.DATADOC, crs.NRDOC, crs.NRI, crs.PREFIXDOC, Coalesce(crs.SERIADOC,dc.SERIE) SERIADOC,
    CASE WHEN CRS.TIPDOC = 16 THEN ''Borderou vanzari zilnice '' WHEN CRS.TIPDOC = 14 THEN ''Diminuare de stoc '' ELSE Coalesce(NP.den_part,N.DEN_CONT) END DEN_PART,
    CASE
      WHEN crs.TIPDOC IN (29,33) AND crs.obs LIKE ''%/%'' AND INSTR(crs.OBS,''/'',1,2) = 0 THEN SUBSTR(crs.OBS,INSTR(crs.OBS,''/'')+1)
      WHEN crs.TIPDOC IN (29,33) AND crs.obs LIKE ''%/%'' THEN SUBSTR(crs.OBS,INSTR(crs.OBS,''/'')+1,INSTR(crs.OBS,''/'',1,2)-INSTR(crs.OBS,''/'')-1)
      WHEN Coalesce(CRS.CODFISCAL,0) = 0 THEN fiscp.codfiscal
      ELSE fiscd.codfiscal
    END CODFISCAL,
    NULL valdoc,
    crs.baza_med *TVAI.COEFTVA BAZA_MED,  crs.tva_med *TVAI.COEFTVA TVA_MED,
    crs.baza_min *TVAI.COEFTVA BAZA_MIN,  crs.tva_min *TVAI.COEFTVA TVA_MIN,
    crs.baza_max *TVAI.COEFTVA BAZA_MAX,  crs.tva_max *TVAI.COEFTVA TVA_MAX,
    crs.baza_regmin*TVAI.COEFTVA BAZA_REGMIN, crs.tva_regmin*TVAI.COEFTVA TVA_REGMIN,
    crs.baza_regmax*TVAI.COEFTVA BAZA_REGMAX, crs.tva_regmax*TVAI.COEFTVA TVA_REGMAX,
    crs.baza_reg *TVAI.COEFTVA BAZA_REG,  crs.tva_reg *TVAI.COEFTVA TVA_REG,
    crs.baza_reg2*TVAI.COEFTVA BAZA_REG2, crs.tva_reg2*TVAI.COEFTVA TVA_REG2,
    crs.baza_reg3*TVAI.COEFTVA BAZA_REG3, crs.tva_reg3*TVAI.COEFTVA TVA_REG3,
    crs.baza_reg4*TVAI.COEFTVA BAZA_REG4, crs.tva_reg4*TVAI.COEFTVA TVA_REG4,
    crs.baza_reg5*TVAI.COEFTVA BAZA_REG5, crs.tva_reg5*TVAI.COEFTVA TVA_REG5,
    crs.bunuri_cu_ti, crs.tva_bunuri_cu_ti,
    crs.BUNURI_CU_TI_BMED,  crs.BUNURI_CU_TI_TMED,
    crs.BUNURI_CU_TI_BMIN,  crs.BUNURI_CU_TI_TMIN,
    crs.BUNURI_CU_TI_BMAX,  crs.BUNURI_CU_TI_TMAX,
    crs.BUNURI_CU_TI_BREG,  crs.BUNURI_CU_TI_TREG,
    crs.BUNURI_CU_TI_BREG2, crs.BUNURI_CU_TI_TREG2,
    crs.BUNURI_CU_TI_BREG3, crs.BUNURI_CU_TI_TREG3,
    crs.BUNURI_CU_TI_BREG4, crs.BUNURI_CU_TI_TREG4,
    crs.BUNURI_CU_TI_BREG5, crs.BUNURI_CU_TI_TREG5,
    crs.nonro_ded,    crs.serv_nonro_ded,
    crs.nonro_nonded, crs.serv_nonro_nonded,
    crs.ro_ded, crs.ro_nonded,
    crs.rss_311_322, crs.tva_rss_311_322, crs.A_311_322_BMED, crs.A_311_322_TMED, crs.A_311_322_BMIN, crs.A_311_322_TMIN, crs.A_311_322_BMAX, crs.A_311_322_TMAX,
    crs.art143ad, crs.art143bc, crs.serv143bc,
    crs.art294ab, crs.art294cd,
    crs.art292,
    crs.serv278b, crs.serv278t,
    crs.baza_oss, crs.tva_oss,
    crs.oper_neimp, crs.obs,
    sub.den_subunit SUBUNITATEA, CASE t.statcomunitar WHEN 1 THEN ''DA'' ELSE ''NU'' END UE, CASE crs.tiptva WHEN 2 THEN ''DA'' ELSE ''NU'' END TI, crs.datacreare DATACDOC, ut.username, crs.an ANDOC, crs.luna LUNADOC, ''DA'' TVALAINC,
    CASE WHEN TVAI.ORDDOC = 1 OR TVAI.ORDDOC IS NULL THEN (crs.bazax + crs.tva) * Coalesce(TVAI.CoefDoc,1) ELSE NULL END RESTOL,
    CASE WHEN TVAI.ORDDOC = 1 OR TVAI.ORDDOC IS NULL THEN crs.bazax * Coalesce(TVAI.CoefDoc,1) ELSE NULL END BAZAOBLIG,
    CASE WHEN TVAI.ORDDOC = 1 OR TVAI.ORDDOC IS NULL THEN crs.tva * Coalesce(TVAI.CoefDoc,1) ELSE NULL END TVANOBLIG,
    TVAI.PREFIXSTINGERE INCPREFIX, PKG_LIST_BASE_UTILS_DECODE_TIPDOC_SCURT(TVAI.TIPSTINGERE) INCTIP, CASE WHEN TVAI.TIPSTINGERE &lt;&gt; 81 THEN TVAI.NRSTINGERE END INCNR, TVAI.DATASTINGERE INCDATA,
    CASE WHEN TVAI.TIPSTINGERE = 81 THEN (crs.bazax + crs.tva) * TVAI.COEFTVA ELSE TVAI.VALSTINSA END INCVAL, crs.bazax * TVAI.COEFTVA INCVFT, crs.Tva * TVAI.COEFTVA INCTVA,
    (crs.bazax + crs.tva) * (Coalesce(TVAI.CoefDoc,1) - Coalesce(TVAI.CoefPlata,0)) RESTVAL, crs.tva * (Coalesce(TVAI.CoefDoc,1) - Coalesce(TVAI.CoefPlata,0)) RESTTVA,
    CASE WHEN TVAI.ORDDOC IS NULL OR TVAI.ORDDOC = TVAI.CountDoc THEN (crs.bazax + crs.tva) * (Coalesce(TVAI.CoefDoc,1) - Coalesce(TVAI.CoefPlata,0)) ELSE NULL END SOLDVAL,
    CASE WHEN TVAI.ORDDOC IS NULL OR TVAI.ORDDOC = TVAI.CountDoc THEN crs.tva * (Coalesce(TVAI.CoefDoc,1) - Coalesce(TVAI.CoefPlata,0)) ELSE NULL END SOLDTVA,
    CRS.DOCVAL, CRS.DOCBAZA, CRS.DOCTVA'||
    sTIPTVADOC||gUserAlias||'
  FROM CRS
    INNER JOIN TMP_LST_TVAINCAS TVAI  ON TVAI.CodDoc      = crs.CODDOC AND TVAI.TIPDOC = crs.TIPDOC
    LEFT  JOIN NPART            NP    ON NP.CODPART       = CRS.PARTENER
    LEFT  JOIN NPARTCODFISC     FISCD ON FISCD.COD_CODFISCAL = CRS.CODFISCAL
    LEFT  JOIN NPARTCODFISC     FISCP ON FISCP.CODPART    = CRS.PARTENER AND FISCP.PRINCIPAL = 1
    LEFT  JOIN NCONT            N     ON N.CODCONT        = CRS.CODCONT
    LEFT  JOIN NSUBUNIT         SUB   ON SUB.CODSUBUNIT   = CRS.SUBUNITATEA
    LEFT  JOIN NAGENDA          SDOC  ON SDOC.CODAGENDA   = CRS.CODLOCATIE
    LEFT  JOIN NAGENDA          SSOC  ON SSOC.CODPART     = CRS.PARTENER AND Coalesce(SSOC.INACTIV,0) = 0 AND ssoc.SEDIUSOCIAL between 4 and 7 AND SSOC.TIP = 0
    LEFT  JOIN NLOCALIT         L     ON L.CODLOCALIT     = Coalesce(SDOC.CODLOCALIT, SSOC.CODLOCALIT)
    LEFT  JOIN NTARI            T     ON T.CODTARA        = Coalesce(L.CODTARA, 0)
    LEFT  JOIN DOCCARNETE       DC    ON DC.CODCARNET     = CRS.CARNETDOC
    LEFT  JOIN TMP_UTILIZATOR   UT    ON UT.CODUTILIZATOR = CRS.USERID
    LEFT  JOIN INTRARI          INTR  ON INTR.CODINTR     = crs.CODDOC AND INTR.TIPDOC = crs.TIPDOC
    LEFT  JOIN IESIRI           IES   ON IES.CODIES       = crs.CODDOC AND IES.TIPDOC = crs.TIPDOC '||
    gSuplJoins;

  PERFORM pkg_list_base_jurnvanz_pregateste_tmp_lst_tvaincas(aListID, aListVer);

  EXECUTE 'TRUNCATE TABLE bulk_codies';
  PERFORM LIST_EXECUTE_IMMEDIATE('INSERT INTO bulk_codies '||sIDisc, aListID, aListVer);
  FOR vrec IN (SELECT codies FROM bulk_codies) LOOP
    PERFORM PKG_IESIRI_SetValFin(vrec.CodIes, 0);
  END LOOP;
  PERFORM LIST_EXECUTE_IMMEDIATE( sInsert|| sSelWith|| sSelTranz1||sSelA, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE( sInsert|| sSelWith|| sSelTranz2||sSelA, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE( sInsert|| sSelWith|| sSelTranz3||sSelA, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE( sInsert|| sSelWith|| sSelTranz4||sSelA, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE( sInsert|| sSelWith|| sSelTranz5||sSelA, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE( sInsert|| sSelWith|| sSelTranz6||sSelA, aListID, aListVer);
  EXECUTE 'TRUNCATE TABLE bulk_codies';
  PERFORM LIST_EXECUTE_IMMEDIATE('INSERT INTO bulk_codies '||sXDisc, aListID, aListVer);
  FOR vrec IN (SELECT codies FROM bulk_codies) LOOP
    PERFORM PKG_IESIRI_SetValFin(vrec.CodIes, 0);
  END LOOP;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert||sSelWith||sSelTranzX||sSelX, aListID, aListVer);

  EXECUTE 'SELECT count(1) FROM  '||tmpname INTO vCountDebug;
  PERFORM PKG_GLOBALS_CheckDebugMode('Numar linii '||To_Char(vCountDebug), aLISTID, aLISTVER);
  EXECUTE 'TRUNCATE TABLE bulk_codies';
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_prodetichete_processlist</obj_name>
  <obj_hashval>21f5fde04b9dd5070351e9520b78e3a6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_prodetichete_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSelect         varchar := '';
  sCantField       varchar := '';
  sCompare         varchar := '';
  gSuplCols       varchar := 'nart art,nartobj obj,npart p,npers ag,nartcli acli,comanda ccli, intrari1 i1';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Florin 11.04.2023 - sinc. Oracle
  --Adina 14.10.2020
  IF  COALESCE(fnc_GetValConstanta('LiniiEticheteProd', getANLUCRU(), getlunalucru()), '1') = '1' THEN
    sCantField := ' 1, ';
    sCompare := ' x.cant ';
  ELSE
    IF  COALESCE(fnc_GetValConstanta('LiniiEticheteProd', getANLUCRU(), getlunalucru()), '1') = '2' THEN
      sCantField :=
      ' case
          when y.nrcolet = trunc(x.cant/(case when coalesce(x.d1,0)=0 then 1 else coalesce(x.d1,0) end)) + 1 then x.cant - trunc(x.cant/(case when coalesce(x.d1,0)=0 then 1 else coalesce(x.d1,0) end))*(case when coalesce(x.d1,0)=0 then 1 else coalesce(x.d1,0) end)
          else (case when coalesce(x.d1,0)=0 then 1 else coalesce(x.d1,0) end)
        end, ';

      sCompare :=
      ' CASE
          WHEN TRUNC(x.cant/(case when coalesce(x.d1,0)=0 then 1 else coalesce(x.d1,0) end))*(case when coalesce(x.d1,0)=0 then 1 else coalesce(x.d1,0) end) = x.cant then trunc(x.cant/(case when coalesce(x.d1,0)=0 then 1 else coalesce(x.d1,0) end))
          else trunc(x.cant/(case when coalesce(x.d1,0)=0 then 1 else coalesce(x.d1,0) end)) + 1
        END ';
    ELSE
      sCantField := ' x.cant, ';
      sCompare   := ' 1 ';
    END IF;
  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_PRODETICHETE.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
     Art,
     CodExtern,
     Responsabil,
     NrCmdInt,
     NrCmdCli,
     Client,
     Cant,
     CodExternCli,
     DenCli,
     D1,
     D2,
     D3,
     D1S,
     D2S,
     D3S' || gUserFields || ')';

  sSelect := '
  SELECT
    x.denumire,
    x.codextern,
    x.agent,
    x.nrcmdi,
    x.nrcmdcli,
    x.den_part,' || coalesce(chr(13),'') || sCantField || coalesce(chr(13),'') || 'x.codlaclient,
    x.denlaclient,
    x.d1,
    x.d2,
    x.d3,
    x.d1s,
    x.d2s,
    x.d3s' || gUserAlias || '
  from (
  select
    obj.codobiect,
    obj.codarticol,
    p.codpart,
    ag.codpers,
    acli.codartcli,
    obj.denumire,
    obj.codextern,
    ag.nume||'' ''||ag.prenume agent,
    ci.nrdoc nrcmdi,
    cli.nrdoc nrcmdcli,
    p.den_part,
    sum(ns.cantnir) cant,
    acli.CODLACLIENT,
    acli.denumire denlaclient,
    art.d1,
    art.d2,
    art.d3,
    ns.d1 d1s,
    ns.d2 d2s,
    ns.d3 d3s,
    cli.codcomanda,
    i1.codintr1
  FROM intrari i
       inner join intrari1     i1   on i.codintr          = i1.codintr
       inner join nartobj      obj  on obj.codobiect      = i1.codobiect
       inner join nart         art  on obj.codarticol     = art.codarticol
       inner join nir               on i.codintr          = nir.codintr
       inner join nirstoc      ns   on ns.codnir          = nir.codnir and ns.codintr1 = i1.codintr1
       left  join npers        ag   on ag.codpers         = i.agent
       left  join intrprodlink l    on l.codintr1         = i1.codintr1
       left  join cmdprodmat   prod on prod.codcmdprodmat = l.codliniecomanda
       left  join comanda1     ci1  on ci1.codcomanda1    = prod.codcomanda1
       left  join comanda      ci   on ci1.codcomanda     = ci.codcomanda
       left  join cmdlink      cmdl on cmdl.codcomanda1   = ci1.codcomanda1
       left  join comanda1     cli1 on cli1.codcomanda1   = cmdl.codliniecomanda
       left  join comanda      cli  on cli1.codcomanda    = cli.codcomanda
       left  join npart        p    on p.codpart          = cli.partener
       left  join nartcli      acli on acli.codobiect = obj.codobiect and acli.codpart = cli.partener
  WHERE i.codintr in (' || coalesce(current_setting('PKG_LIST_BASE_PRODETICHETE.vCoduri', true),'') || ')
  group by
    obj.codobiect,
    obj.codarticol,
    p.codpart,
    ag.codpers,
    acli.CODARTCLI,
    obj.denumire,
    obj.codextern,
    ag.nume,ag.prenume,
    ci.nrdoc,
    cli.nrdoc,
    p.den_part,
    acli.CODLACLIENT,
    acli.denumire,
    art.d1,
    art.d2,
    art.d3,
    ns.d1,
    ns.d2,
    ns.d3,
    cli.codcomanda,
    i1.codintr1
  ) x
    inner join (WITH RECURSIVE aa AS
                (
                  SELECT 1 NrColet
                  UNION ALL
                  SELECT aa.NrColet+1 FROM aa WHERE aa.NrColet&lt;10000
                )
                SELECT NrColet FROM aa
               ) Y          ON Y.NrColet &lt;= ' || sCompare || ' and y.nrcolet &gt; 0
    left  join intrari1 i1  on i1.codintr1     = x.codintr1
    left  join comanda ccli on ccli.codcomanda = x.codcomanda
    left  join nart art     on art.codarticol  = x.codarticol
    left  join nartobj obj  on obj.codobiect   = x.codobiect
    left  join npart p      on p.codpart       = x.codpart
    left  join npers ag     on ag.codpers      = x.codpers
    left  join nartcli acli on acli.codartcli  = x.codartcli ' || 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_rapstoc_processlist</obj_name>
  <obj_hashval>de4454343b509898fdc184e09c8e12cd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rapstoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert          VARCHAR := '';
  sDinCol          VARCHAR := '';
  sDinSel          VARCHAR := '';
  sDinTmp          VARCHAR := '';
  vDataIni         VARCHAR := current_setting('PKG_LIST_BASE_RAPSTOC.dDataIni' , true);  --current_setting('PKG_LIST_SELECTSCAD.vDataIni' , true);
  vDataFin         VARCHAR := current_setting('PKG_LIST_BASE_RAPSTOC.dDataFin' , true);  --current_setting('PKG_LIST_SELECTSCAD.vDataScad', true);
  gSuplCols        VARCHAR := '';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  v_rec           record;
BEGIN
  --Adina 10 septembrie 2020
  gSuplCols := 'ngest g, intrari intr, iesiri ies, transf t, npart p, npers ag';
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_RAPSTOC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  FOR v_rec IN (SELECT FIELDNAME, INDEXLOCAL FROM tmp_dinamic_cols ORDER BY INDEXLOCAL) LOOP
    sDinCol := sDinCol||','||v_rec.FIELDNAME;
    sDinSel := sDinSel||', r.'||v_rec.FIELDNAME;
    sDinTmp := sDinTmp||',SUM((case when CodObiect = '||v_rec.INDEXLOCAL::varchar||' then Cant else 0 end)) '||v_rec.FIELDNAME;
  END LOOP;

  sInsert:=
  'INSERT INTO '|| tmpName ||'(
    NAV_CodDoc, NAV_TipDoc, DenGest, Part, Promo, TipDoc, Doc, DataDoc, Ord '||sDinCol||gUserFields||')
  WITH r AS (
    SELECT coddoc, tipdoc, promo, codgest, semn '||sDinTmp||'
    FROM tmp_list_rapstoc
    GROUP BY coddoc, tipdoc, promo, codgest, semn
  )
  SELECT
    r.CODDOC, r.TIPDOC, g.Den_Gest,
    CASE
      WHEN r.TIPDOC =  0 THEN ''Stoc initial la '||vDataIni||'''
      WHEN r.TIPDOC =  6 THEN ''Intrare de la subunitate''
      WHEN r.TIPDOC =  7 THEN ''Intrare din productie''
      WHEN r.TIPDOC = 12 AND r.SEMN = 1 THEN ''Intrare prin transfer''
      WHEN r.TIPDOC = 12 THEN ''Iesire prin transfer''
      WHEN r.TIPDOC = 14 THEN ''Minus la inventar''
      WHEN r.TIPDOC = 15 THEN ''Plus la inventar''
      WHEN r.TIPDOC = 16 THEN ''Iesiri pe monetar''
      WHEN r.TIPDOC = 23 THEN ''Iesire catre alta subunitate''
      WHEN r.TIPDOC = 24 THEN ''Iesire in consum''
      ELSE p.Den_part
    END,
    (case when r.Promo=1 then ''Da'' else ''Nu'' end),
    (case r.TIPDOC
        when 0  then ''S''
        when 12 then ''T''
        when 13 then ''PV''
        when 14 then ''PV''
        when 15 then ''PV''
        when 16 then ''M''
        when 2  then ''AE''
        when 20 then ''AE''
        when 3  then ''CF''
        when 21 then ''CF''
        else ''F''
     end),
    CASE
      WHEN r.TIPDOC = 0 THEN ''Stoc initial''
      ELSE Coalesce(intr.prefixdoc,ies.prefixdoc,t.prefixdoc)||Coalesce(intr.nrdoc,ies.nrdoc,t.nrdoc)||''/''||To_Char(Coalesce(intr.datadoc,ies.datadoc,t.datadoc),''dd.mm.yyyy'')
    END,
    CASE WHEN r.TIPDOC = 0 THEN to_date('''||vDataIni||''',''dd.mm.yyyy'') ELSE Coalesce(intr.datadoc,ies.datadoc,t.datadoc) END,
    (case when r.TIPDOC=0 then 0 else 1 end) '||sDinSel||gUserAlias||'
  FROM r
    LEFT JOIN ngest   g    ON g.codgest    = r.codgest
    LEFT JOIN intrari intr ON intr.codintr = r.coddoc AND intr.tipdoc = r.tipdoc
    LEFT JOIN iesiri  ies  ON ies.codies   = r.coddoc AND  ies.tipdoc = r.tipdoc
    LEFT JOIN transf  t    ON t.codtransf  = r.coddoc AND    t.tipdoc = r.tipdoc
    LEFT JOIN npart   p    ON p.codpart    = Coalesce(intr.partener,ies.partener,0)
    LEFT JOIN npers   ag   ON ag.codpers   = COALESCE(ies.agent,0) '|| gSuplJoins;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  sInsert:=
  'INSERT INTO '|| tmpName ||'(
    NAV_CodDoc, NAV_TipDoc, DenGest, Part, Promo, TipDoc, Doc, DataDoc, Ord '||sDinCol||')
  WITH r AS (
    SELECT codgest '||sDinTmp||'
    FROM ( SELECT codgest, codobiect, SUM(cant * semn) cant FROM tmp_list_rapstoc GROUP BY codgest, codobiect) B_PG
    GROUP BY codgest
  )
  SELECT
    0, 0, g.Den_Gest,
    ''Stoc final la '||vDataFin||''', ''Nu'', ''S'', ''Stoc final'', to_date('''||vDataFin||''',''dd.mm.yyyy''),2 '||sDinSel||'
  FROM r LEFT JOIN ngest g ON g.codgest = r.codgest';

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_inventar_processlist</obj_name>
  <obj_hashval>0a369950bada35668277c346a0c12dc8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_inventar_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 := '';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vID              NUMERIC := current_setting('PKG_LIST_BASE_INVENTAR.vID', true)::NUMERIC;
  p_CodInventar    varchar := current_setting('PKG_LIST_BASE_INVENTAR.p_CodInventar', true);
BEGIN
  --Florin 05.02.2025 - sinc. Oracle
  --Florin 09.01.2023 - fixat 56741
  --Adina 02.04.2021 -alstart,alstop
  --Adina 25 septembrie 2020
  IF  vID = 92 THEN
    gSuplCols := 'NARTOBJ OBJ, NART A, INVENTAR1 IV1, IOART1 IO1, NCONT CONT, NCLASEA CLS, NIRSER NSE, NSERII SER, NPART PROD, INVENTREZ IVZ, INVENTSTOC IVS';
  ELSE
    gSuplCols := 'NARTOBJ OBJ, NART A, INVENTAR1 I1, NUM1 NUM1, NPART PROD, NUM UM1, NUM UM2, NSERII SER, NCLASEA CLS, NLOCATII LOC';
  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_INVENTAR.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF  vID = 92 THEN
    sInsert :=
    'INSERT INTO ' || tmpName || ' (
       Pret, Art, Serie, UM, ExpiraLa, StocS, StocF, Dif, ValS, ValF, CodExt, Clasa, CodInt, Loc, ValDif, Dim, Mar, Cont, UM1,
       StocSUM1, StocFUM1, CantNUM1, UM2, StocSUM2, StocFUM2, CantNUM2, StocFL, StocFL1, StocFL2, NrInv, SerieInv ' || gUserFields || ' )
     WITH MFIX AS (
       select mfx1.codnirstoc, substr(fnc_array_to_vc3200(array_agg(Distinct mfx.nrinventar::varchar)),1,2500) nrinv,  --aa: scos ORDER BY mfx.codmifix
       substr(fnc_array_to_vc3200(array_agg(Distinct mfx.serieinv::varchar)),1,2500) serieinv                           --aa: scos ORDER BY mfx.codmifix
       FROM tmp_inventstoc INV1
            INNER JOIN TMP_INVENTAR INV ON INV.CODINVENTAR = INV1.CODINVENTAR
            inner join nirstoc ns       on inv1.codnirstoc = ns.codnirstoc
            inner join mifix1 mfx1      on mfx1.codnirstoc = ns.codnirstoc
            inner join mifix mfx        on mfx.codmifix    = mfx1.codmifix
       where MFX1.ANSTART * 12 + MFX1.LUNASTART = extract(year from inv.datainventar) * 12 + extract(month from inv.datainventar)
       group by mfx1.codnirstoc
     )
    SELECT
      INV1.pret, obj.Denumire, ser.Serie, I1.Den_UMSec, I1.Expirare, coalesce(Inv1.rest, 0), coalesce(Inv1.rest, 0) + coalesce(rez.rezolvat,0), coalesce(rez.rezolvat,0), coalesce(INV1.rest, 0) * coalesce(INV1.pret, 0),
      (coalesce(Inv1.rest, 0) + coalesce(rez.rezolvat,0))*inv1.pret, I1.CodExtern, CLS.den_clasea, obj.codintern, I1.Den_Locatie, coalesce(rez.Rezolvat, 0) * coalesce(rez.pretInreg, 0),
      case when coalesce(rez.Rezolvat, 0) &lt;  0 then ABS(coalesce(rez.Rezolvat, 0)) else 0 end,
      case when coalesce(rez.Rezolvat, 0) &gt;= 0 then ABS(coalesce(rez.Rezolvat, 0)) else 0 end,
      cont.simbol, I1.Den_UM1, coalesce(INV1.restum1, 0), coalesce(Inv1.restum1, 0) + coalesce(rez.rezolvatum1,0), coalesce(rez.rezolvatum1, 0), I1.Den_UM2,
      coalesce(INV1.restum2, 0), coalesce(Inv1.restum2, 0) + coalesce(rez.rezolvatum2,0), coalesce(rez.rezolvatum2, 0), i1.faptic, i1.fapticUM1, i1.fapticUM2,
      mfix.nrinv, mfix.serieinv ' || gUserAlias || '
    FROM tmp_inventstoc INV1
      inner join tmp_inventar1 i1 on inv1.codinventar1 = i1.codinventar1
      inner join tmp_inventar i   on i.codinventar     = i1.codinventar
      inner join nirstoc ns       on inv1.codnirstoc   = ns.codnirstoc
      inner join ioart1 io1       on io1.codioart      = ns.codioart  AND (extract(year from i.datainventar)*12+extract(month from i.datainventar)) BETWEEN io1.ALStart and io1.ALStop
      inner join NARTOBJ OBJ       ON ns.codobiect      = OBJ.codObiect
      INNER JOIN NART A           ON OBJ.codarticol    = A.codarticol
      INNER JOIN INVENTAR1 IV1     on iv1.codinventar1  = INV1.COdinventar1
      INNER JOIN INVENTSTOC    IVS  ON INV1.CODINVENTSTOC = IVS.CODINVENTSTOC
      left join mfix               on mfix.codnirstoc   = inv1.codnirstoc
      left join NCLASEA CLS       on A.CLASA           = CLS.codclasea
      left join ncont cont         on cont.codcont      = io1.cont
      left join nirser nse         on inv1.codnirser    = nse.codnirser
      left join nserii ser         on nse.codserie      = ser.codserie
      left join tmp_inventrez rez on rez.codnirstoc    = inv1.codnirstoc and coalesce(rez.codnirser,0) = coalesce(inv1.codnirser,0) and rez.codinventar1 = i1.codinventar1
      LEFT JOIN INVENTREZ IVZ     ON IVZ.CODREZOLVARE  = REZ.CODREZOLVARE
      left join npart prod         on prod.codpart      = obj.codproducator' || gSuplJoins || '
    WHERE i1.scriptic &lt;&gt; 0
    UNION ALL
    SELECT
      INV1.pret, obj.Denumire, ser.Serie, I1.Den_UMSec, I1.Expirare, coalesce(Inv1.rest, 0), coalesce(Inv1.rest, 0) + coalesce(rez.rezolvat,0), coalesce(rez.rezolvat,0), coalesce(INV1.rest, 0) * coalesce(INV1.pret, 0),
      (coalesce(Inv1.rest, 0) + coalesce(rez.rezolvat,0))*inv1.pret, I1.CodExtern, CLS.den_clasea, obj.codintern, I1.Den_Locatie, coalesce(rez.Rezolvat, 0) * coalesce(rez.pretInreg, 0),
      case when coalesce(rez.Rezolvat, 0) &lt; 0 then ABS(coalesce(rez.Rezolvat, 0)) else 0 end,
      case when coalesce(rez.Rezolvat, 0) &gt;= 0 then ABS(coalesce(rez.Rezolvat, 0)) else 0 end,
      cont.simbol, I1.Den_UM1, coalesce(INV1.restum1, 0), coalesce(Inv1.restum1, 0) + coalesce(rez.rezolvatum1,0), coalesce(rez.rezolvatum1, 0), I1.Den_UM2,
      coalesce(INV1.restum2, 0), coalesce(Inv1.restum2, 0) + coalesce(rez.rezolvatum2,0), coalesce(rez.rezolvatum2, 0), i1.faptic, i1.fapticUM1, i1.fapticUM2,
      mfix.nrinv, mfix.serieinv ' || gUserAlias || '
    FROM tmp_inventar1 i1
      left join tmp_inventstoc INV1 on inv1.codinventar1 = i1.codinventar1
      LEFT JOIN INVENTSTOC    IVS  ON INV1.CODINVENTSTOC = IVS.CODINVENTSTOC
      left join tmp_inventar i       on i.codinventar     = i1.codinventar
      left join nirstoc ns           on inv1.codnirstoc   = ns.codnirstoc
      left join ioart1 io1           on io1.codioart      = ns.codnirstoc - ns.codnirstoc
      left join NARTOBJ OBJ         ON i1.codobiect      = OBJ.codObiect
      left join NART A               ON OBJ.codarticol    = A.codarticol
      left join INVENTAR1 IV1       on iv1.codinventar1  = INV1.COdinventar1
      left join mfix                 on mfix.codnirstoc   = inv1.codnirstoc
      left join NCLASEA CLS         on A.CLASA           = CLS.codclasea
      left join ncont cont           on cont.codcont      = io1.cont
      left join nirser nse           on inv1.codnirser    = nse.codnirser
      left join nserii ser           on nse.codserie      = ser.codserie
      left join tmp_inventrez rez   on rez.codnirstoc    = inv1.codnirstoc and coalesce(rez.codnirser,0) = coalesce(inv1.codnirser,0) and rez.codinventar1 = i1.codinventar1
      LEFT JOIN INVENTREZ IVZ       ON IVZ.CODREZOLVARE  = REZ.CODREZOLVARE
      left join npart prod           on prod.codpart      = obj.codproducator' || gSuplJoins || '
    WHERE coalesce(i1.scriptic,0) = 0 and inv1.codnirstoc &gt; 0
    UNION ALL
    SELECT
      rez.pretinreg, obj.Denumire, ser.Serie, I1.Den_UMSec, I1.Expirare, coalesce(Inv1.rest, 0), coalesce(Inv1.rest, 0) + coalesce(rez.rezolvat,0), coalesce(rez.rezolvat,0), coalesce(INV1.rest, 0) * coalesce(rez.pretinreg, 0),
      (coalesce(Inv1.rest, 0) + coalesce(rez.rezolvat,0))*rez.pretinreg, I1.CodExtern, CLS.den_clasea, obj.codintern, I1.Den_Locatie, coalesce(rez.Rezolvat, 0) * coalesce(rez.pretInreg, 0),
      case when coalesce(rez.Rezolvat, 0) &lt;  0 then ABS(coalesce(rez.Rezolvat, 0)) else 0 end,
      case when coalesce(rez.Rezolvat, 0) &gt;= 0 then ABS(coalesce(rez.Rezolvat, 0)) else 0 end,
      cont.simbol, I1.Den_UM1, coalesce(INV1.restum1, 0), coalesce(Inv1.restum1, 0) + coalesce(rez.rezolvatum1,0), coalesce(rez.rezolvatum1, 0), I1.Den_UM2,
      coalesce(INV1.restum2, 0), coalesce(Inv1.restum2, 0) + coalesce(rez.rezolvatum2,0), coalesce(rez.rezolvatum2, 0), i1.faptic, i1.fapticUM1, i1.fapticUM2,
      mfix.nrinv, serieinv ' || gUserAlias || '
    FROM tmp_inventar1 i1
      inner join tmp_inventrez rez   on rez.codinventar1  = i1.codinventar1
      LEFT JOIN INVENTREZ IVZ       ON IVZ.CODREZOLVARE  = REZ.CODREZOLVARE
      left join tmp_inventstoc INV1 on inv1.codinventar1 = i1.codinventar1
      LEFT JOIN INVENTSTOC    IVS  ON INV1.CODINVENTSTOC = IVS.CODINVENTSTOC
      left join tmp_inventar i       on i.codinventar     = i1.codinventar
      left join nirstoc ns           on rez.codnirstoc    = ns.codnirstoc
      left join ioart1         io1  on io1.codioart      = rez.codioart
      left join NARTOBJ OBJ         ON i1.codobiect      = OBJ.codObiect
      left join NART A               ON OBJ.codarticol    = A.codarticol
      left join INVENTAR1 IV1       on iv1.codinventar1  = INV1.COdinventar1
      left join mfix                 on mfix.codnirstoc   = inv1.codnirstoc
      left join NCLASEA CLS         on A.CLASA           = CLS.codclasea
      left join ncont cont           on cont.codcont      = io1.cont
      left join nirser nse           on rez.codnirser     = nse.codnirser
      left join nserii ser           on nse.codserie      = ser.codserie
      left join npart prod           on prod.codpart      = obj.codproducator' || gSuplJoins || '
    WHERE coalesce(i1.scriptic,0) = 0 and rez.codnirstoc &gt; 0 and coalesce(inv1.codinventar1,0) = 0
      AND (extract(year from i.datainventar)*12+extract(month from i.datainventar)) BETWEEN io1.ALStart and io1.ALStop
    UNION ALL
    SELECT
      rez.pretinreg, obj.Denumire, ser.Serie, I1.Den_UMSec, I1.Expirare, coalesce(Inv1.rest, 0), coalesce(Inv1.rest, 0) + coalesce(rez.rezolvat,0), coalesce(rez.rezolvat,0), coalesce(INV1.rest, 0) * coalesce(rez.pretinreg, 0),
      (coalesce(Inv1.rest, 0) + coalesce(rez.rezolvat,0))*rez.pretinreg, I1.CodExtern, CLS.den_clasea, obj.codintern, I1.Den_Locatie, coalesce(rez.Rezolvat, 0) * coalesce(rez.pretInreg, 0),
      case when coalesce(rez.Rezolvat, 0) &lt;  0 then ABS(coalesce(rez.Rezolvat, 0)) else 0 end,
      case when coalesce(rez.Rezolvat, 0) &gt;= 0 then ABS(coalesce(rez.Rezolvat, 0)) else 0 end,
      cont.simbol, I1.Den_UM1, coalesce(INV1.restum1, 0), coalesce(Inv1.restum1, 0) + coalesce(rez.rezolvatum1,0), coalesce(rez.rezolvatum1, 0), I1.Den_UM2,
      coalesce(INV1.restum2, 0), coalesce(Inv1.restum2, 0) + coalesce(rez.rezolvatum2,0), coalesce(rez.rezolvatum2, 0), i1.faptic, i1.fapticUM1, i1.fapticUM2,
      mfix.nrinv, mfix.serieinv ' || gUserAlias || '
    FROM tmp_inventar1 i1
      inner join tmp_inventrez rez  on rez.codinventar1  = i1.codinventar1
      LEFT JOIN INVENTREZ IVZ       ON IVZ.CODREZOLVARE  = REZ.CODREZOLVARE
      left join tmp_inventstoc INV1 on inv1.codinventar1 = i1.codinventar1 and inv1.codnirstoc = rez.codnirstoc and coalesce(inv1.codnirser,0) = coalesce(rez.codnirser,0)
      LEFT JOIN INVENTSTOC    IVS  ON INV1.CODINVENTSTOC = IVS.CODINVENTSTOC
      left join tmp_inventar i       on i.codinventar     = i1.codinventar
      left join nirstoc ns           on rez.codnirstoc    = ns.codnirstoc
      left join ioart1 io1           on io1.codioart      = ns.codnirstoc - ns.codnirstoc
      left join NARTOBJ OBJ         ON i1.codobiect      = OBJ.codObiect
      left join NART A               ON OBJ.codarticol    = A.codarticol
      left join INVENTAR1 IV1       on iv1.codinventar1  = INV1.COdinventar1
      left join mfix                 on mfix.codnirstoc   = inv1.codnirstoc
      left join NCLASEA CLS         on A.CLASA           = CLS.codclasea
      left join ncont cont           on cont.codcont      = io1.cont
      left join nirser nse           on rez.codnirser     = nse.codnirser
      left join nserii ser           on nse.codserie      = ser.codserie
      left join npart prod           on prod.codpart      = obj.codproducator' || gSuplJoins || '
    WHERE coalesce(i1.scriptic,0) &gt; 0 and rez.codnirstoc &gt; 0 and coalesce(inv1.codinventar1,0) = 0
    ';

  sInsert1 :=
  'INSERT INTO ' || tmpName || ' (
      Pret, Art, Serie, UM, ExpiraLa, StocS, StocF, Dif, ValS, ValF, CodExt, Clasa, CodInt, Loc, ValDif, Dim, Mar, Cont, UM1,
      StocSUM1, StocFUM1, CantNUM1, UM2, StocSUM2, StocFUM2, CantNUM2, StocFL, StocFL1, StocFL2 ' || gUserFields || ' )
    SELECT
      rez.pretinreg, obj.Denumire, ser.Serie, I1.Den_UMSec, I1.Expirare, 0, coalesce(rez.rezolvat,0), coalesce(rez.rezolvat,0), 0,
      coalesce(rez.rezolvat, 0)* coalesce(rez.pretinreg,0), I1.CodExtern, CLS.den_clasea, obj.codintern, I1.Den_Locatie, coalesce(rez.Rezolvat, 0) * coalesce(rez.pretInreg, 0),
      case when I1.Diferente &lt; 0 then ABS(coalesce(rez.Rezolvat, 0)) else 0 end,
      case when I1.Diferente &gt;= 0 then ABS(coalesce(rez.Rezolvat, 0)) else 0 end,
      cont.simbol, I1.Den_UM1, 0, coalesce(rez.rezolvatum1,0), coalesce(rez.rezolvatum1,0), I1.Den_UM2, 0,
      coalesce(rez.rezolvatum2,0), coalesce(rez.rezolvatum2,0), i1.faptic, i1.fapticUM1, i1.fapticUM2 ' || gUserAlias || '
    FROM tmp_inventrez rez
      inner join tmp_inventar1 i1 on i1.codinventar1  = rez.codinventar1
      inner join tmp_inventar i   on i.codinventar    = i1.codinventar
      inner join NARTOBJ OBJ       ON i1.codobiect     = OBJ.codObiect
      INNER JOIN NART A           ON OBJ.codarticol   = A.codarticol
      INNER JOIN INVENTAR1 IV1     on iv1.codinventar1 = I1.COdinventar1
      inner join ioart1 io1       on io1.codioart     = rez.codioart  AND (extract(year from i.datainventar)*12+extract(month from i.datainventar)) BETWEEN io1.ALStart and io1.ALStop
      LEFT JOIN INVENTREZ IVZ     ON IVZ.CODREZOLVARE = REZ.CODREZOLVARE
      left join ncont cont         on cont.codcont     = io1.cont
      left join NCLASEA CLS       on A.CLASA          = CLS.codclasea
      left join nirser nse        on rez.codnirser    = nse.codnirser
      left join nserii ser         on i1.codserie      = ser.codserie
      left join npart prod         on prod.codpart     = obj.codproducator
      LEFT JOIN INVENTSTOC    IVS  ON REZ.CODINVENTAR1 - REZ.CODINVENTAR1 = IVS.CODINVENTSTOC ' || gSuplJoins || '
    WHERE coalesce(rez.codnirstoc,0)=0 and coalesce(i1.scriptic,0) &lt;&gt; 0
    UNION ALL
    SELECT
      rez.pretinreg, obj.Denumire, ser.Serie, I1.Den_UMSec, I1.Expirare, 0, coalesce(rez.rezolvat,0), coalesce(rez.rezolvat,0), 0,
      coalesce(rez.rezolvat, 0)* coalesce(rez.pretinreg,0), I1.CodExtern, CLS.den_clasea, obj.codintern, I1.Den_Locatie, coalesce(rez.Rezolvat, 0) * coalesce(rez.pretInreg, 0),
      case when I1.Diferente &lt; 0 then ABS(coalesce(rez.Rezolvat, 0)) else 0 end,
      case when I1.Diferente &gt;= 0 then ABS(coalesce(rez.Rezolvat, 0)) else 0 end,
      cont.simbol, I1.Den_UM1, 0, coalesce(rez.rezolvatum1,0), coalesce(rez.rezolvatum1,0), I1.Den_UM2, 0,
      coalesce(rez.rezolvatum2,0), coalesce(rez.rezolvatum2,0), i1.faptic, i1.fapticUM1, i1.fapticUM2 ' || gUserAlias || '
    FROM tmp_inventar1 i1
      left join tmp_inventrez rez on i1.codinventar1  = rez.codinventar1
      left join tmp_inventar i     on i.codinventar    = i1.codinventar
      LEFT JOIN INVENTREZ IVZ     ON IVZ.CODREZOLVARE = REZ.CODREZOLVARE
      left join NARTOBJ OBJ       ON i1.codobiect     = OBJ.codObiect
      left JOIN NART A             ON OBJ.codarticol   = A.codarticol
      left JOIN INVENTAR1 IV1     on iv1.codinventar1 = I1.COdinventar1
      left join ioart1 io1         on io1.codioart     = rez.codioart
      left join ncont cont         on cont.codcont     = io1.cont
      left join NCLASEA CLS       on A.CLASA          = CLS.codclasea
      left join nirser nse        on rez.codnirser    = nse.codnirser
      left join nserii ser         on i1.codserie      = ser.codserie
      left join npart prod         on prod.codpart     = obj.codproducator
      LEFT JOIN INVENTSTOC    IVS  ON REZ.CODINVENTAR1 - REZ.CODINVENTAR1 = IVS.CODINVENTSTOC ' || gSuplJoins || '
    WHERE coalesce(rez.codnirstoc,0)=0 and coalesce(i1.scriptic,0) = 0
      AND (extract(year from i.datainventar)*12+extract(month from i.datainventar)) BETWEEN io1.ALStart and io1.ALStop ';
  ELSE
    sInsert := 'INSERT INTO ' || tmpName || ' (
       Art, Serie, UM, Expirala, StocS, StocF, Dif, CodExt, Clasa, CodInt, Loc,
       UM1, StocSUM1, StocFUM1, DifM1, UM2, StocSUM2, StocFUM2, DifUM2 ' || gUserFields || ' )
    SELECT
      obj.Denumire, ser.Serie, num1.Den_UM1, I1.Expirare, i1.scriptic, i1.faptic, coalesce(i1.faptic,0) - i1.scriptic, OBJ.CodExtern, CLS.den_clasea, obj.codintern, LOC.Denumire,
      um1.Den_UM, i1.scripticUM1, i1.fapticUM1, coalesce(i1.fapticUM1,0) - i1.scripticUM1, um2.Den_UM, i1.scripticUM2, i1.fapticUM2, coalesce(i1.fapticUM2,0) - i1.scripticUM2 ' || gUserAlias || '
    FROM inventar1 i1
      inner join NARTOBJ OBJ   ON i1.codobiect   = OBJ.codObiect
      INNER JOIN NART A       ON OBJ.codarticol = A.codarticol
      inner join num1         on num1.codum1    = i1.um1
      left join npart prod     on prod.codpart   = obj.codproducator
      left join num um1       on a.um1          = um1.codum
      left join num um2       on a.um2          = um2.codum
      left join nserii ser     on i1.codserie    = ser.codserie
      left join NCLASEA CLS   on A.CLASA        = CLS.codclasea
      left join nlocatii loc   on i1.codlocatie  = loc.codlocatie' || gSuplJoins || '
    WHERE i1.codinventar = ' || coalesce(p_CodInventar,'');
  END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  IF  vID = 92 THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert1, aListID, aListVer);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz1_processlist</obj_name>
  <obj_hashval>2a7225b397738fc505b0970a92e4a5d9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz1_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert               varchar := '';
  sSelect               varchar := '';
  sWhere                 varchar := '';
  sColMinMax             varchar := ', NAOS.STOCMIN, NAOS.STOCMED, NAOS.STOCMAX';
  vToateGest             BOOLEAN;
  vCuNecesarZero         BOOLEAN;
  vAducStocMinMaxGest   BOOLEAN;
  vSelStocReal           varchar := '';
  vCateGest             NUMERIC := 0;
  vCateLGest             NUMERIC := 0;
  vToateIOArt           boolean := 0;
  vCond_Subunit_C       varchar := '';
  vCond_Subunit_CS      varchar := '';
  vCond_Subunit_G       varchar := '';
  vUserID               numeric;
  sFiltruCMD             varchar := '';
  sDataIni               varchar := '';
  sDataFin               varchar := '';
  sStocMinMaxJoin       VARCHAR := '';
  pUsername             varchar := '';
  pStocExternFirma       varchar := fnc_GetValConstanta('StocExternFirma', getANLUCRU(), getlunalucru());
  pStocExternCamp       varchar := PKG_LIST_BASE_UTILS_Get_StocExternCamp();
  gSuplCols             VARCHAR := 'NARTOBJ NAO, NARTOBJSUBUNIT NAOS, NART NA, NUM NUM, NPART PROD, NCLASEA CLSA, PRETM PM, NGEST GIMP, NPART FURNP, NGEST FURNG';
   gUserFields           VARCHAR := '';
  gUserAlias            VARCHAR := '';
  gNullAlias            VARCHAR := '';
  gSuplJoins            VARCHAR := '';
  vCentralizat          NUMERIC;
  sSubunitMinMax        VARCHAR := '';
  sSubunitMinMaxGroupBy VARCHAR := '';
BEGIN
  --Florin 03.02.2025 - fixat 64626
  --Florin 31.01.2025 - fixat 64584
  --Florin 23.01.2025 - sinc. Oracle
  --Florin 20.01.2025 - sinc. Oracle
  --Florin 17.01.2025 - sinc. Oracle
  --Florin 28.11.2024 - fixat 64136
  --Florin 26.11.2024 - sinc. Oracle
  --Adina 17.08.2021 - sinc.Oracle din 16.08.2021
  --Adina 29.04.2021 - sinc.Oracle - doar la zi
  --Adina 20.04.2021 - sinc.Oracle - doar la zi
  --Adina 12.02.2021 - modif.Oracle din 10.02.2021
  --Adina 28.12.2020 - add index la TMP_PRETACH
  --Adina 10.12.2020 tichet 41518
  --Adina 27 august 2020
  vUserId          := COALESCE(current_setting('PKG_GLOBALS.USERID', true)::numeric, 0);
  vCond_Subunit_C  := ' AND EXISTS (SELECT TMPS.VALOARE FROM TMP_MANEVRA_LISTE TMPS WHERE TMPS.FILTRU = ''CODSUBUNIT'' AND TMPS.VALOARE = C.SUBUNITATEA::varchar) ';
  vCond_Subunit_CS := ' AND EXISTS (SELECT TMPS.VALOARE FROM TMP_MANEVRA_LISTE TMPS WHERE TMPS.FILTRU = ''CODSUBUNIT'' AND TMPS.VALOARE = C.SubunitSursa::varchar) ';
  vCond_Subunit_G  := ' AND G.CODSUBUNIT::varchar IN (SELECT TMPS.VALOARE FROM TMP_MANEVRA_LISTE TMPS WHERE TMPS.FILTRU = ''CODSUBUNIT'') ';

  PERFORM pkg_globals_SetSeparator('/');

  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_STOCEXTERN', 'TSE',  'TSE.CODCOMUN = NAO.' || coalesce(pStocExternCamp,''));
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_NAPROVIZ1.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  IF  StrPos(gSuplJoins, 'TMP_STOCEXTERN') &gt; 0 THEN
    --SELECT CURRENT_SCHEMA INTO pUSERNAME;
    pUSERNAME := current_setting('PKG_GLOBALS.FIRMANAME', true);
    PERFORM winmadmin.PKG_USERFIRME_POPULEAZA_STOCURI_EXTERNE(pUSERNAME, pStocExternFirma, pStocExternCamp);
  END IF;

  vToateGest          := current_setting('pkg_list_base_naproviz1.vToateGest' , true)::boolean;
  vToateIOArt         := current_setting('pkg_list_base_naproviz1.vToateIoart', true)::boolean;  --(SELECT PKG_LIST_SELECTSCAD_ToateIoart.WME_RESULT FROM PKG_LIST_SELECTSCAD_ToateIoart(NULL,NULL));
  vCuNecesarZero      := current_setting('pkg_list_base_naproviz1.vExtra1'    , true)::boolean;   --(SELECT PKG_LIST_SELECTSCAD_Extra1.WME_RESULT FROM PKG_LIST_SELECTSCAD_Extra1(NULL,NULL));
  vAducStocMinMaxGest := current_setting('pkg_list_base_naproviz1.vExtra2'    , true)::boolean;

  sFiltruCMD := '';
  vCentralizat := CASE WHEN length(current_setting('pkg_list_base_naproviz1.vCentralizat', true))=0 THEN 0 ELSE current_setting('pkg_list_base_naproviz1.vCentralizat', true)::NUMERIC END ;
  IF  vCentralizat &gt; 0 THEN
    sDataIni   := 'TO_DATE(''' || coalesce(current_setting('pkg_list_base_naproviz1.vDataIni',  true),'') || ''',''DD.MM.YYYY'')';
    sDataFin   := 'TO_DATE(''' || coalesce(current_setting('pkg_list_base_naproviz1.vDataScad', true),'') || ''',''DD.MM.YYYY'')';
    sFiltruCMD := ' AND C1.TERMEN BETWEEN ' || sDataIni || ' AND ' || sDataFin || ' ';
  END IF;

  sSubunitMinMax        := ' SUBUNITATE, ';
  sSubunitMinMaxGroupBy := ' , SUBUNITATE ';

  IF GETSUBUNITATE() = 1 THEN
    sSubunitMinMax        := ' 1 as  SUBUNITATE, ';
    sSubunitMinMaxGroupBy := '';
  END IF;
INSERT INTO x(view_name, test) VALUES ('NAOS', vAducStocMinMaxGest);
  IF NOT vAducStocMinMaxGest THEN
      sStocMinMaxJoin := ' LEFT JOIN (
                                        SELECT 0 AS CODS,
                                           CODOBIECT,
                                           1 as  SUBUNITATE,
                                           SUM (STOCMIN)     AS STOCMIN,
                                           SUM (STOCMAX)     AS STOCMAX,
                                           SUM (STOCMED)     AS STOCMED,
                                           MIN (PROCSTOCMIN) AS PROCSTOCMIN,
                                           MIN (PROCSTOCMAX) AS PROCSTOCMAX,
                                           MIN (PROCSTOCMED) AS PROCSTOCMED,
                                           NULL AS CODGEST
                                           FROM NARTOBJSUBUNIT NSBN
                                            INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE::numeric = NSBN.SUBUNITATE AND TMP.FILTRU = ''CODSUBUNIT''
                                           WHERE  (NSBN.codgest is null or NSBN.codgest = 0)
                                               AND NSBN.SUBUNITATE  IN (SELECT CodSubunit FROM tmp_subunitdedicate)
                                           GROUP BY  CODOBIECT) NAOS ON NAO.CODOBIECT = NAOS.CODOBIECT ';
  ELSE
    sStocMinMaxJoin := ' LEFT JOIN (SELECT 0 AS CODS,
                                           CODOBIECT,
                                           SUM (STOCMIN)     AS STOCMIN,
                                           SUM (STOCMAX)     AS STOCMAX,
                                           SUM (STOCMED)     AS STOCMED,
                                           MIN (PROCSTOCMIN) AS PROCSTOCMIN,
                                           MIN (PROCSTOCMAX) AS PROCSTOCMAX,
                                           MIN (PROCSTOCMED) AS PROCSTOCMED,
                                           NULL::numeric AS CODGEST
                                     FROM NARTOBJSUBUNIT NSBN
                                     WHERE NSBN.CODGEST is NOT NULL ';
    sStocMinMaxJoin := sStocMinMaxJoin ||
    ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE::numeric = NSBN.CODGEST) ';

--    IF NOT (GETSUBUNITATE() = 1) THEN
--          sStocMinMaxJoin := sStocMinMaxJoin ||
--              '  AND NSBN.SUBUNITATE = GETSUBUNITATE() ';
--    END IF;

    sStocMinMaxJoin := sStocMinMaxJoin ||
                         ' GROUP BY  CODOBIECT) NAOS ON NAO.CODOBIECT = NAOS.CODOBIECT';
  END IF;

  vSelStocReal := '
      SELECT NS.CODOBIECT, SUM(NS.REST) CANT
      FROM NIRSTOC NS
        INNER JOIN NIR     N ON NS.CODNIR   = N.CODNIR
        INNER JOIN NGEST   G ON G.CodGest   = N.GEST
        INNER JOIN NARTOBJ O ON O.CodObiect = NS.CodObiect AND COALESCE(O.INACTIV,0) = 0 ';

  vSelStocReal := coalesce(vSelStocReal,'') || '
        AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND coalesce(VALOARE,'''') = coalesce(N.GEST::varchar,'''') ) ';

  IF  NOT vToateIOArt THEN
    vSelStocReal := coalesce(vSelStocReal,'') || '
        AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND coalesce(VALOARE,'''') = coalesce(NS.CODIOART::varchar,'''') ) ';
  END IF;

  vSelStocReal := coalesce(vSelStocReal,'') || '
      GROUP BY NS.CODOBIECT';

  sWhere := '
  WHERE ((
    COALESCE(SR.Cant,0) + COALESCE(CF.RESTA,0) - COALESCE(CC.RESTA,0) - COALESCE(CSERV.RESTA,0) + COALESCE(CSIN.RESTA,0) - COALESCE(CSIES.RESTA,0) + COALESCE(CIIN.RESTA,0) - COALESCE(CIIES.RESTA,0) - COALESCE(CG.RESTA,0) &lt; COALESCE(NAOS.STOCMIN,0) OR
    COALESCE(SR.Cant,0) + COALESCE(CF.RESTA,0) - COALESCE(CC.RESTA,0) - COALESCE(CSERV.RESTA,0) + COALESCE(CSIN.RESTA,0) - COALESCE(CSIES.RESTA,0) + COALESCE(CIIN.RESTA,0) - COALESCE(CIIES.RESTA,0) - COALESCE(CG.RESTA,0) &lt; COALESCE(NAOS.STOCMAX,0) ) AND
    COALESCE(SR.Cant,0) + COALESCE(CF.RESTA,0) - COALESCE(CC.RESTA,0) - COALESCE(CSERV.RESTA,0) + COALESCE(CSIN.RESTA,0) - COALESCE(CSIES.RESTA,0) + COALESCE(CIIN.RESTA,0) - COALESCE(CIIES.RESTA,0) - COALESCE(CG.RESTA,0) &gt;= 0) OR
    COALESCE(SR.Cant,0) + COALESCE(CF.RESTA,0) - COALESCE(CC.RESTA,0) - COALESCE(CSERV.RESTA,0) + COALESCE(CSIN.RESTA,0) - COALESCE(CSIES.RESTA,0) + COALESCE(CIIN.RESTA,0) - COALESCE(CIIES.RESTA,0) - COALESCE(CG.RESTA,0) &lt; 0
  AND COALESCE(NA.TIPARTICOL,''0'') = ''0'' ';

  IF vCuNecesarZero THEN
    sWhere := ' WHERE COALESCE(NA.TIPARTICOL,''0'') = ''0'' ';
  END IF;

  sWhere := coalesce(sWhere,'') || ' AND COALESCE(NAO.INACTIV,0) = 0 ';

  sInsert :=
  'INSERT INTO ' || tmpName || '(
    Articol, UM, PretAch, CantAch, PretMedAch,
    Cant,
    Val,
    Sursa, Data, Furn, StocMIN, StocMED, StocMAX, StocReal,
    CantC_CF   , CantA_CF   , RestA_CF,
    CantC_CC   , CantA_CC   , RestA_CC,
    CantC_CSERV, CantA_CSERV, RestA_CSERV,
    CantC_CSIn , CantA_CSIn , RestA_CSIn,
    CantC_CSIes, CantA_CSIes, RestA_CSIes,
    CantC_CG   , CantA_CG   , RestA_CG,
    CantC_CIIn , CantA_CIIn , RestA_CIIn,
    CantC_CIIes, CantA_CIIes, RestA_CIIes,
    CodExtern, CodIntern, Producator, Rezervat,RestCCMat,RestAstept ' || gUserFields || ')';

  TRUNCATE TABLE TMP_STOCREAL;
  sSelect := 'insert into tmp_stocreal(codobiect,cant) ' || coalesce(vSelStocReal,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sselect, aListID, aListVer);

  TRUNCATE TABLE TMP_STOCREZ;
  sSelect := coalesce('insert into tmp_stocrez(codobiect,rezervat) ' ||
     'SELECT NS.CODOBIECT, SUM(R.REST) REZERVAT
      FROM REZERVATS R
        INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = R.CODNIRSTOC
        INNER JOIN NIR     N  ON NS.CODNIR     = N.CODNIR
        INNER JOIN NGEST   G  ON N.GEST        = G.CodGest ','') || coalesce(vCond_Subunit_G,'') || '
        INNER JOIN NARTOBJ O  ON O.CodObiect   = NS.CodObiect
      WHERE COALESCE(R.REST,0) &gt; 0 AND COALESCE(O.INACTIV,0) = 0 ';
  if NOT vToateGest THEN
    sSelect := coalesce(sSelect,'') || '
        AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND coalesce(VALOARE,'''') = coalesce(N.GEST::varchar,'''')) ';
    sSelect := coalesce(sSelect,'') || '    GROUP BY NS.CODOBIECT';
    EXECUTE sSelect;
  END IF;

  ALTER TABLE TMP_CMD   SET UNLOGGED ;
  ALTER TABLE TMP_CMDTL SET UNLOGGED ;

  DELETE FROM TMP_CMD   WHERE USERID = vUserId;
  DELETE FROM TMP_CMDTL WHERE USERID = vUserId;
  TRUNCATE TABLE tmp_manevra_consum;

  sSelect := coalesce('insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) ' ||
     'SELECT C1.CodObiect, SUM(C1.CantComandat) CantC, SUM(C1.CantAcceptat) CantA, SUM(C1.RestAcceptat) RestA, ''CF'',','') || coalesce(vUserId::varchar,'') || '
      FROM COMANDA1 C1
           INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
           INNER JOIN NARTOBJ O ON O.CodObiect   = C1.CodObiect
      WHERE COALESCE(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND COALESCE(O.INACTIV,0) = 0 AND
            C.TipDoc = 8 AND C1.RestAcceptat &gt; 0 ' || coalesce(sFiltruCMD,'') || coalesce(vCond_Subunit_C,'') || '
      GROUP BY C1.CodObiect';
  EXECUTE sSelect;

  sSelect := coalesce('insert into tmp_cmdtl(codcmdtl,codobiect,cantc, userid) ' ||
  'SELECT nextval(''SEQ_CMDTL_CODCMDTL''),CodObiect, cantc, ','') || coalesce(vUserId::varchar,'') || '
   from (
   select c1.codobiect, SUM(I1.RESTASTEPTARE) cantc
      FROM COMANDA1 C1
           INNER JOIN COMANDA  C  ON C1.CodComanda     = C.CodComanda
           INNER JOIN INTRLINK L  ON L.CODLINIECOMANDA = C1.CODCOMANDA1
           INNER JOIN INTRARI1 I1 ON I1.CODINTR1       = L.CODINTR1
           INNER JOIN INTRARI  I  ON I.CODINTR         = I1.CODINTR
           INNER JOIN NARTOBJ  O  ON O.CodObiect       = C1.CodObiect
      WHERE COALESCE(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 8 AND COALESCE(O.INACTIV,0) = 0 AND
            I.TIPFACTURA = 9 AND I.OPERAT = 1 AND I.ANULAT = 0 AND I1.RESTASTEPTARE &gt; 0 ' || coalesce(sFiltruCMD,'') || coalesce(vCond_Subunit_C,'') || '
      GROUP BY C1.CodObiect
      ) A_PG';
  EXECUTE sSelect;

  sSelect := 'insert into tmp_cmd(codobiect,resta,tip,userid) ' ||
  'select codobiect, sum(COALESCE(cant,0)) resta, ''CCMAT'',' || coalesce(vUserId::varchar,'') ||
  ' from (select pn.codobiect, (c1.cantacceptat-COALESCE(lansari.cant,0)) / pn0.cant * pn.cant cant
          from proiectnod pn
           inner join proiectnod pn0 on pn.codproiect = pn0.codproiect and pn0.nodoriginal = 0
           inner join comanda1 c1    on c1.codproiect = pn.codproiect
           inner join comanda c      on c.codcomanda  = c1.codcomanda
           left join (select sum(cant) cant, cmdlink.codliniecomanda codcomanda1, c1.codobiect
                      from cmdlink
                         inner join comanda1 c1 on c1.codcomanda1 = cmdlink.codcomanda1
                        group by cmdlink.codliniecomanda, c1.codobiect
                      ) lansari on lansari.codcomanda1 = c1.codcomanda1 and c1.codobiect = lansari.codobiect
    where c.tipdoc = 18 and c.anulat = 0 and c.operat = 1 and COALESCE(C.INCHISA, 0) = 0' || coalesce(sFiltruCMD,'') || ') A_PG group by codobiect';
  EXECUTE sSelect;

  sSelect := coalesce('insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) ' ||
  'SELECT C1.CodObiect, SUM(C1.CantComandat) CantC, SUM(C1.CantAcceptat) CantA, SUM(C1.RestAcceptat) RestA, ''CC'',','') || coalesce(vUserId::varchar,'') || '
      FROM COMANDA1 C1
           INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
           INNER JOIN NARTOBJ O ON O.CodObiect   = C1.CodObiect
      WHERE COALESCE(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND COALESCE(O.INACTIV,0) = 0 AND
            C.TipDoc = 18 AND C1.RestAcceptat &gt; 0 ' || coalesce(sFiltruCMD,'') || coalesce(vCond_Subunit_C,'') || '
      GROUP BY C1.CodObiect';
  EXECUTE sSelect;

  sSelect := coalesce('insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) ' ||
  'SELECT C1.CodObiect, SUM(C1.CantComandat) CantC, SUM(C1.CantAcceptat) CantA, SUM(C1.RestAcceptat) RestA, ''CSERV'',','') || coalesce(vUserId::varchar,'') || '
      FROM COMANDA1 C1
           INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
           INNER JOIN NARTOBJ O ON O.CodObiect   = C1.CodObiect
      WHERE COALESCE(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND COALESCE(O.INACTIV,0) = 0 AND
            C.TipDoc = 92 AND C1.RestAcceptat &gt; 0 ' || coalesce(sFiltruCMD,'') || coalesce(vCond_Subunit_C,'') || '
      GROUP BY C1.CodObiect';
  EXECUTE sSelect;

  sSelect := coalesce('insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) ' ||
  'SELECT C1.CodObiect, SUM(C1.CantComandat) CantC, SUM(C1.CantAcceptat) CantA, SUM(C1.RestAcceptat) RestA, ''CSIN'',','') || coalesce(vUserId::varchar,'') || '
      FROM COMANDA1 C1
           INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
           INNER JOIN NARTOBJ O ON O.CodObiect   = C1.CodObiect
      WHERE COALESCE(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND COALESCE(O.INACTIV,0) = 0 AND
            C.TipDoc = 44 AND C1.RestAcceptat &gt; 0 ' || coalesce(sFiltruCMD,'') || coalesce(vCond_Subunit_C,'') || '
      GROUP BY C1.CodObiect';
  EXECUTE sSelect;

  sSelect := coalesce('insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) ' ||
  'SELECT C1.CodObiect, SUM(C1.CantComandat) CantC, SUM(C1.CantAcceptat) CantA, SUM(C1.RestAcceptat) RestA, ''CSIES'',','') || coalesce(vUserId::varchar,'') || '
      FROM COMANDA1 C1
           INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
           INNER JOIN NARTOBJ O ON O.CodObiect   = C1.CodObiect
      WHERE COALESCE(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND COALESCE(O.INACTIV,0) = 0 AND
            C.TipDoc = 44 AND C1.RestAcceptat &gt; 0 ' || coalesce(sFiltruCMD,'') || coalesce(vCond_Subunit_CS,'') || '
      GROUP BY C1.CodObiect';
  EXECUTE sSelect;

  sSelect := coalesce('insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) ' ||
  'SELECT C1.CodObiect, SUM(C1.CantComandat) CantC, SUM(C1.CantAcceptat) CantA, SUM(C1.RestAcceptat) RestA, ''CG'',','') || coalesce(vUserId::varchar,'') || '
      FROM COMANDA1 C1
        INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
        INNER JOIN NGEST   G ON C.CodGest     = G.CodGest
        INNER JOIN NARTOBJ O ON O.CodObiect   = C1.CodObiect
      WHERE COALESCE(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND G.Tip = 1 AND COALESCE(O.INACTIV,0) = 0 AND
            C.TipDoc = 43 AND C1.RestAcceptat &gt; 0 ' || coalesce(sFiltruCMD,'') || coalesce(vCond_Subunit_C,'') || '
      GROUP BY C1.CodObiect';
  EXECUTE sSelect;

  sSelect := coalesce('insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) ' ||
  'SELECT CMDMAT.CodObiect, SUM(CMDMAT.Cant) CantC, SUM(CMDMAT.Cant) CantA, SUM(CMDMAT.Rest) RestA, ''CIIN'',','') || coalesce(vUserId::varchar,'') || '
      FROM CMDPRODMAT CMDMAT
        INNER JOIN COMANDA1 C1 ON CMDMAT.CodComanda1 = C1.CodComanda1
        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 = 53
        AND CMDMAT.Rest &gt; 0 ' || coalesce(vCond_Subunit_C,'') || '
        AND ((C1.Consum = 1 AND CMDMAT.Tip &lt;&gt; 1) OR (C1.Consum = 2 AND CMDMAT.Tip = 2))' || coalesce(sFiltruCMD,'') || '
      GROUP BY CMDMAT.CodObiect';
  EXECUTE sSelect;

  sSelect := coalesce('insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) ' ||
  'SELECT CMDMAT.CodObiect, SUM(CMDMAT.Cant) CantC, SUM(CMDMAT.Cant) CantA, SUM(CMDMAT.Rest) RestA, ''CIIES'',','') || coalesce(vUserId::varchar,'') || '
      FROM CMDPRODMAT CMDMAT
        INNER JOIN COMANDA1 C1 ON CMDMAT.CodComanda1 = C1.CodComanda1
        INNER JOIN COMANDA  C  ON C1.CodComanda      = C.CodComanda
      WHERE COALESCE(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0
        AND CMDMAT.Rest &gt; 0 ' || coalesce(vCond_Subunit_C,'') || '
        AND ((C1.Consum = 1 AND CMDMAT.Tip = 1) OR (C1.Consum = 2 AND CMDMAT.Tip &lt;&gt; 2))' || coalesce(sFiltruCMD,'') || '
      GROUP BY CMDMAT.CodObiect';
  EXECUTE sSelect;

  sSelect := 'insert into tmp_manevra_consum(codobiect,codcomanda1) ' ||
  'SELECT distinct CMDMAT.CodObiect, c1.codcomanda
      FROM CMDPRODMAT CMDMAT
        INNER JOIN COMANDA1 C1 ON CMDMAT.CodComanda1 = C1.CodComanda1
        INNER JOIN COMANDA  C  ON C1.CodComanda      = C.CodComanda
      WHERE COALESCE(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0
        AND CMDMAT.Rest &gt; 0 ' || coalesce(vCond_Subunit_C,'') || '
        AND ((C1.Consum = 1 AND CMDMAT.Tip = 1) OR (C1.Consum = 2 AND CMDMAT.Tip &lt;&gt; 2))' || coalesce(sFiltruCMD,'');
  EXECUTE sSelect;

  TRUNCATE TABLE TMP_PRETACH;
  sSelect := 'insert into tmp_PRETACH(CODOBIECT,PRETACH,DATAPRET,DEN_PART,SURSA,CANT,CODPART,CODGEST) ' || CHR(13) ||
  'SELECT CODOBIECT, PRETACH, DATANIR DATAPRET, CASE WHEN I.TIPDOC = 7 THEN S.DEN_GEST ELSE FURN.DEN_PART END DEN_PART, ''STOC'' SURSA, CANT, FURN.CODPART, S.CODGEST ' || CHR(13) ||
  'FROM ( '                 || CHR(13) ||
  '  SELECT NS.CODOBIECT, ' || CHR(13) ||
  '         FIRST_VALUE(NS.PRET - COALESCE(NS.ADAOS, 0)) OVER (PARTITION BY NS.CODOBIECT ORDER BY N.DATANIR DESC, NS.CODINTR1 DESC) PRETACH, ' || CHR(13) ||
  '         FIRST_VALUE(N.DATANIR)                  OVER (PARTITION BY NS.CODOBIECT ORDER BY N.DATANIR DESC, NS.CODINTR1 ASC) DATANIR, '      || CHR(13) ||
  '         FIRST_VALUE(N.CODINTR)                  OVER (PARTITION BY NS.CODOBIECT ORDER BY N.DATANIR DESC, NS.CODINTR1 ASC) CODINTR, '      || CHR(13) ||
  '         FIRST_VALUE(NS.CANTNIR)                 OVER (PARTITION BY NS.CODOBIECT ORDER BY N.DATANIR DESC, NS.CODINTR1 ASC) CANT, '         || CHR(13) ||
  '         ROW_NUMBER()                            OVER (PARTITION BY NS.CODOBIECT ORDER BY N.DATANIR DESC, NS.CODINTR1 ASC) ROWNR '         || CHR(13) ||
  '  FROM NIRSTOC NS '                                                      || CHR(13) ||
  '       INNER JOIN NARTOBJ O ON O.CodObiect = NS.CodObiect '              || CHR(13) ||
  '       INNER JOIN ( '                                                    || CHR(13) ||
  '                   SELECT N.CODNIR, N.DATANIR, N.CODINTR, G.CODSUBUNIT ' || CHR(13) ||
  '                   FROM NIR N '                                                                           || CHR(13) ||
  '                        INNER JOIN NGEST G ON N.GEST = G.CodGest ' || coalesce(vCond_Subunit_G,'') || ' ' || CHR(13) ||
  '                   WHERE TIPNIR IN (1,2,3,4,5,6,7,8,9) AND OPERAT = 1 AND ANULAT = 0 '                    || CHR(13) ||
  '                  ) N ON N.CODNIR = NS.CODNIR '                                                           || CHR(13) ||
  '  WHERE COALESCE(O.INACTIV,0) = 0 '                                                                       || CHR(13) ||
  '  ) PRET '                                              || CHR(13) ||
  '    INNER JOIN INTRARI I ON I.CODINTR = PRET.CODINTR '  || CHR(13) ||
  '    LEFT JOIN NPART FURN ON FURN.CODPART = I.PARTENER ' || CHR(13) ||
  '    LEFT JOIN NGEST S    ON S.CODGEST = I.CODGESTPROD ' || CHR(13) ||
  '  WHERE ROWNR = 1 '                                     || CHR(13) ||
  'UNION ALL '                                                                                            || CHR(13) ||
  'SELECT CODOBIECT, PRETACH, NULL DATAPRET, NULL DEN_PART, ''MED'' SURSA, 0 CANT, 0 CODPART, 0 CODGEST ' || CHR(13) ||
  'FROM ( '                                                                                               || CHR(13) ||
  '  SELECT NS.CODOBIECT, '                                                                               || CHR(13) ||
  '         SUM(NS.CANTNIR * (COALESCE(NS.PRET,0) - COALESCE(NS.ADAOS,0)))/(case when SUM(NS.CANTNIR)=0 then 1 else SUM(NS.CANTNIR) end) PRETACH ' || CHR(13) ||
  '  FROM NIRSTOC NS '                                                                                 || CHR(13) ||
  '       INNER JOIN NIR     N ON NS.CODNIR   = N.CODNIR'                                              || CHR(13) ||
  '       INNER JOIN NARTOBJ O ON O.CodObiect = NS.CodObiect'                                          || CHR(13) ||
  '       INNER JOIN NGEST   G ON N.GEST = G.CodGest ' || coalesce(vCond_Subunit_G,'') || ' '          || CHR(13) ||
  '  WHERE TIPNIR IN (1,2,3,4,5,6,7,8,9) AND OPERAT = 1 AND ANULAT = 0 AND COALESCE(O.INACTIV,0) = 0 ' || CHR(13) ||
  '  GROUP BY NS.CODOBIECT '                                                                           || CHR(13) ||
  '  ) A_PG';
  EXECUTE sSelect;

  sSelect := '
  SELECT
    NAO.DENUMIRE, NUM.DEN_UM, PA.PRETACH, PA.CANT, PAM.PRETACH,
    CASE
      WHEN COALESCE(SR.Cant, 0) + COALESCE(CF.RESTA,0) - COALESCE(CC.RESTA,0) - COALESCE(CSERV.RESTA,0) + COALESCE(CSIN.RESTA,0) - COALESCE(CSIES.RESTA,0) - COALESCE(CG.RESTA,0) + COALESCE(CIIN.RESTA,0) - COALESCE(CIIES.RESTA,0) &gt; 0 then 0
      ELSE -(COALESCE(SR.Cant, 0) + COALESCE(CF.RESTA,0) - COALESCE(CC.RESTA,0) - COALESCE(CSERV.RESTA,0) + COALESCE(CSIN.RESTA,0) - COALESCE(CSIES.RESTA,0) - COALESCE(CG.RESTA,0) + COALESCE(CIIN.RESTA,0) - COALESCE(CIIES.RESTA,0))
    END CANT,
    CASE
      WHEN COALESCE(SR.Cant, 0) + COALESCE(CF.RESTA,0) - COALESCE(CC.RESTA,0) - COALESCE(CSERV.RESTA,0) + COALESCE(CSIN.RESTA,0) - COALESCE(CG.RESTA,0) - COALESCE(CSIES.RESTA,0) + COALESCE(CIIN.RESTA,0) - COALESCE(CIIES.RESTA,0) &gt; 0 then 0
      ELSE -(COALESCE(SR.Cant, 0) + COALESCE(CF.RESTA,0) - COALESCE(CC.RESTA,0) - COALESCE(CSERV.RESTA,0) + COALESCE(CSIN.RESTA,0) - COALESCE(CSIES.RESTA,0) - COALESCE(CG.RESTA,0) + COALESCE(CIIN.RESTA,0) - COALESCE(CIIES.RESTA,0)) * COALESCE(PA.PRETACH, 0)
    END VAL,
    PA.SURSA, PA.DATAPRET, PA.DEN_PART FURN' || coalesce(sColMinMax,'') || ', COALESCE(SR.CANT,0),
    COALESCE(CF.CANTC   ,0), COALESCE(CF.CANTA   ,0), COALESCE(CF.RESTA   ,0),
    COALESCE(CC.CANTC   ,0), COALESCE(CC.CANTA   ,0), COALESCE(CC.RESTA   ,0),
    COALESCE(CSERV.CANTC,0), COALESCE(CSERV.CANTA,0), COALESCE(CSERV.RESTA,0),
    COALESCE(CSIN.CANTC ,0), COALESCE(CSIN.CANTA ,0), COALESCE(CSIN.RESTA ,0),
    COALESCE(CSIES.CANTC,0), COALESCE(CSIES.CANTA,0), COALESCE(CSIES.RESTA,0),
    COALESCE(CG.CANTC   ,0), COALESCE(CG.CANTA   ,0), COALESCE(CG.RESTA   ,0),
    COALESCE(CIIN.CANTC ,0), COALESCE(CIIN.CANTA ,0), COALESCE(CIIN.RESTA ,0),
    COALESCE(CIIES.CANTC,0), COALESCE(CIIES.CANTA,0), COALESCE(CIIES.RESTA,0),
    NAO.CODEXTERN, NAO.CODINTERN, PROD.DEN_PART, SREZ.REZERVAT, COALESCE(CCMat.RestA,0), COALESCE(AST.CANTC,0) ' || gUserAlias || '
  FROM NARTOBJ NAO
    INNER JOIN NART NA             ON NA.CODARTICOL = NAO.CODARTICOL
    INNER JOIN NUM                 ON NUM.CODUM     = NA.UM
    LEFT JOIN PRETM PM             ON PM.CODOBIECT  = NAO.CODOBIECT     AND PM.SUBUNITATEA    = '||GETSUBUNITATE()::varchar||' AND PM.IMPLICIT = 1
    LEFT JOIN NARTIMPLICITE ARTIMP ON ARTIMP.CODARTICOL = NA.CODARTICOL AND ARTIMP.CODSUBUNIT = '||GETSUBUNITATE()::varchar||'
    LEFT JOIN NGEST GIMP           ON GIMP.CODGEST    = ARTIMP.GESTIMPLICITA
    ' || sStocMinMaxJoin || '
    LEFT JOIN TMP_STOCREAL SR      ON SR.CODOBIECT    = NAO.CODOBIECT
    LEFT JOIN TMP_STOCREZ SREZ     ON SRez.CODOBIECT  = NAO.CODOBIECT
    LEFT JOIN TMP_CMD CF           ON CF.CODOBIECT    = NAO.CODOBIECT AND CF.TIP     = ''CF''    AND CF.USERID    = ' || coalesce(vUserId::varchar,'') || '
    LEFT JOIN TMP_CMD CC           ON CC.CODOBIECT    = NAO.CODOBIECT AND CC.TIP     = ''CC''    AND CC.USERID    = ' || coalesce(vUserId::varchar,'') || '
    LEFT JOIN TMP_CMD CSERV        ON CSERV.CODOBIECT = NAO.CODOBIECT AND CSERV.TIP  = ''CSERV'' AND CSERV.USERID = ' || coalesce(vUserId::varchar,'') || '
    LEFT JOIN TMP_CMD CSIN         ON CSIN.CODOBIECT  = NAO.CODOBIECT AND CSIN.TIP   = ''CSIN''  AND CSIN.USERID  = ' || coalesce(vUserId::varchar,'') || '
    LEFT JOIN TMP_CMD CSIES        ON CSIES.CODOBIECT = NAO.CODOBIECT AND CSIES.TIP  = ''CSIES'' AND CSIES.USERID = ' || coalesce(vUserId::varchar,'') || '
    LEFT JOIN TMP_CMD CG           ON CG.CODOBIECT    = NAO.CODOBIECT AND CG.TIP     = ''CG''    AND CG.USERID    = ' || coalesce(vUserId::varchar,'') || '
    LEFT JOIN TMP_CMD CIIN         ON CIIN.CODOBIECT  = NAO.CODOBIECT AND CIIN.TIP   = ''CIIN''  AND CIIN.USERID  = ' || coalesce(vUserId::varchar,'') || '
    LEFT JOIN TMP_CMD CIIES        ON CIIES.CODOBIECT = NAO.CODOBIECT AND CIIES.TIP  = ''CIIES'' AND CIIES.USERID = ' || coalesce(vUserId::varchar,'') || '
    LEFT JOIN TMP_CMD CCMAT        ON CCMAT.CODOBIECT = NAO.CODOBIECT AND CCMAT.TIP  = ''CCMAT'' AND CCMAT.USERID = ' || coalesce(vUserId::varchar,'') || '
    LEFT JOIN TMP_CMDTL AST        ON NAO.CODOBIECT   = AST.CODOBIECT AND AST.USERID = ' || coalesce(vUserId::varchar,'') || '
    LEFT JOIN NPART PROD           ON PROD.CODPART    = NAO.CODPRODUCATOR
    LEFT JOIN TMP_PRETACH PA       ON PA.CODOBIECT    = NAO.CODOBIECT AND PA.SURSA   = ''STOC''
    LEFT JOIN NPART FURNP          ON FURNP.CODPART   = PA.CODPART
    LEFT JOIN NGEST FURNG          ON FURNG.CODGEST   = PA.CODGEST
    LEFT JOIN TMP_PRETACH PAM      ON PAM.CODOBIECT   = NAO.CODOBIECT AND PAM.SURSA = ''MED''
    LEFT JOIN NCLASEA CLSA         ON CLSA.CODCLASEA  = NA.CLASA' || gSuplJoins || coalesce(sWhere,'');

  EXECUTE 'DROP INDEX IF EXISTS TMP_PRETACH_idx';
  EXECUTE 'CREATE INDEX TMP_PRETACH_idx ON TMP_PRETACH(CODOBIECT,SURSA)';

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

  DELETE FROM TMP_CMD   WHERE USERID = vUserId;
  DELETE FROM TMP_CMDTL WHERE USERID = vUserId;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz3_processlist</obj_name>
  <obj_hashval>220292ba998f28bb9964787780cb94ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz3_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSelect         varchar := '';
  vDataStart         date;
  vDataFin         date;
    vDataStartAux         DATE;
    vDataFinAux           DATE;
  sAux           varchar := '';
  sFiltru         varchar := '';
  sColMinMax         varchar := ', coalesce(NAOS.STOCMIN,0), coalesce(NAOS.STOCMED,0), coalesce(NAOS.STOCMAX,0)';
  sTransf         varchar := '';
  vCond_Subunit_C     varchar := '';
  vCond_Subunit_CS     varchar := '';
  vCond_Subunit_G     varchar := '';
  vUserID         numeric;
  gSuplCols           VARCHAR := 'NARTOBJ NAO, NART NA, NUM NUM, NPART PROD, NCLASEA CA';
   gUserFields         VARCHAR := '';
  gUserAlias          VARCHAR := '';
  gNullAlias          VARCHAR := '';
  gSuplJoins          VARCHAR := '';
    vAnPrec               numeric;
    vLunaPrec             numeric;
BEGIN
  --Florin 01.03.2023 - sinc. Oracle
  --Laura 01.11.2021 - sinc Oracle (01.11.2021)
  --Laura 01.10.2021 - sinc Oracle (30.09.2021)
  --Laura 29.09.2021 - sinc Oracle (27.09.2021)
  --Adina 14.07.2021 - sinc.Oracle din 14.07.2021
  --Adina 20.04.2021 - sinc.Oracle
  --Adina 05.04.2021 - alstart,alstop
  --Adina 01 septembrie 2020
  vUserId      := COALESCE(current_setting('PKG_GLOBALS.USERID', true)::numeric, 0);
  vCond_Subunit_C  := COALESCE(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'');
  vCond_Subunit_CS := COALESCE(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C', 'SubunitSursa',NULL,NULL),'');
  vCond_Subunit_G  := COALESCE(PKG_LIST_BASE_UTILS_COND_SUBUNIT('G', 'CODSUBUNIT'  ,NULL,NULL),'');

  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_NAPROVIZ3.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
    gNullAlias  := coalesce(gNullAlias,'') ;
    gSuplJoins  := coalesce(gSuplJoins,'') ;
    gSuplCols   := coalesce(gSuplCols,'')  ;

  IF  getSUBUNITATE() = 1 THEN
    sColMinMax := ', coalesce(NAO.STOCMIN,0), coalesce(NAO.STOCMED,0), coalesce(NAO.STOCMAX,0)';
  END IF;

  vDataStart := to_date(current_setting('PKG_LIST_SELECTGESTART.vDataStart', true),'dd.mm.yyyy');
  vDataFin    := to_date(current_setting('PKG_LIST_SELECTGESTART.vDataFin'  , true),'dd.mm.yyyy');

  DELETE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'GESTCODCMD';

  sFiltru := '';
  IF  NOT current_setting('PKG_LIST_SELECTGESTART.vAllGest', true)::boolean THEN
    sFiltru := '
        AND C1.GESTACT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'')';
  END IF;

  IF  NOT current_setting('PKG_LIST_SELECTGESTART.vAllArt', true)::boolean THEN
    sFiltru := sFiltru || '
        AND C1.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')';
  END IF;

  sSelect :=
  'INSERT INTO tmp_manevra_liste(valoare, filtru)
    SELECT DISTINCT C1.GESTACT, ''GESTCODCMD''
    FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
    WHERE coalesce(C.INCHISA, 0) = 0 AND C.DATADOC &lt;= ''' || coalesce(vDataFin::varchar,'') || '''
    AND C.Operat = 1 AND coalesce(C.Anulat, 0) &lt;&gt; 1 AND C.TipDoc = 18 ' || coalesce(vCond_Subunit_C,'') || '
    AND C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || '''' || sFiltru;
  EXECUTE sSelect;

  DELETE FROM tmp_stocreal;

  sFiltru := '';
  IF  NOT current_setting('PKG_LIST_SELECTGESTART.vAllGest', true)::boolean THEN
    sFiltru := '
        AND n.gest::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'')';
    sTransf := ', 12, 13';
  END IF;

  IF  NOT current_setting('PKG_LIST_SELECTGESTART.vAllArt', true)::boolean THEN
    sFiltru := sFiltru || '
        AND NS.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')';
  END IF;

  SELECT  NEWAN, newLuna INTO vAnPrec, vLunaPrec from pkg_globals_Calculeaza_Luna_Precedenta(Extract(Year from vDataStart)::numeric, Extract(Month from vDataStart)::numeric, vAnPrec, vLunaPrec);
  PERFORM pkg_globals_SetLunaTemp(Extract(Year from vDataStart)::numeric, Extract(Month from vDataStart)::numeric);
  PERFORM pkg_globals_SetLunaPrecedenta(vAnPrec, vLunaPrec);
  PERFORM PKG_LIST_SELFISAMAG_setAllParams(NULL, NULL, TO_CHAR(vDataStart, 'DD.MM.YYYY'), 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);

  sSelect :=
  'INSERT INTO tmp_stocreal(codobiect,cant,tip) ' || '
  SELECT NS.CODOBIECT, SUM(V.REST) CANT, ''INIT''
  FROM V_STOC_INI_NECESAR2 V
    INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = V.CODNIRSTOC
    INNER JOIN nir     n  ON n.codnir      = ns.codnir
    INNER JOIN ngest   g  ON g.codgest     = n.gest ' || coalesce(vCond_Subunit_G,'') || '
  WHERE V.rest &lt;&gt; 0 ' || sFiltru || '
  GROUP BY ns.codobiect';
  EXECUTE sSelect;

  sFiltru := '';
  IF  NOT current_setting('PKG_LIST_SELECTGESTART.vAllArt', true)::boolean THEN
    sFiltru := sFiltru || '
        AND NS.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')';
  END IF;

  sSelect :=
  'INSERT INTO tmp_stocreal(codobiect,cant,tip) ' || '
  SELECT NS.CODOBIECT, SUM(NSE.REST) CANT, ''BLOCAT''
  FROM NIRSER NSE
    INNER JOIN NIRSTOC NS ON NSE.CODNIRSTOC = NS.CODNIRSTOC
    INNER JOIN NIR        ON NIR.CODNIR     = NS.CODNIR
  WHERE NSE.STARE = 4
    AND NIR.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''GESTCODCMD'')' || sFiltru || '
  GROUP BY NS.CODOBIECT';
  EXECUTE sSelect;

  DELETE FROM tmp_miscari;

  sFiltru := '';
  IF  NOT current_setting('PKG_LIST_SELECTGESTART.vAllGest', true)::boolean THEN
    sFiltru := '
          AND n.gest::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'')';
  END IF;

  IF  NOT current_setting('PKG_LIST_SELECTGESTART.vAllArt', true)::boolean THEN
    sFiltru := sFiltru || '
        AND NS.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')';
  END IF;

  sSelect :=
  'INSERT INTO tmp_miscari(codobiect,cantintr,canties)
  SELECT codobiect, sum(cantintr) cantintr, sum(canties) canties
  FROM (
    SELECT ns.codobiect,
      CASE WHEN n.tipnir IN (1, 2, 3, 4, 5, 6, 7' || sTransf || ') THEN ns.cantfurn ELSE 0 END cantintr,
      CASE WHEN n.tipnir IN (19, 20, 21, 22, 23, 24, 25) THEN -ns.cantfurn ELSE 0 END canties
    FROM nir n
      INNER JOIN ngest   g  ON g.codgest   = n.gest ' || coalesce(vCond_Subunit_G,'') || '
      INNER JOIN nirstoc ns ON ns.codnir   = n.codnir
      INNER JOIN ioart1  io ON io.codioart = ns.codioart AND ' || coalesce(getAnLunaLucru()::varchar,'') || ' BETWEEN io.ALStart and io.ALStop
    WHERE n.tipnir IN (1, 2, 3, 4, 5, 6, 7, 19, 20, 21, 22, 23, 24, 25' || sTransf || ')
      AND io.mg &lt;&gt; 5
      AND n.operat = 1 AND n.anulat = 0
      AND n.datanir BETWEEN ''' || coalesce(vDataStart::varchar,'') || ''' AND ''' || coalesce(vDataFin::varchar,'') || '''' || sFiltru || '
    UNION ALL
    SELECT ns.codobiect,
      CASE WHEN l.tiplivr IN (1, 2, 3, 4, 5, 6, 7) THEN -l1.cant WHEN l.tiplivr = 15 THEN l1.cant ELSE 0 END cantintr,
      CASE WHEN l.tiplivr IN (14, 16, 19, 20, 21, 22, 23, 24, 25' || sTransf || ') THEN l1.cant ELSE 0 END canties
    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 ' || coalesce(vCond_Subunit_G,'') || '
      INNER JOIN ioart1  io ON io.codioart   = ns.codioart AND ' || coalesce(getAnLunaLucru()::varchar,'') || ' BETWEEN io.ALStart and io.ALStop
    WHERE l.tiplivr IN (1, 2, 3, 4, 5, 6, 7, 14, 15, 16, 19, 20, 21, 23, 24' || sTransf || ')
      AND io.mg &lt;&gt; 5
      AND l.operat = 1 AND l.anulat = 0
      AND l.datalivr BETWEEN ''' || coalesce(vDataStart::varchar,'') || ''' AND ''' || coalesce(vDataFin::varchar,'') || '''' || sFiltru || ') A_PG
  GROUP BY codobiect';
  EXECUTE sSelect;
  DELETE FROM tmp_cmd WHERE USERID = VUSERID;

  if current_setting('PKG_LIST_SELECTGESTART.vAnaliza', true)::numeric &gt; 0 then
    sSelect :=
    'INSERT INTO tmp_cmd(codobiect,resta,tip,userid)
    SELECT codobiect, sum(cant), ''VC'','||coalesce(vUserId::varchar,'')||'
    FROM (
      SELECT ns.codobiect,
           l1.cant
      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 '||coalesce(vCond_Subunit_G,'')||'
        INNER JOIN ioart1  io ON io.codioart   = ns.codioart AND '||coalesce(getAnLunaLucru()::varchar,'')||' BETWEEN io.ALStart and io.ALStop
      WHERE l.tiplivr IN (16, 19, 20, 21, 23, 24)
        AND io.mg &lt;&gt; 5
        AND l.operat = 1 AND l.anulat = 0
        AND l.datalivr BETWEEN '''||coalesce(vDataStart::varchar,'')||''' AND '''||coalesce(vDataFin::varchar,'')||''''||sFiltru||') A_PG
    GROUP BY codobiect';
    EXECUTE sSelect;
    vDataStartAux := vDataStart - 7;
    vDataFinAux   := vDataFin - 7;
    sSelect :=
    'INSERT INTO tmp_cmd(codobiect,resta,tip,userid)
    SELECT codobiect, sum(cant), ''VM1'','||coalesce(vUserId::varchar,'')||'
    FROM (
      SELECT ns.codobiect,
            l1.cant
      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 '||coalesce(vCond_Subunit_G,'')||'
        INNER JOIN ioart1  io ON io.codioart   = ns.codioart AND '||coalesce(getAnLunaLucru()::varchar,'')||' BETWEEN io.ALStart and io.ALStop
      WHERE l.tiplivr IN (16, 19, 20, 21, 23, 24)
        AND io.mg &lt;&gt; 5
        AND l.operat = 1 AND l.anulat = 0
        AND l.datalivr BETWEEN '''||coalesce(vDataStartAux::varchar, '')||''' AND '''||coalesce(vDataFinAux::varchar,'')||''''|| sFiltru||') A_PG
    GROUP BY codobiect';
    EXECUTE sSelect;
    vDataStartAux := vDataStartAux - 7;
    vDataFinAux   := vDataFinAux - 7;
    sSelect :=
    'INSERT INTO tmp_cmd(codobiect,resta,tip,userid)
    SELECT codobiect, sum(cant), ''VM2'','||coalesce (vUserId::varchar,'')||'
    FROM (
      SELECT ns.codobiect,
            l1.cant
      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 '||coalesce(vCond_Subunit_G,'')||'
        INNER JOIN ioart1  io ON io.codioart   = ns.codioart AND '||coalesce(getAnLunaLucru()::varchar,'')||' BETWEEN io.ALStart and io.ALStop
      WHERE l.tiplivr IN (16, 19, 20, 21, 23, 24)
        AND io.mg &lt;&gt; 5
        AND l.operat = 1 AND l.anulat = 0
        AND l.datalivr BETWEEN '''||coalesce(vDataStartAux::varchar,'')||''' AND '''||coalesce(vDataFinAux::varchar,'')||''''|| sFiltru||') A_PG
    GROUP BY codobiect';
    EXECUTE sSelect;
    vDataStartAux := vDataStartAux - 7;
    vDataFinAux   := vDataFinAux - 7;
    sSelect :=
    'INSERT INTO tmp_cmd(codobiect,resta,tip,userid)
    SELECT codobiect, sum(cant), ''VM3'','||coalesce(vUserId::varchar,'')||'
    FROM (
      SELECT ns.codobiect,
           l1.cant
      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 '||coalesce(vCond_Subunit_G,'')||'
        INNER JOIN ioart1  io ON io.codioart   = ns.codioart AND '||coalesce(getAnLunaLucru()::varchar,'')||' BETWEEN io.ALStart and io.ALStop
      WHERE l.tiplivr IN (16, 19, 20, 21, 23, 24)
        AND io.mg &lt;&gt; 5
        AND l.operat = 1 AND l.anulat = 0
        AND l.datalivr BETWEEN '''||coalesce(vDataStartAux::varchar,'')||''' AND '''||coalesce(vDataFinAux::varchar,'')||''''|| sFiltru||') A_PG
    GROUP BY codobiect';
    EXECUTE sSelect;
    vDataStartAux := vDataStartAux - 7;
    vDataFinAux   := vDataFinAux - 7;
   --
    sSelect :=
    'INSERT INTO tmp_cmd(codobiect,resta,tip,userid)
    SELECT codobiect, sum(cant), ''VM4'','||coalesce(vUserId::varchar,'')||'
    FROM (
      SELECT ns.codobiect,
           l1.cant
      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 '||coalesce(vCond_Subunit_G,'')||'
        INNER JOIN ioart1  io ON io.codioart   = ns.codioart AND '||coalesce(getAnLunaLucru()::varchar,'')||' BETWEEN io.ALStart and io.ALStop
      WHERE l.tiplivr IN (16, 19, 20, 21, 22, 23, 24)
        AND io.mg &lt;&gt; 5
        AND l.operat = 1 AND l.anulat = 0
        AND l.datalivr BETWEEN '''||coalesce(vDataStartAux::varchar,'')||''' AND '''||coalesce(vDataFinAux::varchar,'')||''''|| sFiltru||') A_PG
    GROUP BY codobiect';
    EXECUTE sSelect;
   --
    sSelect :=
    'INSERT INTO tmp_cmd(codobiect,resta,tip,userid)
    SELECT codobiect, count(codlocatie), ''LOC'','||coalesce(vUserId::varchar,'')||'
    FROM (
      SELECT DISTINCT ns.codobiect, I.CODLOCATIE
      FROM livr l
    INNER JOIN IESIRI  I ON L.CODIES      = I.CODIES
        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 '||coalesce(vCond_Subunit_G,'')||'
        INNER JOIN ioart1  io ON io.codioart   = ns.codioart AND '||coalesce(getAnLunaLucru()::varchar,'')||' BETWEEN io.ALStart and io.ALStop
      WHERE l.tiplivr IN (16, 19, 20, 21, 23, 24)
        AND io.mg &lt;&gt; 5
        AND l.operat = 1 AND l.anulat = 0
        AND l.datalivr BETWEEN '''||coalesce(vDataStartAux::varchar,'')||''' AND '''||coalesce(vDataFinAux::varchar,'')||''''|| sFiltru||') A_PG
    GROUP BY codobiect';
    EXECUTE sSelect;
    vDataStartAux := (SELECT iso_week_to_date.WME_RESULT FROM iso_week_to_date(NULL, getANLUCRU() - 1, current_setting('PKG_LIST_SELECTGESTART.vSaptamana', true)::numeric)) + 7;
    vDataFinAux   := vDataStartAux + 6;
    sSelect :=
    'INSERT INTO tmp_cmd(codobiect,resta,tip,userid)
    SELECT codobiect, sum(cant), ''VP1'','||coalesce(vUserId::varchar,'')||'
    FROM (
      SELECT ns.codobiect,
           l1.cant
      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 '||coalesce(vCond_Subunit_G,'')||'
        INNER JOIN ioart1  io ON io.codioart   = ns.codioart AND '||coalesce(getAnLunaLucru()::varchar,'')||' BETWEEN io.ALStart and io.ALStop
      WHERE l.tiplivr IN (16, 19, 20, 21, 23, 24)
        AND io.mg &lt;&gt; 5
        AND l.operat = 1 AND l.anulat = 0
        AND l.datalivr BETWEEN '''||coalesce(vDataStartAux::varchar,'')||''' AND '''||coalesce(vDataFinAux::varchar,'')||''''||sFiltru||') A_PG
    GROUP BY codobiect';
    EXECUTE sSelect;
    vDataStartAux := vDataStartAux + 7;
    vDataFinAux   := vDataFinAux + 7;
    sSelect :=
    'INSERT INTO tmp_cmd(codobiect,resta,tip,userid)
    SELECT codobiect, sum(cant), ''VP2'','||coalesce(vUserId::varchar,'')||'
    FROM (
      SELECT ns.codobiect,
           l1.cant
      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 '||coalesce(vCond_Subunit_G, '')||'
        INNER JOIN ioart1  io ON io.codioart   = ns.codioart AND '||coalesce(getAnLunaLucru()::varchar,'')||' BETWEEN io.ALStart and io.ALStop
      WHERE l.tiplivr IN (16, 19, 20, 21, 23, 24)
        AND io.mg &lt;&gt; 5
        AND l.operat = 1 AND l.anulat = 0
        AND l.datalivr BETWEEN '''||coalesce(vDataStartAux::varchar,'')||''' AND '''||coalesce(vDataFinAux::varchar,'')||''''||sFiltru||') A_PG
    GROUP BY codobiect';
    EXECUTE sSelect;
    vDataStartAux := vDataStartAux + 7;
    vDataFinAux   := vDataFinAux + 7;
    sSelect :=
    'INSERT INTO tmp_cmd(codobiect,resta,tip,userid)
    SELECT codobiect, sum(cant), ''VP3'','||coalesce(vUserId::varchar,'')||'
    FROM (
      SELECT ns.codobiect,
           l1.cant
      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 '||coalesce(vCond_Subunit_G,'')||'
        INNER JOIN ioart1  io ON io.codioart   = ns.codioart AND '||coalesce (getAnLunaLucru()::varchar,'')||' BETWEEN io.ALStart and io.ALStop
      WHERE l.tiplivr IN (16, 19, 20, 21, 23, 24)
        AND io.mg &lt;&gt; 5
        AND l.operat = 1 AND l.anulat = 0
        AND l.datalivr BETWEEN '''||coalesce (vDataStartAux::varchar,'')||''' AND '''||coalesce(vDataFinAux::varchar,'')||''''||sFiltru||') A_PG
    GROUP BY codobiect';
    EXECUTE sSelect;
    vDataStartAux := vDataStartAux + 7;
    vDataFinAux   := vDataFinAux + 7;
    sSelect :=
    'INSERT INTO tmp_cmd(codobiect,resta,tip,userid)
    SELECT codobiect, sum(cant), ''VP4'','||coalesce(vUserId::varchar,'')||'
    FROM (
      SELECT ns.codobiect,
           l1.cant
      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 '||coalesce(vCond_Subunit_G,'')||'
        INNER JOIN ioart1  io ON io.codioart   = ns.codioart AND '||coalesce (getAnLunaLucru()::varchar,'')||' BETWEEN io.ALStart and io.ALStop
      WHERE l.tiplivr IN (16, 19, 20, 21, 23, 24)
        AND io.mg &lt;&gt; 5
        AND l.operat = 1 AND l.anulat = 0
        AND l.datalivr BETWEEN '''||coalesce(vDataStartAux::varchar,'')||''' AND '''||coalesce (vDataFinAux::varchar,'')||''''|| sFiltru||') A_PG
    GROUP BY codobiect';
    EXECUTE sSelect;
  end if;

  sFiltru := '';
  IF  NOT current_setting('PKG_LIST_SELECTGESTART.vAllArt', true)::boolean THEN
    sFiltru := sFiltru || '
        AND C1.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')';
  END IF;

  sSelect :=
  'INSERT INTO tmp_cmd(codobiect,cantc,canta,resta,tip,userid)
  SELECT
    C1.CodObiect,
    SUM(CASE WHEN C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || ''' THEN C1.CantComandat - coalesce(STORNO.CANT,0) ELSE 0 END) CantC,
    SUM(CASE WHEN C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || ''' THEN C1.CantAcceptat - coalesce(STORNO.CANT,0) ELSE 0 END) CantA,
    SUM(C1.RestAcceptat) RestA, ''CF'',' || coalesce(vUserId::varchar,'') || '
  FROM COMANDA1 C1
    INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
    LEFT JOIN (
                SELECT SUM(L.CANT) CANT, L.CODLINIECOMANDA
                FROM CMDLIVRLINK L
                  INNER JOIN COMANDA1 C1 ON C1.CODCOMANDA1 = L.CODCOMANDA1
                  INNER JOIN COMANDA  C  ON C.CODCOMANDA   = C1.CODCOMANDA
                WHERE C.TIPDOC = 66 AND C.ANULAT &lt;&gt; 1 AND C.OPERAT = 1
                GROUP BY L.CODLINIECOMANDA
              ) STORNO ON STORNO.CODLINIECOMANDA = C1.CODCOMANDA1
  WHERE coalesce(C.INCHISA, 0) = 0 AND C.DATADOC &lt;= ''' || coalesce(vDataFin::varchar,'') || '''
    AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 8 ' || coalesce(vCond_Subunit_C,'') || '
    AND C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || '''' || sFiltru || '
  GROUP BY C1.CodObiect';
  EXECUTE sSelect;

  sSelect := 'INSERT INTO tmp_cmd(codobiect,cantc,canta,resta,tip,userid)
  SELECT
    C1.CodObiect,
    SUM(CASE WHEN C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || ''' THEN C1.CantComandat - coalesce(STORNO.CANT,0) ELSE 0 END) CantC,
    SUM(CASE WHEN C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || ''' THEN C1.CantAcceptat - coalesce(STORNO.CANT,0) ELSE 0 END) CantA,
    SUM(C1.RestAcceptat) RestA, ''CC'',' || coalesce(vUserId::varchar,'') || '
  FROM COMANDA1 C1
    INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
    LEFT  JOIN (
                SELECT SUM(L.CANT) CANT, L.CODLINIECOMANDA
                FROM CMDLIVRLINK L
                  INNER JOIN COMANDA1 C1 ON C1.CODCOMANDA1 = L.CODCOMANDA1
                  INNER JOIN COMANDA  C  ON C.CODCOMANDA   = C1.CODCOMANDA
                WHERE C.TIPDOC = 65 AND C.ANULAT &lt;&gt; 1 AND C.OPERAT = 1
                GROUP BY L.CODLINIECOMANDA
              ) STORNO ON STORNO.CODLINIECOMANDA = C1.CODCOMANDA1
  WHERE coalesce(C.INCHISA, 0) = 0 AND C.DATADOC &lt;= ''' || coalesce(vDataFin::varchar,'') || '''
    AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 18 ' || coalesce(vCond_Subunit_C,'') || '
    AND COALESCE(C.DISPLIVRARE,0) = 0 AND C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || '''' || sFiltru || '
  GROUP BY C1.CodObiect';
  EXECUTE sSelect;

  sSelect := 'INSERT INTO tmp_cmd(codobiect,cantc,canta,resta,tip,userid)
  SELECT
    C1.CodObiect,
    SUM(CASE WHEN C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || ''' THEN C1.CantComandat - coalesce(STORNO.CANT,0) ELSE 0 END) CantC,
    SUM(CASE WHEN C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || ''' THEN C1.CantAcceptat - coalesce(STORNO.CANT,0) ELSE 0 END) CantA,
    SUM(C1.RestAcceptat) RestA, ''CSERV'',' || coalesce(vUserId::varchar,'') || '
  FROM COMANDA1 C1
    INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
    LEFT  JOIN (
                SELECT SUM(L.CANT) CANT, L.CODLINIECOMANDA
                FROM CMDLIVRLINK L
                  INNER JOIN COMANDA1 C1 ON C1.CODCOMANDA1 = L.CODCOMANDA1
                  INNER JOIN COMANDA  C  ON C.CODCOMANDA   = C1.CODCOMANDA
                WHERE C.TIPDOC = 65 AND C.ANULAT &lt;&gt; 1 AND C.OPERAT = 1
                GROUP BY L.CODLINIECOMANDA
              ) STORNO ON STORNO.CODLINIECOMANDA = C1.CODCOMANDA1
  WHERE coalesce(C.INCHISA, 0) = 0 AND C.DATADOC &lt;= ''' || coalesce(vDataFin::varchar,'') || '''
    AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 92 ' || coalesce(vCond_Subunit_C,'') || '
    AND COALESCE(C.DISPLIVRARE,0) = 0 AND C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || '''' || sFiltru || '
  GROUP BY C1.CodObiect';
  EXECUTE sSelect;

  sSelect := 'INSERT INTO tmp_cmd(codobiect,cantc,canta,resta,tip,userid)
  SELECT
    C1.CodObiect,
    SUM(CASE WHEN C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || ''' THEN C1.CantComandat ELSE 0 END) CantC,
    SUM(CASE WHEN C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || ''' THEN C1.CantAcceptat ELSE 0 END) CantA,
    SUM(C1.RestAcceptat) RestA, ''CSIN'',' || coalesce(vUserId::varchar,'') || '
  FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
  WHERE coalesce(C.INCHISA, 0) = 0 AND C.DATADOC &lt;= ''' || coalesce(vDataFin::varchar,'') || '''
    AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 44 ' || coalesce(vCond_Subunit_C,'') || '
    AND C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || '''' || sFiltru || '
  GROUP BY C1.CodObiect';
  EXECUTE sSelect;

  sSelect :=
  'INSERT INTO tmp_cmd(codobiect,cantc,canta,resta,tip,userid)
  SELECT
    C1.CodObiect,
    SUM(CASE WHEN C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || ''' THEN C1.CantComandat ELSE 0 END) CantC,
    SUM(CASE WHEN C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || ''' THEN C1.CantAcceptat ELSE 0 END) CantA,
    SUM(C1.RestAcceptat) RestA, ''CSIES'',' || coalesce(vUserId::varchar,'') || '
  FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
  WHERE coalesce(C.INCHISA, 0) = 0 AND C.DATADOC &lt;= ''' || coalesce(vDataFin::varchar,'') || '''
    AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 44 ' || coalesce(vCond_Subunit_CS,'') || '
    AND C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || '''' || sFiltru || '
  GROUP BY C1.CodObiect';
  EXECUTE sSelect;

  sFiltru := '';
  IF  NOT current_setting('PKG_LIST_SELECTGESTART.vAllGest', true)::boolean THEN
    sFiltru := '
        AND C.CodGest::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'')';
  END IF;

  IF  NOT current_setting('PKG_LIST_SELECTGESTART.vAllArt', true)::boolean THEN
    sFiltru := coalesce(sFiltru,'') || '
        AND C1.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')';
  END IF;

  sSelect :=
  'INSERT INTO tmp_cmd(codobiect,cantc,canta,resta,tip,userid)
  SELECT
    C1.CodObiect,
    SUM(CASE WHEN C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || ''' THEN C1.CantComandat ELSE 0 END) CantC,
    SUM(CASE WHEN C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || ''' THEN C1.CantAcceptat ELSE 0 END) CantA,
    SUM(C1.RestAcceptat) RestA, ''CG'',' || coalesce(vUserId::varchar,'') || '
  FROM COMANDA1 C1
    INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
    INNER JOIN NGEST   G ON C.CodGest     = G.CodGest
  WHERE coalesce(C.INCHISA, 0) = 0 AND C.DATADOC &lt;= ''' || coalesce(vDataFin::varchar,'') || '''
    AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 43 ' || coalesce(vCond_Subunit_C,'') || '
    AND C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || '''
    AND coalesce(G.Tip,0) = 1' || sFiltru || '
  GROUP BY C1.CodObiect';
  EXECUTE sSelect;

  sSelect := 'INSERT INTO tmp_cmd(codobiect,cantc,canta,resta,tip,userid)
  SELECT
    CMDMAT.CodObiect,
    SUM(CASE WHEN C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || ''' THEN CMDMAT.Cant ELSE 0 END) CantC,
    SUM(CASE WHEN C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || ''' THEN CMDMAT.Cant ELSE 0 END) CantA,
    SUM(CMDMAT.Rest) RestA, ''CIIN'',' || coalesce(vUserId::varchar,'') || '
  FROM CMDPRODMAT CMDMAT
    INNER JOIN COMANDA1 C1 ON CMDMAT.CodComanda1 = C1.CodComanda1
    INNER JOIN COMANDA  C  ON C1.CodComanda      = C.CodComanda
  WHERE coalesce(C.INCHISA, 0) = 0 AND C.DATADOC &lt;= ''' || coalesce(vDataFin::varchar,'') || '''
    AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 53 ' || coalesce(vCond_Subunit_C,'') || '
    AND C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || '''
    AND ((C1.Consum = 1 AND CMDMAT.Tip &lt;&gt; 1) OR (C1.Consum = 2 AND CMDMAT.Tip = 2))
  GROUP BY CMDMAT.CodObiect';
  EXECUTE sSelect;

  sFiltru := '';
  IF  NOT current_setting('PKG_LIST_SELECTGESTART.vAllArt', true)::boolean THEN
    sFiltru := sFiltru || '
        AND CMDMAT.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')';
  END IF;

  sSelect :=
  'INSERT INTO tmp_cmd(codobiect,cantc,canta,resta,tip,userid)
  SELECT
    CMDMAT.CodObiect,
    SUM(CASE WHEN C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || ''' THEN CMDMAT.Cant ELSE 0 END) CantC,
    SUM(CASE WHEN C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || ''' THEN CMDMAT.Cant ELSE 0 END) CantA,
    SUM(CMDMAT.Rest) RestA, ''CIIES'',' || coalesce(vUserId::varchar,'') || '
  FROM CMDPRODMAT CMDMAT
    INNER JOIN COMANDA1 C1 ON CMDMAT.CodComanda1 = C1.CodComanda1
    INNER JOIN COMANDA  C  ON C1.CodComanda      = C.CodComanda
  WHERE coalesce(C.INCHISA, 0) = 0 AND C.DATADOC &lt;= ''' || coalesce(vDataFin::varchar,'') || '''
    AND C.Operat = 1 AND C.Anulat = 0 ' || coalesce(vCond_Subunit_C,'') || '
    AND C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || '''
    AND ((C1.Consum = 1 AND CMDMAT.Tip = 1) OR (C1.Consum = 2 AND CMDMAT.Tip &lt;&gt; 2))' || sFiltru || '
  GROUP BY CMDMAT.CodObiect';
  EXECUTE sSelect;

  sAux := '
    WHERE ';
  sFiltru := '';
  IF  NOT current_setting('PKG_LIST_SELECTGESTART.vAllArt', true)::boolean THEN
    sFiltru := sAux || 'NAO.CODOBIECT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')';
    sAux := '
        AND ';
  END IF;

  sSelect :=
  'INSERT INTO ' || tmpName || '(
    Articol, UM, Clasa, Prod, StocMIN, StocMED, StocMAX,
    StocIni, CantIntr, CantIes, StocFin,
    CantC_CF, CantA_CF, RestA_CF,
    CantC_CC, CantA_CC, RestA_CC,
    CantC_CSERV, CantA_CSERV, RestA_CSERV,
    CantC_CSIn, CantA_CSIn, RestA_CSIn,
    CantC_CSIes, CantA_CSIes, RestA_CSIes,
    CantC_CG, CantA_CG, RestA_CG,
    CantC_CIIn, CantA_CIIn, RestA_CIIn,
    CantC_CIIes, CantA_CIIes, RestA_CIIes,
    StocEst,
    Necesar, GESTCMD, STOCGESTCMD,
  VanzS, VanzSM1, VanzSM2, VanzSM3, VanzSM4,
  VanzSP1, VanzSP2, VanzSP3, VanzSP4, SediiVanz ' || gUserFields || ')
  WITH GESTCMD AS (
    SELECT C1.CodObiect, string_agg(DISTINCT G.DEN_GEST,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' order by G.DEN_GEST) GEST
    FROM COMANDA1 C1
      INNER JOIN COMANDA C ON C1.CodComanda          = C.CodComanda
      LEFT  JOIN NGEST   G ON coalesce(C1.GESTACT,0) = coalesce(G.CODGEST,0)
    WHERE coalesce(C.INCHISA, 0) = 0 AND C.DATADOC &lt;= ''' || coalesce(vDataFin::varchar,'') || '''
      AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 18 ' || coalesce(vCond_Subunit_C,'') || '
      AND C.DATADOC &gt;= ''' || coalesce(vDataStart::varchar,'') || '''
    GROUP BY C1.CodObiect)
  SELECT
    NAO.DENUMIRE, NUM.DEN_UM, CA.DEN_CLASEA, PROD.DEN_PART' || coalesce(sColMinMax,'') || ',
    coalesce(SI.CANT,0)    , coalesce(M.CANTINTR,0) , coalesce(M.CANTIES,0), coalesce(SI.CANT,0) + coalesce(M.CANTINTR,0) - coalesce(M.CANTIES,0),
    coalesce(CF.CANTC,0)   , coalesce(CF.CANTA,0)   , coalesce(CF.RESTA,0),
    coalesce(CC.CANTC,0)   , coalesce(CC.CANTA,0)   , coalesce(CC.RESTA,0),
    coalesce(CSERV.CANTC,0), coalesce(CSERV.CANTA,0), coalesce(CSERV.RESTA,0),
    coalesce(CSIN.CANTC,0) , coalesce(CSIN.CANTA,0) , coalesce(CSIN.RESTA,0),
    coalesce(CSIES.CANTC,0), coalesce(CSIES.CANTA,0), coalesce(CSIES.RESTA,0),
    coalesce(CG.CANTC,0)   , coalesce(CG.CANTA,0)   , coalesce(CG.RESTA,0),
    coalesce(CIIN.CANTC,0) , coalesce(CIIN.CANTA,0) , coalesce(CIIN.RESTA,0),
    coalesce(CIIES.CANTC,0), coalesce(CIIES.CANTA,0), coalesce(CIIES.RESTA,0),
    CASE
      WHEN coalesce(SI.CANT,0) + coalesce(M.CANTINTR,0) - coalesce(M.CANTIES,0) - coalesce(CG.RESTA,0) + coalesce(CF.RESTA,0) - coalesce(CC.RESTA,0) - coalesce(CSERV.RESTA,0) + coalesce(CSIN.RESTA,0) - coalesce(CSIES.RESTA,0) + coalesce(CIIN.RESTA,0) - coalesce(CIIES.RESTA,0) &lt; 0 THEN 0
      ELSE coalesce(SI.CANT,0) + coalesce(M.CANTINTR,0) - coalesce(M.CANTIES,0) - coalesce(CG.RESTA,0) + coalesce(CF.RESTA,0) - coalesce(CC.RESTA,0) - coalesce(CSERV.RESTA,0) + coalesce(CSIN.RESTA,0) - coalesce(CSIES.RESTA,0) + coalesce(CIIN.RESTA,0) - coalesce(CIIES.RESTA,0)
    END,
    CASE
      WHEN coalesce(SI.CANT,0) + coalesce(M.CANTINTR,0) - coalesce(M.CANTIES,0) - coalesce(CG.RESTA,0) + coalesce(CF.RESTA,0) - coalesce(CC.RESTA,0) - coalesce(CSERV.RESTA,0) + coalesce(CSIN.RESTA,0) - coalesce(CSIES.RESTA,0) + coalesce(CIIN.RESTA,0) - coalesce(CIIES.RESTA,0) &gt; 0 THEN 0
      ELSE coalesce(SI.CANT,0) + coalesce(M.CANTINTR,0) - coalesce(M.CANTIES,0) - coalesce(CG.RESTA,0) + coalesce(CF.RESTA,0) - coalesce(CC.RESTA,0) - coalesce(CSERV.RESTA,0) + coalesce(CSIN.RESTA,0) - coalesce(CSIES.RESTA,0) + coalesce(CIIN.RESTA,0) - coalesce(CIIES.RESTA,0)
    END * -1, GESTCMD.GEST, coalesce(STOCBLOCAT.CANT,0), VC.RESTA, VM1.RESTA, VM2.RESTA, VM3.RESTA, VM4.RESTA,
  VP1.RESTA, VP2.RESTA, VP3.RESTA, VP4.RESTA, SV.RESTA ' || gUserAlias || '
  FROM NARTOBJ NAO
    INNER JOIN NART           NA         ON NA.CODARTICOL        = NAO.CODARTICOL
    INNER JOIN NUM                       ON NUM.CODUM            = NA.UM
    LEFT  JOIN NARTOBJSUBUNIT NAOS       ON NAO.CODOBIECT        = NAOS.CODOBIECT
                                            and (NAOS.codgest is null or NAOS.codgest = 0)
                                            AND NAOS.SUBUNITATE = ' || coalesce(getSUBUNITATE()::varchar,'') || '
    LEFT  JOIN NPART          PROD       ON PROD.CODPART         = NAO.CODPRODUCATOR
    LEFT  JOIN NCLASEA        CA         ON CA.CODCLASEA         = NA.CLASA
    LEFT  JOIN TMP_STOCREAL   SI         ON SI.CODOBIECT         = NAO.CODOBIECT AND SI.TIP = ''INIT''
    LEFT  JOIN TMP_MISCARI    M          ON M.CODOBIECT          = NAO.CODOBIECT
    LEFT  JOIN TMP_CMD        CF         ON CF.CODOBIECT         = NAO.CODOBIECT AND CF.TIP    = ''CF''    AND CF.USERID    = ' || coalesce(vUserId::varchar,'') || '
    LEFT  JOIN TMP_CMD        CC         ON CC.CODOBIECT         = NAO.CODOBIECT AND CC.TIP    = ''CC''    AND CC.USERID    = ' || coalesce(vUserId::varchar,'') || '
    LEFT  JOIN TMP_CMD        CSERV      ON CSERV.CODOBIECT      = NAO.CODOBIECT AND CSERV.TIP = ''CSERV'' AND CSERV.USERID = ' || coalesce(vUserId::varchar,'') || '
    LEFT  JOIN TMP_CMD        CSIN       ON CSIN.CODOBIECT       = NAO.CODOBIECT AND CSIN.TIP  = ''CSIN''  AND CSIN.USERID  = ' || coalesce(vUserId::varchar,'') || '
    LEFT  JOIN TMP_CMD        CSIES      ON CSIES.CODOBIECT      = NAO.CODOBIECT AND CSIES.TIP = ''CSIES'' AND CSIES.USERID = ' || coalesce(vUserId::varchar,'') || '
    LEFT  JOIN TMP_CMD        CG         ON CG.CODOBIECT         = NAO.CODOBIECT AND CG.TIP    = ''CG''    AND CG.USERID    = ' || coalesce(vUserId::varchar,'') || '
    LEFT  JOIN TMP_CMD        CIIN       ON CIIN.CODOBIECT       = NAO.CODOBIECT AND CIIN.TIP  = ''CIIN''  AND CIIN.USERID  = ' || coalesce(vUserId::varchar,'') || '
    LEFT  JOIN TMP_CMD        CIIES      ON CIIES.CODOBIECT      = NAO.CODOBIECT AND CIIES.TIP = ''CIIES'' AND CIIES.USERID = ' || coalesce(vUserId::varchar,'') || '
  LEFT JOIN TMP_CMD         VC         ON VC.CODOBIECT         = NAO.CODOBIECT AND VC.TIP     = ''VC''    AND VC.USERID    = ' ||coalesce(vUserId::varchar,'')||'
    LEFT JOIN TMP_CMD         VM1        ON VM1.CODOBIECT        = NAO.CODOBIECT AND VM1.TIP   = ''VM1''   AND VM1.USERID   = ' ||coalesce(vUserId::varchar,'')||'
    LEFT JOIN TMP_CMD         VM2        ON VM2.CODOBIECT        = NAO.CODOBIECT AND VM2.TIP   = ''VM2''   AND VM2.USERID   = ' ||coalesce(vUserId::varchar,'')||'
    LEFT JOIN TMP_CMD         VM3        ON VM3.CODOBIECT        = NAO.CODOBIECT AND VM3.TIP   = ''VM3''   AND VM3.USERID   = ' ||coalesce(vUserId::varchar,'')||'
    LEFT JOIN TMP_CMD         VM4        ON VM4.CODOBIECT        = NAO.CODOBIECT AND VM4.TIP   = ''VM4''   AND VM4.USERID   = ' ||coalesce(vUserId::varchar,'')||'
    LEFT JOIN TMP_CMD         VP1        ON VP1.CODOBIECT        = NAO.CODOBIECT AND VP1.TIP   = ''VP1''   AND VP1.USERID   = ' ||coalesce(vUserId::varchar,'')||'
    LEFT JOIN TMP_CMD         VP2        ON VP2.CODOBIECT        = NAO.CODOBIECT AND VP2.TIP   = ''VP2''   AND VP2.USERID   = ' ||coalesce(vUserId::varchar,'')||'
    LEFT JOIN TMP_CMD         VP3        ON VP3.CODOBIECT        = NAO.CODOBIECT AND VP3.TIP   = ''VP3''   AND VP3.USERID   = ' ||coalesce(vUserId::varchar,'')||'
    LEFT JOIN TMP_CMD         VP4        ON VP4.CODOBIECT        = NAO.CODOBIECT AND VP4.TIP   = ''VP4''   AND VP4.USERID   = ' ||coalesce(vUserId::varchar,'')||'
    LEFT JOIN TMP_CMD         SV         ON SV.CODOBIECT         = NAO.CODOBIECT AND  SV.TIP   = ''LOC''   AND SV.USERID    = ' ||coalesce(vUserId::varchar,'')||'
  LEFT  JOIN GESTCMD                   ON GESTCMD.CODOBIECT    = NAO.CODOBIECT
    LEFT  JOIN TMP_STOCREAL   STOCBLOCAT ON STOCBLOCAT.CODOBIECT = NAO.CODOBIECT AND STOCBLOCAT.TIP = ''BLOCAT'' ' || gSuplJoins || sFiltru;

  PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
  DELETE FROM tmp_cmd WHERE USERID = VUSERID;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz4_processlist</obj_name>
  <obj_hashval>047dd756c901dfa67d143cf1f353ae16</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz4_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert          VARCHAR := '';
  sSelect          VARCHAR := '';
  sColMinMax       VARCHAR := ', NAOS.STOCMIN, NAOS.STOCMED, NAOS.STOCMAX';
  vToateGest       BOOLEAN;
  vToateIOArt      BOOLEAN;
  vCuNecesarZero   BOOLEAN;
  vAux             VARCHAR := '';
  vSelStocReal     VARCHAR := '';
  vCateGest        NUMERIC        := 0;
  vCateLGest       NUMERIC        := 0;
  vProductie       BOOLEAN;
  vCondIntrari     VARCHAR := '';
  vCondIesiri      VARCHAR := '';
  vCondIesiriD    VARCHAR := '';
  vNrZileStocMed   NUMERIC;
  vDataRef         VARCHAR := '';
  vStocAux         VARCHAR := '';

  vGestString     varchar := '';
  vIOArtString     varchar:= '';
  sJoinExt         VARCHAR := '';
  vCond_Subunit_C varchar := '';
  vCond_Subunit_G varchar := '';
  vSetimana       NUMERIC;
  vUserID         NUMERIC;
  vAn             NUMERIC;
  vPrevAn         NUMERIC;
  vPrevSetimana   NUMERIC;
  vNextAn         NUMERIC;
  vNextSetimana   NUMERIC;
  vCount           NUMERIC;
  vPPrevAn         NUMERIC;
  vPPrevSetimana   NUMERIC;
  vCondLansat     varchar := '';
  vCampLansat     varchar := '';
   gSuplCols       VARCHAR := 'NARTOBJ NAO, NARTOBJSUBUNIT NAOS, NART NA, NUM NUM, NPART PROD, NCLASEA CLSA, NCLASEAS CLSAS, NARTCLI NACLI, NPART PART, NUM1 NUM1';
   gUserFields     VARCHAR := '';
  gUserAlias      VARCHAR := '';
  gNullAlias      VARCHAR := '';
  gSuplJoins      VARCHAR := '';
  vScadNeop       numeric(1);
  sFieldNeop      varchar(100);
  sJoinNeop       varchar(200);
BEGIN
  --Florin 30.10.2025 - sinc. Oracle
  --Florin 28.10.2022 - sinc. Oracle
  --Adina 20.04.2021 - sinc.Oracle
  --Adina 01 septembrie 2020
  vUserId         := COALESCE(current_setting('PKG_GLOBALS.USERID', true)::numeric, 0);
  vCond_Subunit_C := COALESCE(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'');
  vCond_Subunit_G := COALESCE(PKG_LIST_BASE_UTILS_COND_SUBUNIT('G', 'CODSUBUNIT',NULL,NULL),'');

  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_NAPROVIZ4.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  vToateGest     := (current_setting('PKG_LIST_SELECTSCAD.vToateGest'  , true)::NUMERIC = 1)::boolean;
  vToateIOArt    := (current_setting('PKG_LIST_SELECTSCAD.vToateGest'  , true)::NUMERIC = 1)::boolean;
  vCuNecesarZero := (current_setting('PKG_LIST_SELECTSCAD.vExtra1'     , true)::NUMERIC = 1)::boolean;
  vProductie     := (current_setting('PKG_LIST_SELECTSCAD.vCentralizat', true)::numeric = 1)::boolean;
  vSetimana      := current_setting('PKG_LIST_SELECTSCAD.vSetimana'    , true)::numeric;
  vAn            := getANLUCRU();

  vStocAux := '0';
  IF current_setting('PKG_LIST_SELECTSCAD.vTipNecesar', true)::numeric = 1 THEN
    vStocAux := ' coalesce(NAOS.STOCMIN,0) ';
  ELSE
    IF  current_setting('PKG_LIST_SELECTSCAD.vTipNecesar', true)::numeric = 2 THEN
      vStocAux := ' coalesce(NAOS.STOCMED,0) ';
    ELSE
      IF current_setting('PKG_LIST_SELECTSCAD.vTipNecesar', true)::numeric = 3 THEN
        vStocAux := ' coalesce(NAOS.STOCMAX,0) ';
      END IF;
    END IF;
  END IF;

  vCondLansat := ' AND C1.RestLansat &gt; 0 ';
  vCampLansat := 'RestA';
  if (current_setting('PKG_LIST_SELECTSCAD.vExtra3', true)::NUMERIC = 1) then
    vCondLansat := '';
    vCampLansat := 'CantA';
  end if;

  IF GETSUBUNITATE() = 1 THEN
    sColMinMax  := ', NAO.STOCMIN, NAO.STOCMED, NAO.STOCMAX';
  END IF;

  vSelStocReal := '
      SELECT NS.CODOBIECT, SUM(case when n.operat = 0 then ns.cantnir else ns.rest end) CANT
      FROM NIRSTOC NS
        INNER JOIN NARTOBJ OBJ ON OBJ.CODOBIECT = NS.CODOBIECT
        INNER JOIN NIR     N   ON NS.CODNIR     = N.CODNIR
        INNER JOIN NGEST   G   ON G.CodGest     = N.GEST '||vCond_Subunit_G||'
        INNER JOIN (SELECT A.CODARTICOL, COUNT(O.CODOBIECT) NR
                    FROM NART A
                         INNER JOIN NARTOBJ O ON O.CODARTICOL = A.CODARTICOL
                    GROUP BY A.CODARTICOL) NROBJ ON OBJ.CODARTICOL = NROBJ.CODARTICOL
      WHERE (NROBJ.NR = 1 OR (NROBJ.NR &gt; 1 AND EXISTS (SELECT ATR.CODOBIECT FROM NATROBJ ATR WHERE ATR.CODOBIECT = OBJ.CODOBIECT)))
        and ((ns.rest &lt;&gt; 0 and n.operat = 1) or (ns.rest = 0 and n.operat = 0 and n.tipnir = 12)) and g.tip &lt;&gt; 4 ';
  vAux := '
      AND ';
  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
      vSelStocReal := vSelStocReal || vAux||' EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND coalesce(VALOARE,'''') = coalesce(N.GEST::varchar,'''')) ';
    elsif vCateGest = 0 then
      vSelStocReal := vSelStocReal || vAux||' EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND coalesce(VALOARE,'''') = coalesce(NS.CODLOCATIE::varchar,'''')) ';
    else
      vSelStocReal := vSelStocReal || vAux||' (EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND coalesce(VALOARE,'''') = coalesce(N.GEST::varchar,'''')) OR '||
                                   'EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND coalesce(VALOARE,'''') = coalesce(NS.CODLOCATIE::varchar,''''))) ';
    end if;
    vAux := '
        AND';
    vGestString := ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND coalesce(VALOARE,'''') = coalesce(N.GEST::varchar,'''')) ';
  end if;

  if NOT vToateIOArt then
    vSelStocReal := vSelStocReal || vAux||' EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND coalesce(VALOARE,'''') = coalesce(NS.CODIOART::varchar,'''') ) ';
    vIOArtString := ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND coalesce(VALOARE,'''') = coalesce(NS.CODIOART::varchar,'''') ) ';
  end if;
  vSelStocReal := vSelStocReal ||'
      GROUP BY NS.CODOBIECT';

  vSelStocReal := vSelStocReal||'
      UNION ALL
      SELECT OBJ.CODOBIECT, SUM(case when n.operat = 0 then ns.cantnir else ns.rest end) CANT
      FROM NARTOBJ OBJ
        INNER JOIN NARTOBJ O  ON OBJ.CODARTICOL = O.CODARTICOL
        INNER JOIN NIRSTOC NS ON O.CODOBIECT    = NS.CODOBIECT
        INNER JOIN NIR     N  ON NS.CODNIR      = N.CODNIR
        INNER JOIN NGEST   G  ON G.CodGest      = N.GEST '||vCond_Subunit_G||'
        INNER JOIN (SELECT A.CODARTICOL, COUNT(O.CODOBIECT) NR
                    FROM NART A
                         INNER JOIN NARTOBJ O ON O.CODARTICOL = A.CODARTICOL
                    GROUP BY A.CODARTICOL) NROBJ ON OBJ.CODARTICOL = NROBJ.CODARTICOL
      WHERE (NROBJ.NR &gt; 1 AND NOT EXISTS (SELECT ATR.CODOBIECT FROM NATROBJ ATR WHERE ATR.CODOBIECT = OBJ.CODOBIECT))
        and ((ns.rest &lt;&gt; 0 and n.operat = 1) or (ns.rest = 0 and n.operat = 0 and n.tipnir = 12)) and g.tip &lt;&gt; 4 ';
  vAux := '
      AND ';
  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
      vSelStocReal := vSelStocReal || vAux||' EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND coalesce(VALOARE,'''') = coalesce(N.GEST::varchar,'''')) ';
    elsif vCateGest = 0 then
      vSelStocReal := vSelStocReal || vAux||' EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND coalesce(VALOARE,'''') = coalesce(NS.CODLOCATIE::varchar,'''')) ';
    else
      vSelStocReal := vSelStocReal || vAux||' (EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND coalesce(VALOARE,'''') = coalesce(N.GEST::varchar,'''')) OR '||
                                   'EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND coalesce(VALOARE,'''') = coalesce(NS.CODLOCATIE::varchar,''''))) ';
    end if;
    vAux := '
        AND';
    vGestString := ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND coalesce(VALOARE,'''') = coalesce(N.GEST::varchar,'''')) ';
  end if;

  if NOT vToateIOArt then
    vSelStocReal := vSelStocReal || vAux||' EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND coalesce(VALOARE,'''') = coalesce(NS.CODIOART::varchar,'''') ) ';
    vIOArtString := ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND coalesce(VALOARE,'''') = coalesce(NS.CODIOART::varchar,'''') ) ';
  end if;
  vSelStocReal := vSelStocReal ||'
      GROUP BY OBJ.CODOBIECT';

  vDataRef := to_char(Last_Day(To_Date('01.'||to_char(GetLUNALUCRU(), '99')||'.'||to_char(GetANLUCRU(), '9999'),'dd.mm.yyyy')), 'DD.MM.YYYY');

  if current_setting('PKG_LIST_SELECTSCAD.vMod', true)::numeric = 0 then
    vDataRef      := current_setting('PKG_LIST_SELECTSCAD.vDataScad', true);
    vCondIntrari  := ' AND C1.TERMEN &lt;       to_date('''||current_setting('PKG_LIST_SELECTSCAD.vDataIni', true)||''', ''DD.MM.YYYY'') ';
    vCondIesiri   := ' AND C1.TERMEN BETWEEN to_date('''||current_setting('PKG_LIST_SELECTSCAD.vDataIni', true)||''', ''DD.MM.YYYY'') AND to_date('''||current_setting('PKG_LIST_SELECTSCAD.vDataScad', true)||''', ''DD.MM.YYYY'') ';
    vCondIesiriD  := ' AND C1.TERMEN &lt;=      to_date('''||current_setting('PKG_LIST_SELECTSCAD.vDataIni', true)||''', ''DD.MM.YYYY'') ';
  else
    vDataRef      := current_setting('PKG_LIST_SELECTSCAD.vDataScad', true);
    vCondIntrari  := ' AND C.DATADOC &lt;       to_date('''||current_setting('PKG_LIST_SELECTSCAD.vDataIni', true)||''', ''DD.MM.YYYY'') ';
    vCondIesiri   := ' AND C.DATADOC BETWEEN to_date('''||current_setting('PKG_LIST_SELECTSCAD.vDataIni', true)||''', ''DD.MM.YYYY'') AND to_date('''||current_setting('PKG_LIST_SELECTSCAD.vDataScad', true)||''', ''DD.MM.YYYY'') ';
    vCondIesiriD  := ' AND C.DATADOC &lt;=      to_date('''||current_setting('PKG_LIST_SELECTSCAD.vDataIni', true)||''', ''DD.MM.YYYY'') ';
  end if;

  vNrZileStocMed := COALESCE(fnc_GetValConstanta('NrZileStocMed', getANLUCRU(), getLUNALUCRU())::numeric,0);
  SELECT fnc_GetValConstanta('ScadAcceptatNeopFurn', getANLUCRU(), getLUNALUCRU()) INTO vScadNeop;

  sInsert:=
  'INSERT INTO '||tmpName||'(
    Articol,
    UM,
    PretAch,
    Cant,
    Val,
    Sursa,
    Data,
    Furn,
    StocMIN,
    StocMED,
    StocMAX,
    StocReal,
    CantC_CF,
    CantA_CF,
    RestA_CF,
    CantC_CFT,
    CantA_CFT,
    RestA_CFT,
    CantC_CC,
    CantA_CC,
    RestA_CC,
    CantC_CIIes,
    CantA_CIIes,
    RestA_CIIes,
    CantC_CCPANALA,
    CantA_CCPANALA,
    RestA_CCPANALA,
    CantC_CIIesLA,
    CantA_CIIesLA,
    RestA_CIIesLA,
    CodExtern,
    CodIntern,
    Producator,
    Rezervat,
    ZileStocMED,
    PartOf,
    UMOf,
    CantMinOf,
    ZileLOf,
    ZileLNom,
    RestA_CF_Next,
    CantC_CCPER,
    CantA_CCPER,
    RestA_CCPER,
    CantC_CIPER,
    CantA_CIPER,
    RestA_CIPER,
    CantC_CFPER,
    CantA_CFPER,
    RestA_CFPER,
    CantC_PlanifPrev,
    CantA_PlanifPrev,
    RestA_PlanifPrev,
    BC_PlanifPrev,
    CantC_PlanifPer,
    CantA_PlanifPer,
    RestA_PlanifPer,
    BC_PlanifPer,
    CantC_PlanifNext,
    CantA_PlanifNext,
    RestA_PlanifNext,
    BC_PlanifNext,
    CodObiect,
    Saptamana '||gUserFields||')';

  DELETE FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'MATERIALE';
  INSERT INTO TMP_MANEVRA_LISTE(VALOARE, FILTRU)
  SELECT DISTINCT CODOBIECT, 'MATERIALE' FROM NARTOBJ WHERE coalesce(PRODUSPROPRIU,0) = 0;

  DELETE FROM TMP_STOCREAL;
  DELETE from TMP_CMD WHERE USERID = vUserId;

  sFieldNeop := '';
  sJoinNeop  := '';
  if vScadNeop = 1 then
    sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT C1.CodObiect, 0 CantC, 0 CantA, SUM(l.cant) RestA, ''NEOP'', '||coalesce(vUserId, 0)||' '||
    'FROM COMANDA1 C1 '||
    'INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda '||
    'INNER JOIN INTRLINK L ON C1.CodComanda1 = L.CodLinieComanda '||
    'INNER JOIN INTRARI1 I1 ON I1.CodINTR1 = L.CodINTR1 '||
    'INNER JOIN INTRARI I ON I.CodINTR = I1.CodINTR '||
    'WHERE Nvl(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 8 AND C1.RestAcceptat &gt; 0 '||coalesce(vCond_Subunit_C, '')||
    '      AND COALESCE(I.OPERAT,0) = 0 '||
    'GROUP BY C1.CodObiect';
    EXECUTE sSelect;
    sFieldNeop := ' + coalesce(neop.resta,0) ';
    sJoinNeop  := chr(13)||'  LEFT JOIN TMP_CMD NEOP ON NEOP.CODOBIECT = C1.CODOBIECT AND NEOP.TIP = ''NEOP'' AND NEOP.USERID = '||vUserId||CHR(13);
  end if;

  sSelect := 'insert into tmp_stocreal(codobiect,cant) '||vSelStocReal;
  execute sSelect;

  DELETE FROM TMP_STOCREZ;
  sSelect := 'insert into tmp_stocrez(codobiect,rezervat) '||'SELECT NS.CODOBIECT, SUM(R.REST) REZERVAT '||
      'FROM REZERVATS R '||
        'INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = R.CODNIRSTOC '||
        'INNER JOIN NIR     N  ON NS.CODNIR     = N.CODNIR '||
        'INNER JOIN NGEST   G  ON N.GEST        = G.CodGest '||vCond_Subunit_G||' '||
      'WHERE coalesce(R.REST,0) &gt; 0 '||
      vGestString||
      vIOArtString||
      'GROUP BY NS.CODOBIECT';
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT C1.CodObiect, SUM(C1.CantComandat) CantC, SUM(C1.CantAcceptat) CantA, SUM(C1.RestAcceptat'||sFieldNeop||') RestA, ''CF'', '||vUserId||' '||
    'FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda '||sJoinNeop||
    'WHERE Nvl(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 8 AND C1.RestAcceptat &gt; 0 '||vCond_Subunit_C||vCondIntrari||' '||
    'GROUP BY C1.CodObiect';
  EXECUTE sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,resta,tip, userid) '||
    'SELECT C1.CodObiect, SUM(C1.RestAcceptat'||coalesce(sFieldNeop, '')||') RestA, ''CFN'', '||coalesce(vUserId, 0)||' '||
    'FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda '||coalesce(sJoinNeop, '')||
    'WHERE Nvl(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 8 AND C1.RestAcceptat &gt; 0 '||coalesce(vCond_Subunit_C, '')||' '||
    '     AND C1.TERMEN BETWEEN
     add_days(to_date(''' || current_setting('PKG_LIST_SELECTSCAD.vDATASCAD', true) || ''', ''dd.mm.yyyy''), 1) AND
     add_days(to_date(''' || current_setting('PKG_LIST_SELECTSCAD.vDATASCAD', true) || ''', ''dd.mm.yyyy''), 7) GROUP BY C1.CodObiect';
  EXECUTE sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT C1.CodObiect, SUM(C1.CantComandat) CantC, SUM(C1.CantAcceptat) CantA, SUM(C1.RestAcceptat'||coalesce(sFieldNeop, '')||') RestA, ''CFT'','||coalesce(vUserId, 0)||' '||
    'FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda '||sJoinNeop||
    'WHERE Nvl(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 8 AND C1.RestAcceptat &gt; 0 '||coalesce(vCond_Subunit_C, '')||' '||
    'GROUP BY C1.CodObiect';
  EXECUTE sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT C1.CodObiect, SUM(C1.CantComandat) CantC, SUM(C1.CantAcceptat) CantA, SUM(C1.RestAcceptat'||coalesce(sFieldNeop, '')||') RestA, ''CFPER'','||coalesce(vUserId, 0)||' '||
    'FROM COMANDA1 C1 INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda '||sJoinNeop||
    'WHERE Nvl(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 8 AND C1.RestAcceptat &gt; 0 '||coalesce(vCond_Subunit_C, '')||coalesce(vCondIesiri, '')||' '||
    'GROUP BY C1.CodObiect';
  EXECUTE sSelect;

  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT coalesce(NE.CODOBIECT,PN.CodObiect), SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantComandat else PN.Cant/PN0.Cant*C1.CantComandat end) CantC, SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantAcceptat else PN.Cant/PN0.Cant*C1.CantAcceptat end) CantA, SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.RestLansat else PN.Cant/PN0.Cant*C1.RestLansat end) RestA,
            ''CC'','||vUserId::varchar||' '||
      'FROM COMANDA C '||
        'INNER JOIN COMANDA1   C1  ON C.CodComanda    = C1.CodComanda '||
        'INNER JOIN PROIECTNOD PN  ON C1.CODPROIECT   = PN.CODPROIECT  AND PN.TIP = 3 '||
        'INNER JOIN PROIECTNOD PN0 ON C1.CODPROIECT   = PN0.CODPROIECT AND coalesce(PN0.NODORIGINAL, 0) = 0 '||
        'LEFT  JOIN NODECHIV   NE  ON C1.CODCOMANDA1  = NE.CODCOMANDA1 AND PN.CODPROIECTNOD = NE.CODPROIECTNOD '||
      'WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat  = 1              AND C.Anulat = 0 AND coalesce(C.DispLivrare, 0) = 0 AND C.TipDoc = 18 '||
        vCondLansat||' and coalesce(c1.exceptional,0) = 0 '||vCond_Subunit_C||vCondIesiri||' '||
      'GROUP BY coalesce(NE.CODOBIECT,PN.CodObiect)';
  execute sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT coalesce(NE.CODOBIECT,PN.CodObiect), SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantComandat else PN.Cant/PN0.Cant*C1.CantComandat end) CantC, SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantAcceptat else PN.Cant/PN0.Cant*C1.CantAcceptat end) CantA, SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.RestLansat else PN.Cant/PN0.Cant*C1.RestLansat end) RestA,
            ''CIIES'','||vUserId::varchar||' '||
      'FROM COMANDA C '||
        'INNER JOIN COMANDA1   C1  ON C.CodComanda   = C1.CodComanda '||
        'INNER JOIN PROIECTNOD PN  ON C1.CODPROIECT  = PN.CODPROIECT AND PN.TIP = 3 '||
        'INNER JOIN PROIECTNOD PN0 ON C1.CODPROIECT  = PN0.CODPROIECT AND coalesce(PN0.NODORIGINAL, 0) = 0 '||
        'LEFT  JOIN NODECHIV   NE  ON C1.CODCOMANDA1 = NE.CODCOMANDA1 AND PN.CODPROIECTNOD = NE.CODPROIECTNOD '||
      'WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND C.DispLivrare = 2 AND C.TipDoc = 18 '||
        vCondLansat||' and coalesce(c1.exceptional,0) = 0 '||vCond_Subunit_C||vCondIesiri||' '||
      'GROUP BY coalesce(NE.CODOBIECT,PN.CodObiect)';
  execute sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT coalesce(NE.CODOBIECT,PN.CodObiect), SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantComandat else PN.Cant/PN0.Cant*C1.CantComandat end) CantC, SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantAcceptat else PN.Cant/PN0.Cant*C1.CantAcceptat end) CantA, SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.RestLansat else PN.Cant/PN0.Cant*C1.RestLansat end) RestA,
            ''CCPANALA'','||vUserId::varchar||' '||
      'FROM COMANDA C '||
        'INNER JOIN COMANDA1   C1  ON C.CodComanda   = C1.CodComanda '||
        'INNER JOIN PROIECTNOD PN  ON C1.CODPROIECT  = PN.CODPROIECT AND PN.TIP = 3 '||
        'INNER JOIN PROIECTNOD PN0 ON C1.CODPROIECT  = PN0.CODPROIECT AND coalesce(PN0.NODORIGINAL, 0) = 0 '||
        'LEFT  JOIN NODECHIV   NE  ON C1.CODCOMANDA1 = NE.CODCOMANDA1 AND PN.CODPROIECTNOD = NE.CODPROIECTNOD '||
      'WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0  AND coalesce(C.DispLivrare, 0) = 0 AND C.TipDoc = 18 '||
        vCondLansat||' and coalesce(c1.exceptional,0) = 0 '||vCond_Subunit_C||vCondIntrari||' '||
      'GROUP BY coalesce(NE.CODOBIECT,PN.CodObiect)';
  execute sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT coalesce(NE.CODOBIECT,PN.CodObiect), SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantComandat else PN.Cant/PN0.Cant*C1.CantComandat end) CantC, SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantAcceptat else PN.Cant/PN0.Cant*C1.CantAcceptat end) CantA, SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.RestLansat else PN.Cant/PN0.Cant*C1.RestLansat end) RestA,
            ''CIIESPANALA'','||vUserId::varchar||' '||
      'FROM COMANDA C '||
        'INNER JOIN COMANDA1   C1  ON C.CodComanda   = C1.CodComanda '||
        'INNER JOIN PROIECTNOD PN  ON C1.CODPROIECT  = PN.CODPROIECT AND PN.TIP = 3 '||
        'INNER JOIN PROIECTNOD PN0 ON C1.CODPROIECT  = PN0.CODPROIECT AND coalesce(PN0.NODORIGINAL, 0) = 0 '||
        'LEFT  JOIN NODECHIV   NE  ON C1.CODCOMANDA1 = NE.CODCOMANDA1 AND PN.CODPROIECTNOD = NE.CODPROIECTNOD '||
      'WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND C.DispLivrare = 2 AND C.TipDoc = 18 '||
        vCondLansat||' and coalesce(c1.exceptional,0) = 0 '||vCond_Subunit_C||vCondIntrari||' '||
      'GROUP BY coalesce(NE.CODOBIECT,PN.CodObiect)';
  execute sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT coalesce(NE.CODOBIECT,PN.CodObiect), SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantComandat else PN.Cant/PN0.Cant*C1.CantComandat end) CantC, SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantAcceptat else PN.Cant/PN0.Cant*C1.CantAcceptat end) CantA, SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.RestLansat else PN.Cant/PN0.Cant*C1.RestLansat end) RestA,
            ''CCPER'','||vUserId::varchar||' '||
      'FROM COMANDA C '||
        'INNER JOIN COMANDA1   C1  ON C.CodComanda   = C1.CodComanda '||
        'INNER JOIN PROIECTNOD PN  ON C1.CODPROIECT  = PN.CODPROIECT AND PN.TIP = 3 '||
        'INNER JOIN PROIECTNOD PN0 ON C1.CODPROIECT  = PN0.CODPROIECT AND coalesce(PN0.NODORIGINAL, 0) = 0 '||
        'LEFT  JOIN NODECHIV   NE  ON C1.CODCOMANDA1 = NE.CODCOMANDA1 AND PN.CODPROIECTNOD = NE.CODPROIECTNOD '||
      'WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND coalesce(C.DispLivrare, 0) = 0 AND C.TipDoc = 18 '||
        vCondLansat||' and coalesce(c1.exceptional,0) = 0 '||vCond_Subunit_C||vCondIesiri||' '||
      'GROUP BY coalesce(NE.CODOBIECT,PN.CodObiect)';
  execute sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT coalesce(NE.CODOBIECT,PN.CodObiect), SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantComandat else PN.Cant/PN0.Cant*C1.CantComandat end) CantC, SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantAcceptat else PN.Cant/PN0.Cant*C1.CantAcceptat end) CantA, SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.RestLansat else PN.Cant/PN0.Cant*C1.RestLansat end) RestA,
            ''CIPER'','||vUserId::varchar||' '||
      'FROM COMANDA C '||
        'INNER JOIN COMANDA1   C1  ON C.CodComanda   = C1.CodComanda '||
        'INNER JOIN PROIECTNOD PN  ON C1.CODPROIECT  = PN.CODPROIECT AND PN.TIP = 3 '||
        'INNER JOIN PROIECTNOD PN0 ON C1.CODPROIECT  = PN0.CODPROIECT AND coalesce(PN0.NODORIGINAL, 0) = 0 '||
        'LEFT  JOIN NODECHIV   NE  ON C1.CODCOMANDA1 = NE.CODCOMANDA1 AND PN.CODPROIECTNOD = NE.CODPROIECTNOD '||
      'WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND C.DispLivrare = 2 AND C.TipDoc = 18 '||
        vCondLansat||' and coalesce(c1.exceptional,0) = 0 '||vCond_Subunit_C||vCondIesiri||' '||
      'GROUP BY coalesce(NE.CODOBIECT,PN.CodObiect)';
  execute sSelect;

  /*informatii aduse din planificari*/
  if vSetimana = 1 then
    vPrevAn := vAn - 1;
    vPrevSetimana := 53;
  else
    vPrevAn := vAn;
    vPrevSetimana := vSetimana - 1;
  end if;
  if vPrevSetimana = 1 then
    vPPrevAn := vPrevAn - 1;
    vPPrevSetimana := 53;
  else
    vPPrevAn := vPrevAn;
    vPPrevSetimana := vPrevSetimana - 1;
  end if;
  if vSetimana = 53 then
    vNextAn := vAn + 1;
    vNextSetimana := 1;
  else
    vNextAn := vAn;
    vNextSetimana := vSetimana + 1;
  end if;

  select count(*) into vCount
  from planifprod
  where ((saptamana = vSetimana      and an = vAn      and (subunitatea = GETSUBUNITATE() or GETSUBUNITATE() = 1)) or
         (saptamana = vPrevSetimana  and an = vPrevAn  and (subunitatea = GETSUBUNITATE() or GETSUBUNITATE() = 1)) or
         (saptamana = vPPrevSetimana and an = vPPrevAn and (subunitatea = GETSUBUNITATE() or GETSUBUNITATE() = 1)) or
         (saptamana = vNextSetimana  and an = vNextAn  and (subunitatea = GETSUBUNITATE() or GETSUBUNITATE() = 1))
        )
        and anulat = 0;

  if vCount &gt; 0 then
    DELETE FROM TMP_PLANIFNODZ;
    INSERT INTO TMP_PLANIFNODZ (CODRETETA, CODOBIECT, NECESAR)
    SELECT CODRETETA, CODOBIECT, SUM(NECESAR) FROM (
    SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
    FROM PLANIFNOD PNOD
         INNER JOIN PLANIFPROD1 PP1 ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
         INNER JOIN PLANIFPROD  PP  ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
    WHERE PP.An = vAn and PP.Saptamana = vSetimana 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 (PP.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
    UNION ALL
    SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
    FROM PLANIFNOD PNOD
         INNER JOIN PLANIFPROD1 PP1 ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
         INNER JOIN PLANIFPROD  PP  ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
    WHERE PP.An = vAn and PP.Saptamana = vSetimana 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 (PP.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
    UNION ALL
    SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
    FROM PLANIFNOD PNOD
         INNER JOIN PLANIFPROD1 PP1 ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
         INNER JOIN PLANIFPROD  PP  ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
    WHERE PP.An = vAn and PP.Saptamana = vSetimana 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 (PP.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
    UNION ALL
    select codreteta, codobiect, NEXTWEEK necesar from
    (SELECT L1.CODRETETA, L1.CODOBIECT, sum(coalesce(l1.nextweek,0)) nextweek
     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 = vPrevAn and l.saptamana = vPrevSetimana
           and l1.nextweek &gt; 0
           AND (L.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
     group by l1.codreteta, l1.codobiect
     ) A_PG ) B_PG
     group by codobiect, codreteta;

     sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '                            ||CHR(13)||
      'SELECT MAT.CodObiect, SUM((TMP.NECESAR - coalesce(REPORT.NEXTWEEK,0))/PC.CANT*MAT.CANT) CantC, SUM(coalesce(REPORT.NEXTWEEK,0)/PC.CANT*MAT.CANT) CantA, coalesce(LANS.STINS,0) RestA, ''PLANIFPER'','||vUserId::varchar||' '||CHR(13)||
      'FROM TMP_PLANIFNODZ TMP '                                                                          ||CHR(13)||
      '     INNER JOIN PRODCOMP PC  ON TMP.CODRETETA  = PC.CODPRODCOMP '                                  ||CHR(13)||
      '     INNER JOIN PRODMAT  MAT ON PC.CODPRODCOMP = MAT.CODPRODCOMP '                                 ||CHR(13)||
      '     LEFT JOIN ( '                                                                                 ||CHR(13)||
      '                SELECT L1.CODRETETA, L1.CODOBIECT, SUM(coalesce(L1.NEXTWEEK,0)) NEXTWEEK '         ||CHR(13)||
      '                from LANSZ1 L1 '                                                                   ||CHR(13)||
      '                     inner join LANSZ l on l.codlansz = l1.codlansz '                              ||CHR(13)||
      '                where l.operat = 1 and l.anulat = 0 and l.blocat = 0 '                             ||CHR(13)||
      '                      and l.an = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||CHR(13)||
      '                      and l1.nextweek &gt; 0 '                                                        ||CHR(13)||
      '                      AND (L.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1) '               ||CHR(13)||
      '               group by l1.codreteta, l1.codobiect '                                               ||CHR(13)||
      '               ) REPORT ON REPORT.CODRETETA = TMP.CODRETETA'                                       ||CHR(13)||
      '     LEFT JOIN (SELECT CODOBIECT, SUM(STINS) STINS FROM ( '                                        ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                         ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                              ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '           ||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_LUNI '             ||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '                  ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                           ||CHR(13)||
      '                union all '                                                                        ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                         ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                              ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '           ||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_MARTI '            ||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '                  ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                           ||CHR(13)||
      '                union all '                                                                        ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                         ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                              ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '           ||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_MIERCURI '         ||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '                  ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                           ||CHR(13)||
      '                union all '                                                                        ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                         ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                              ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '           ||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_JOI '              ||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '                  ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                           ||CHR(13)||
      '                union all '                                                                        ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                         ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                              ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '           ||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_VINERI '           ||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '                  ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                           ||CHR(13)||
      '                union all '                                                                        ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                         ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                              ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '           ||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_SAMBATA '          ||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '                  ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                           ||CHR(13)||
      '                union all '                                                                        ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                         ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                              ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '           ||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_DUMINICA '         ||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '                  ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                           ||CHR(13)||
      '                ) aa GROUP BY CODOBIECT) LANS ON LANS.CODOBIECT = MAT.CODOBIECT  '                 ||CHR(13)||
      'GROUP BY MAT.CodObiect, coalesce(LANS.STINS,0)';
      --execute sSelect;

      DELETE FROM TMP_PLANIFNODZ;
      INSERT INTO TMP_PLANIFNODZ (CODRETETA, CODOBIECT, NECESAR)
      SELECT CODRETETA, CODOBIECT, SUM(NECESAR) FROM (
      SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
      FROM PLANIFNOD PNOD
           INNER JOIN PLANIFPROD1 PP1 ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
           INNER JOIN PLANIFPROD  PP  ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
      WHERE PP.An = vPrevAn and PP.Saptamana = vPrevSetimana 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 (PP.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
      UNION ALL
      SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
      FROM PLANIFNOD PNOD
           INNER JOIN PLANIFPROD1 PP1 ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
           INNER JOIN PLANIFPROD  PP  ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
      WHERE PP.An = vPrevAn and PP.Saptamana = vPrevSetimana 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 (PP.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
      UNION ALL
      SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
      FROM PLANIFNOD PNOD
           INNER JOIN PLANIFPROD1 PP1 ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
           INNER JOIN PLANIFPROD  PP  ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
      WHERE PP.An = vPrevAn and PP.Saptamana = vPrevSetimana 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 (PP.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
      UNION ALL
    (
    select codreteta, codobiect, nextweek necesar from
    (SELECT distinct L1.CODRETETA, L1.CODOBIECT, sum(coalesce(l1.nextweek,0)) nextweek
     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 = vPPrevAn and l.saptamana = vPPrevSetimana
           and l1.nextweek &gt; 0
           AND (L.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
     group by l1.codreteta, l1.codobiect
     ) A_PG)) C_PG
     group by codobiect, codreteta;

     sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '                              ||CHR(13)||
      'SELECT MAT.CodObiect, SUM((TMP.NECESAR - coalesce(REPORT.NEXTWEEK,0))/PC.CANT*MAT.CANT) CantC, SUM(coalesce(REPORT.NEXTWEEK,0)/PC.CANT*MAT.CANT) CantA, coalesce(LANS.STINS,0) RestA, ''PLANIFPREV'','||vUserId::varchar||' '||CHR(13)||
      'FROM TMP_PLANIFNODZ TMP '                                                                            ||CHR(13)||
      '     INNER JOIN PRODCOMP PC ON TMP.CODRETETA = PC.CODPRODCOMP '                                      ||CHR(13)||
      '     INNER JOIN PRODMAT MAT ON PC.CODPRODCOMP = MAT.CODPRODCOMP '                                    ||CHR(13)||
      '     LEFT JOIN ( '                                                                                   ||CHR(13)||
      '                SELECT L1.CODRETETA, L1.CODOBIECT, SUM(coalesce(L1.NEXTWEEK,0)) NEXTWEEK '           ||CHR(13)||
      '                from LANSZ1 L1 '                                                                     ||CHR(13)||
      '                     inner join LANSZ l on l.codlansz = l1.codlansz '                                ||CHR(13)||
      '                where l.operat = 1 and l.anulat = 0 and l.blocat = 0 '                               ||CHR(13)||
      '                      and l.an = '||vPPrevAn::varchar||' and l.saptamana = '||vPPrevSetimana::varchar||CHR(13)||
      '                      and l1.nextweek &gt; 0 '                                                          ||CHR(13)||
      '                      AND (L.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1) '                 ||CHR(13)||
      '                group by l1.codreteta, l1.codobiect '                                                ||CHR(13)||
      '               ) REPORT ON REPORT.CODRETETA = TMP.CODRETETA'                                         ||CHR(13)||
      '     LEFT JOIN (SELECT CODOBIECT, SUM(STINS) STINS FROM ( '                                          ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                           ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                                ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '             ||CHR(13)||
      '                     INNER JOIN LANSZ1 L1 ON CMD.CODCOMANDA1 = L1.CODCMD1_LUNI '                     ||CHR(13)||
      '                     INNER JOIN LANSZ L ON L1.CODLANSZ = L.CODLANSZ '                                ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                             ||CHR(13)||
      '                union all '                                                                          ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                           ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                                ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '             ||CHR(13)||
      '                     INNER JOIN LANSZ1 L1 ON CMD.CODCOMANDA1 = L1.CODCMD1_MARTI '                    ||CHR(13)||
      '                     INNER JOIN LANSZ L ON L1.CODLANSZ = L.CODLANSZ '                                ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                             ||CHR(13)||
      '                union all '                                                                          ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                           ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                                ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '             ||CHR(13)||
      '                     INNER JOIN LANSZ1 L1 ON CMD.CODCOMANDA1 = L1.CODCMD1_MIERCURI '                 ||CHR(13)||
      '                     INNER JOIN LANSZ L ON L1.CODLANSZ = L.CODLANSZ '                                ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                             ||CHR(13)||
      '                union all '                                                                          ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                           ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                                ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '             ||CHR(13)||
      '                     INNER JOIN LANSZ1 L1 ON CMD.CODCOMANDA1 = L1.CODCMD1_JOI '                      ||CHR(13)||
      '                     INNER JOIN LANSZ L ON L1.CODLANSZ = L.CODLANSZ '                                ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                             ||CHR(13)||
      '                union all '                                                                          ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                           ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                                ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '             ||CHR(13)||
      '                     INNER JOIN LANSZ1 L1 ON CMD.CODCOMANDA1 = L1.CODCMD1_VINERI '                   ||CHR(13)||
      '                     INNER JOIN LANSZ L ON L1.CODLANSZ = L.CODLANSZ '                                ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                             ||CHR(13)||
      '                union all '                                                                          ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                           ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                                ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '             ||CHR(13)||
      '                     INNER JOIN LANSZ1 L1 ON CMD.CODCOMANDA1 = L1.CODCMD1_SAMBATA '                  ||CHR(13)||
      '                     INNER JOIN LANSZ L ON L1.CODLANSZ = L.CODLANSZ '                                ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                             ||CHR(13)||
      '                union all '                                                                          ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                           ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                                ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '             ||CHR(13)||
      '                     INNER JOIN LANSZ1 L1 ON CMD.CODCOMANDA1 = L1.CODCMD1_DUMINICA '                 ||CHR(13)||
      '                     INNER JOIN LANSZ L ON L1.CODLANSZ = L.CODLANSZ '                                ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                             ||CHR(13)||
      '                ) aa GROUP BY CODOBIECT) LANS ON LANS.CODOBIECT = MAT.CODOBIECT  '                   ||CHR(13)||
      'GROUP BY MAT.CodObiect,coalesce(LANS.STINS,0)';
      --execute sSelect;

      DELETE FROM TMP_PLANIFNODZ;
      INSERT INTO TMP_PLANIFNODZ (CODRETETA, CODOBIECT, NECESAR)
      SELECT CODRETETA, CODOBIECT, SUM(NECESAR) FROM (
      SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
      FROM PLANIFNOD PNOD
           INNER JOIN PLANIFPROD1 PP1 ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
           INNER JOIN PLANIFPROD  PP  ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
      WHERE PP.An = vNextAn and PP.Saptamana = vNextSetimana 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 (PP.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
      UNION ALL
      SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
      FROM PLANIFNOD PNOD
           INNER JOIN PLANIFPROD1 PP1 ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
           INNER JOIN PLANIFPROD  PP  ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
      WHERE PP.An = vNextAn and PP.Saptamana = vNextSetimana 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 (PP.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
      UNION ALL
      SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
      FROM PLANIFNOD PNOD
           INNER JOIN PLANIFPROD1 PP1 ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
           INNER JOIN PLANIFPROD  PP  ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
      WHERE PP.An = vNextAn and PP.Saptamana = vNextSetimana 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 (PP.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
      UNION ALL
    (
    select codreteta, codobiect, nextweek necesar from
    (SELECT distinct L1.CODRETETA, L1.CODOBIECT, sum(coalesce(l1.nextweek,0)) nextweek
     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 = vAn and l.saptamana = vSetimana
           and l1.nextweek &gt; 0
           AND (L.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
     group by l1.codreteta, l1.codobiect
     ) A_PG)) B_PG
     group by codobiect, codreteta;

     sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '                    ||CHR(13)||
      'SELECT MAT.CodObiect, SUM((TMP.NECESAR - coalesce(REPORT.NEXTWEEK,0))/PC.CANT*MAT.CANT) CantC, SUM(coalesce(REPORT.NEXTWEEK,0)/PC.CANT*MAT.CANT) CantA, coalesce(LANS.STINS,0) RestA, ''PLANIFNEXT'','||vUserId::varchar||' '||CHR(13)||
      'FROM TMP_PLANIFNODZ TMP '                                                                  ||CHR(13)||
      '     INNER JOIN PRODCOMP PC ON TMP.CODRETETA = PC.CODPRODCOMP '                            ||CHR(13)||
      '     INNER JOIN PRODMAT MAT ON PC.CODPRODCOMP = MAT.CODPRODCOMP '                          ||CHR(13)||
      '     LEFT JOIN ( '                                                                         ||CHR(13)||
      '                SELECT L1.CODRETETA, L1.CODOBIECT, SUM(coalesce(L1.NEXTWEEK,0)) NEXTWEEK ' ||CHR(13)||
      '                from LANSZ1 L1 '                                                           ||CHR(13)||
      '                     inner join LANSZ l on l.codlansz = l1.codlansz '                      ||CHR(13)||
      '                where l.operat = 1 and l.anulat = 0 and l.blocat = 0 '                     ||CHR(13)||
      '                      and l.an = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||CHR(13)||
      '                      and l1.nextweek &gt; 0 '                                                ||CHR(13)||
      '                      AND (L.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1) '       ||CHR(13)||
      '               group by l1.codreteta, l1.codobiect '                                       ||CHR(13)||
      '               ) REPORT ON REPORT.CODRETETA = TMP.CODRETETA'                               ||CHR(13)||
      '     LEFT JOIN (SELECT CODOBIECT, SUM(STINS) STINS FROM ( '                                ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                 ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                      ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '   ||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_LUNI '     ||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '          ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                   ||CHR(13)||
      '                union all '                                                                ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                 ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                      ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '   ||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_MARTI '    ||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '          ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                   ||CHR(13)||
      '                union all '                                                                ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                 ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                      ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '   ||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_MIERCURI ' ||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '          ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                   ||CHR(13)||
      '                union all '                                                                ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                 ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                      ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '   ||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_JOI '      ||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '          ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                   ||CHR(13)||
      '                union all '                                                                ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                 ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                      ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '   ||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_VINERI '   ||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '          ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                   ||CHR(13)||
      '                union all '                                                                ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                 ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                      ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '   ||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_SAMBATA '  ||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '          ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                   ||CHR(13)||
      '                union all '                                                                ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                 ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                      ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '   ||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_DUMINICA ' ||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '          ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                   ||CHR(13)||
      '                ) aa GROUP BY CODOBIECT) LANS ON LANS.CODOBIECT = MAT.CODOBIECT  '         ||CHR(13)||
      'GROUP BY MAT.CodObiect,coalesce(LANS.STINS,0)';
      --execute sSelect;
  end if;

  DELETE FROM TMP_PRETACH;
  sSelect := 'insert into tmp_PRETACH(CODOBIECT,PRETACH,DATAPRET,DEN_PART,SURSA) '||
    'SELECT CODOBIECT, PRETACH, DATANIR DATAPRET, DEN_PART, ''STOC'' SURSA '||
      'FROM ( '||
        'SELECT NS.CODOBIECT, '||
        'FIRST_VALUE(NS.PRET - coalesce(NS.ADAOS, 0)) OVER (PARTITION BY NS.CODOBIECT ORDER BY N.DATANIR DESC) PRETACH, '||
        'FIRST_VALUE(N.DATANIR)                       OVER (PARTITION BY NS.CODOBIECT ORDER BY N.DATANIR DESC) DATANIR, '||
        'FIRST_VALUE(N.CODINTR)                       OVER (PARTITION BY NS.CODOBIECT ORDER BY N.DATANIR DESC) CODINTR, '||
        'ROW_NUMBER()                                 OVER (PARTITION BY NS.CODOBIECT ORDER BY N.DATANIR DESC) ROWNR '   ||
        'FROM NIRSTOC NS '||
          'INNER JOIN ( '||
            'SELECT N.CODNIR, N.DATANIR, N.CODINTR, G.CODSUBUNIT '||
            'FROM NIR N '||
              'INNER JOIN NGEST G ON N.GEST = G.CodGest '||vCond_Subunit_G||' '||
            'WHERE TIPNIR IN (1,2,3,4,5,6,7,8,9) AND OPERAT = 1 AND ANULAT = 0 '||
          ') N ON N.CODNIR = NS.CODNIR '||
      ') PRET '||
        'INNER JOIN INTRARI I    ON I.CODINTR    = PRET.CODINTR '||
        'LEFT  JOIN NPART   FURN ON FURN.CODPART = I.PARTENER '||
      'WHERE ROWNR = 1';
  --execute sSelect;

  sSelect :=
  'SELECT '||
    'NAO.DENUMIRE, NUM.DEN_UM, PA.PRETACH, '||
    'CASE '||
      'WHEN   coalesce(SR.Cant, 0)-'||vStocAux||' - coalesce(SREZ.REZERVAT, 0) + coalesce(CF.RESTA,0) + coalesce(CFPER.RESTA,0) - coalesce(CC.'||vCampLansat||',0) - coalesce(CIIES.'||vCampLansat||',0) - coalesce(CCPANALA.'||vCampLansat||',0) - coalesce(CIIESPANALA.'||vCampLansat||',0) - (coalesce(PLANIFPREV.CANTC,0) - coalesce(PLANIFPREV.RESTA,0)) - (coalesce(PLANIFPER.CANTC,0) - coalesce(PLANIFPER.RESTA,0))  &gt; 0 then 0 '||
      'ELSE -(coalesce(SR.Cant, 0)-'||vStocAux||' - coalesce(SREZ.REZERVAT, 0) + coalesce(CF.RESTA,0) + coalesce(CFPER.RESTA,0) - coalesce(CC.'||vCampLansat||',0) - coalesce(CIIES.'||vCampLansat||',0) - coalesce(CCPANALA.'||vCampLansat||',0) - coalesce(CIIESPANALA.'||vCampLansat||',0) - (coalesce(PLANIFPREV.CANTC,0) - coalesce(PLANIFPREV.RESTA,0)) - (coalesce(PLANIFPER.CANTC,0) - coalesce(PLANIFPER.RESTA,0))) '||
    'END CANT, '||
    'CASE '||
      'WHEN   coalesce(SR.Cant, 0)-'||vStocAux||' + coalesce(CF.RESTA,0) + coalesce(CFPER.RESTA,0) - coalesce(CC.'||vCampLansat||',0) - coalesce(CIIES.'||vCampLansat||',0) - coalesce(CCPANALA.'||vCampLansat||',0) - coalesce(CIIESPANALA.'||vCampLansat||',0) - (coalesce(PLANIFPREV.CANTC,0) - coalesce(PLANIFPREV.RESTA,0)) - (coalesce(PLANIFPER.CANTC,0) - coalesce(PLANIFPER.RESTA,0)) &gt; 0 then 0 '||
      'ELSE -(coalesce(SR.Cant, 0)-'||vStocAux||' + coalesce(CF.RESTA,0) + coalesce(CFPER.RESTA,0) - coalesce(CC.'||vCampLansat||',0) - coalesce(CIIES.'||vCampLansat||',0) - coalesce(CCPANALA.'||vCampLansat||',0) - coalesce(CIIESPANALA.'||vCampLansat||',0) - (coalesce(PLANIFPREV.CANTC,0) - coalesce(PLANIFPREV.RESTA,0)) - (coalesce(PLANIFPER.CANTC,0) - coalesce(PLANIFPER.RESTA,0))) * coalesce(PA.PRETACH, 0) '||
    'END VAL, '||
    'PA.SURSA, PA.DATAPRET, PA.DEN_PART FURN'||sColMinMax||', coalesce(SR.CANT,0), '||
    'coalesce(CF.CANTC,0), coalesce(CF.CANTA,0), coalesce(CF.RESTA,0), '||
    'coalesce(CFT.CANTC,0), coalesce(CFT.CANTA,0), coalesce(CFT.RESTA,0), '||
    'coalesce(CC.CANTC,0), coalesce(CC.CANTA,0), coalesce(CC.RESTA,0), '||
    'coalesce(CIIES.CANTC,0), coalesce(CIIES.CANTA,0), coalesce(CIIES.RESTA,0), '||
    'coalesce(CCPANALA.CANTC,0), coalesce(CCPANALA.CANTA,0), coalesce(CCPANALA.RESTA,0), '||
    'coalesce(CIIESPANALA.CANTC,0), coalesce(CIIESPANALA.CANTA,0), coalesce(CIIESPANALA.RESTA,0), '||
    'NAO.CODEXTERN, NAO.CODINTERN, PROD.DEN_PART, coalesce(SREZ.REZERVAT, 0), coalesce(NA.NRZILESTOCMEDIU,'||vNrZileStocMed||'), '||
    'PART.DEN_PART, NUM1.DEN_UM1, OFE1.CANTMIN, OFE1.ZileL, COALESCE(NAOIMP.DURMAXAPROV,NAO.DURMAXAPROV), coalesce(CFN.RESTA,0),'||
    'coalesce(CCPER.CANTC,0), coalesce(CCPER.CANTA,0), coalesce(CCPER.RESTA,0), '||
    'coalesce(CIPER.CANTC,0), coalesce(CIPER.CANTA,0), coalesce(CIPER.RESTA,0), '||
    'coalesce(CFPER.CANTC,0), coalesce(CFPER.CANTA,0), coalesce(CFPER.RESTA,0), '||
    'coalesce(PLANIFPREV.CANTC,0), coalesce(PLANIFPREV.CANTA,0), coalesce(PLANIFPREV.CANTC,0) - coalesce(PLANIFPREV.RESTA,0), coalesce(PLANIFPREV.RESTA,0), '||
    'coalesce(PLANIFPER.CANTC,0) , coalesce(PLANIFPER.CANTA,0) , coalesce(PLANIFPER.CANTC ,0) - coalesce(PLANIFPER.RESTA ,0), coalesce(PLANIFPER.RESTA ,0), '||
    'coalesce(PLANIFNEXT.CANTC,0), coalesce(PLANIFNEXT.CANTA,0), coalesce(PLANIFNEXT.CANTC,0) - coalesce(PLANIFNEXT.RESTA,0), coalesce(PLANIFNEXT.RESTA,0), '||
    'NAO.CodObiect, '||vSetimana::varchar||' '||gUserAlias||' '||
  'FROM NARTOBJ NAO '||
    'INNER JOIN TMP_MANEVRA_LISTE MAT         ON NAO.CODOBIECT::varchar = MAT.VALOARE AND MAT.FILTRU = ''MATERIALE'' '||
    'INNER JOIN NART              NA          ON NA.CODARTICOL          = NAO.CODARTICOL '||
    'INNER JOIN NUM                           ON NUM.CODUM              = NA.UM '||
    'LEFT  JOIN NARTOBJSUBUNIT    NAOS        ON NAO.CODOBIECT          = NAOS.CODOBIECT
                                                 and ( NAOS.codgest is null or NAOS.codgest = 0)
                                                 AND NAOS.SUBUNITATE = GETSUBUNITATE() '||
    'LEFT  JOIN NARTOBJIMP        NAOIMP      ON NAO.CODOBIECT          = NAOIMP.CODOBIECT AND NAOIMP.CODSUBUNIT = GETSUBUNITATE() '||
    'LEFT  JOIN TMP_STOCREAL      SR          ON SR.CODOBIECT           = NAO.CODOBIECT '||
    'LEFT  JOIN TMP_STOCREZ       SREZ        ON SRez.CODOBIECT         = NAO.CODOBIECT '||
    'LEFT  JOIN TMP_CMD           CF          ON CF.CODOBIECT           = NAO.CODOBIECT AND CF.TIP          = ''CF''          AND CF.USERID          = '||vUserId::varchar||' '||
    'LEFT  JOIN TMP_CMD           CFN         ON CFN.CODOBIECT          = NAO.CODOBIECT AND CFN.TIP         = ''CFN''         AND CFN.USERID         = '||vUserId::varchar||' '||
    'LEFT  JOIN TMP_CMD           CFT         ON CFT.CODOBIECT          = NAO.CODOBIECT AND CFT.TIP         = ''CFT''         AND CFT.USERID         = '||vUserId::varchar||' '||
    'LEFT  JOIN TMP_CMD           CC          ON CC.CODOBIECT           = NAO.CODOBIECT AND CC.TIP          = ''CC''          AND CC.USERID          = '||vUserId::varchar||' '||
    'LEFT  JOIN TMP_CMD           CIIES       ON CIIES.CODOBIECT        = NAO.CODOBIECT AND CIIES.TIP       = ''CIIES''       AND CIIES.USERID       = '||vUserId::varchar||' '||
    'LEFT  JOIN TMP_CMD           CCPANALA    ON CCPANALA.CODOBIECT     = NAO.CODOBIECT AND CCPANALA.TIP    = ''CCPANALA''    AND CCPANALA.USERID    = '||vUserId::varchar||' '||
    'LEFT  JOIN TMP_CMD           CIIESPANALA ON CIIESPANALA.CODOBIECT  = NAO.CODOBIECT AND CIIESPANALA.TIP = ''CIIESPANALA'' AND CIIESPANALA.USERID = '||vUserId::varchar||' '||
    'LEFT  JOIN TMP_CMD           CCPER       ON CCPER.CODOBIECT        = NAO.CODOBIECT AND CCPER.TIP       = ''CCPER''       AND CCPER.USERID       = '||vUserId::varchar||' '||
    'LEFT  JOIN TMP_CMD           CIPER       ON CIPER.CODOBIECT        = NAO.CODOBIECT AND CIPER.TIP       = ''CIPER''       AND CIPER.USERID       = '||vUserId::varchar||' '||
    'LEFT  JOIN TMP_CMD           CFPER       ON CFPER.CODOBIECT        = NAO.CODOBIECT AND CFPER.TIP       = ''CFPER''       AND CFPER.USERID       = '||vUserId::varchar||' '||
    'LEFT  JOIN TMP_CMD           PLANIFPREV  ON PLANIFPREV.CODOBIECT   = NAO.CODOBIECT AND PLANIFPREV.TIP  = ''PLANIFPREV''  AND PLANIFPREV.USERID  = '||vUserId::varchar||' '||
    'LEFT  JOIN TMP_CMD           PLANIFPER   ON PLANIFPER.CODOBIECT    = NAO.CODOBIECT AND PLANIFPER.TIP   = ''PLANIFPER''   AND PLANIFPER.USERID   = '||vUserId::varchar||' '||
    'LEFT  JOIN TMP_CMD           PLANIFNEXT  ON PLANIFNEXT.CODOBIECT   = NAO.CODOBIECT AND PLANIFNEXT.TIP  = ''PLANIFNEXT''  AND PLANIFNEXT.USERID  = '||vUserId::varchar||' '||
    'LEFT  JOIN NPART             PROD        ON PROD.CODPART           = NAO.CODPRODUCATOR '                     ||
    'LEFT  JOIN TMP_PRETACH       PA          ON PA.CODOBIECT           = NAO.CODOBIECT '                         ||
    'LEFT  JOIN NCLASEA           CLSA        ON CLSA.CODCLASEA         = coalesce(NA.CLASA,0) '                  ||
    'LEFT  JOIN NCLASEAS          CLSAS       ON CLSAS.CODCLASEAS       = coalesce(NA.CLASASTATIST,0)  '          ||
    'LEFT  JOIN NARTCLI           NACLI       ON NAO.CODOBIECT          = NACLI.CODOBIECT AND NACLI.IMPLICIT = 1 '||
    'LEFT  JOIN NPART             PART        ON NACLI.CODPART          = PART.CODPART '                          ||
    'LEFT  JOIN OFERTA            OFE         ON OFE.Partener           = NACLI.CODPART AND OFE.DATASTART &lt;= Last_Day(To_Date('''||vDataRef||''',''dd.mm.yyyy'')) AND OFE.DATAEND &gt;= To_Date('''||vDataRef||''',''dd.mm.yyyy'') '||
    'LEFT  JOIN OFERTA1           OFE1        ON OFE1.CODOFERTA         = OFE.CODOFERTA AND OFE1.CODOBIECT = NAO.CODOBIECT  '||
    'LEFT  JOIN NUM1                          ON NUM1.CODUM1            = OFE1.UMSEC '||gSuplJoins||
    sJoinExt;

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

  sSelect := 'update '||tmpName||' set RestA_PlanifNext = 0 where RestA_PlanifNext &lt; 0';
  execute sSelect;
  sSelect := 'update '||tmpName||' set RestA_PlanifPrev = 0 where RestA_PlanifPrev &lt; 0';
  execute sSelect;
  sSelect := 'update '||tmpName||' set RestA_PlanifPer = 0 where RestA_PlanifPer &lt; 0';
  execute sSelect;

  IF NOT vCuNecesarZero THEN
    sSelect := 'delete from '||tmpName||' where cant = 0';
    execute sSelect;
  END IF;

  if (current_setting('PKG_LIST_SELECTSCAD.vExtra2', true)::NUMERIC = 1) then
    sSelect := 'update '||tmpName||' set PretMedAch = pkg_intrari_getpretmediuachiz(CodObiect)';
    execute sSelect;
  end if;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_neccmdcli_processlist</obj_name>
  <obj_hashval>5bc58ad474a1e6e28a8601a06602cfc4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_neccmdcli_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 15.09.2020
  gSuplCols := '';

  IF (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists (NULL,'COMANDC')) = 1 THEN
    gSuplCols := 'COMANDC CEXT';
  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_NECCMDCLI.gSuplCols',gSuplCols,false);

  sInsert := 'INSERT INTO ' || TMPNAME || '(
          NAV_CodDoc,
          NAV_TipDoc,
          CodProiectNod,
          CodArticol,
          Client,
          Produs,
          CodInternP,
          NrDoc,
          DataDoc,
          Termen,
          Material,
          UM,
          Cant,
          CantU,
          IndexP,
          CodInternM,
          MatEchiv,
          Nivel,
          ObsMat ' || coalesce (gUserFields ,'')
          || ')
      select x.NAV_CodDoc,
        x.NAV_TipDoc,
        x.CodProiectNod,
        x.codarticol,
        x.Client,
        x.Produs,
        X.CodInternP,
        x.NrDoc,
        x.DataDoc,
        x.Termen,
        x.Material,
        x.UM,
        x.Cant,
        x.CantU,
        x.indexparinte,
        x.CodInternM,
        x.MatEchiv,
        X.Nivel,
        X.ObsMat ' || coalesce (gUserAlias ,'') || '
      from (select c.codcomanda NAV_CodDoc,
                   c.tipdoc         NAV_TipDOc,
                   nod.codproiectnod,
                   ac.codarticol,
                   p.den_part     client,
                   ac.den_articol produs,
                   oc.codintern   codinternp,
                   c.nrdoc,
                   c.datadoc,
                   c1.termen,
                   om.denumire                                material,
                   um.den_um                                  UM,
                   sum (nod.cant * c1.restlansat / nod0.cant) Cant,
                   mat.cant                                   cantu,
                   nod.indexparinte,
                   om.codintern codinternm,
                   case when oech.codobiect &gt; 0 and oech.codobiect &lt;&gt; nod.codobiect then oech.denumire end  MatEchiv,
                   coalesce (nod.nivel,0) Nivel,
                   mat.Obs  ObsMat
            from (select codobiect from tmp_cmd1 where userid    = getuserid()) tmp
                  inner join comanda     c    on tmp.codobiect   = c.codcomanda
                  inner join comanda1    c1   on c1.codcomanda   = c.codcomanda
                  inner join nartobj     oc   on oc.codobiect    = c1.codobiect
                  inner join nart        ac   on ac.codarticol   = oc.codarticol
                  inner join proiectnod  nod0 on nod0.codproiect = c1.codproiect and coalesce (nod0.nodoriginal,0) = 0
                  inner join proiectnod  nod  on nod.codproiect  = c1.codproiect and coalesce (nod.codreteta,0) = 0
                  inner join nartobj     om   on om.codobiect    = nod.codobiect
                  inner join nart        am   on om.codarticol   = am.codarticol
                  inner join num         um   on um.codum        = am.um
                  inner join npart       p    on p.codpart       = c.partener
                  left join prodmat      mat  on mat.codmat      = nod.codprodmat
                  left join nodechiv     ech  on ech.codcomanda1 = c1.codcomanda1 and ech.codproiectnod = nod.codproiectnod
                  left join nartobj      oech on oech.codobiect  = ech.codobiect
            group by c.codcomanda, c.tipdoc, nod.codproiectnod, ac.codarticol, p.den_part, ac.den_articol, oc.codintern, c.nrdoc, c.datadoc, c1.termen,
                     om.denumire, um.den_um, mat.cant, nod.indexparinte, om.codintern, oech.codobiect, nod.codobiect, oech.denumire, coalesce (nod.nivel,0),mat.obs
           ) x '   || coalesce (chr (13) ,'');

  IF (SELECT PKG_LIST_STRUCT_TmpExists.WME_RESULT FROM PKG_LIST_STRUCT_TmpExists (NULL,'COMANDC')) = 1 THEN
    sInsert := coalesce (sInsert,'') || '      left join comandc cext on cext.codcomanda = x.NAV_CodDoc ' || coalesce (chr (13) ,'');
  END IF;

  sInsert := coalesce (sInsert,'') || coalesce (gSuplJoins ,'');

  PERFORM LIST_EXECUTE_IMMEDIATE (sInsert, aListID, aListVer);

  sinsert := 'DO $$
              DECLARE
                v_rec record;
              begin
                for v_rec in (select *  from ' || TMPNAME || ') loop
                  update ' || TMPNAME || '
                  set total = PKG_LIST_BASE_NECCMDCLI_getsume (codarticol,nav_coddoc,1)
                  where nav_coddoc = v_rec.nav_coddoc
                        and nav_tipdoc = v_rec.nav_tipdoc
                        and codarticol = v_rec.codarticol
                        and codproiectnod = v_rec.codproiectnod;

                  update ' || TMPNAME || '
                  set total2 = PKG_LIST_BASE_NECCMDCLI_getsume (codarticol,nav_coddoc,2)
                  where nav_coddoc = v_rec.nav_coddoc
                        and nav_tipdoc = v_rec.nav_tipdoc
                        and codarticol = v_rec.codarticol
                        and codproiectnod = v_rec.codproiectnod;

              end loop;
              end$$; ';
  EXECUTE sinsert;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_notecredit_processlist</obj_name>
  <obj_hashval>ebbb9ff1b6ae8861bcb9da581a9adfd3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notecredit_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 := '';

  sSelectT  varchar;
  sSelectV  varchar;
  sSelectC  varchar;
  sSelectP  varchar;
  sTipNC    NUMERIC;
  sFiltruNC varchar;
  sTable    varchar;
  sTable1   varchar;
  sCamp     varchar;
  sCamp1    varchar;
  sWhenObj  varchar;
  sDisc     varchar;
BEGIN
  --Adina 26.11.2020 tichet 41277
  --Bogdan 08.09.2020
  sFiltruNC := '
      AND nc.datastart &lt;=   TO_DATE('''|| coalesce (To_Char ( (SELECT PKG_LIST_ALEGPERIOADA_getDataF.WME_RESULT FROM PKG_LIST_ALEGPERIOADA_getDataF (NULL,NULL)) ,'dd.mm.yyyy') ,'')|| ''', ''dd.mm.yyyy'')
      AND nc.datastop  &gt;=   TO_DATE('''|| coalesce (To_Char ( (SELECT PKG_LIST_ALEGPERIOADA_getDataS.WME_RESULT FROM PKG_LIST_ALEGPERIOADA_getDataS (NULL,NULL)) ,'dd.mm.yyyy') ,'')|| ''', ''dd.mm.yyyy'')
      AND i.datadoc BETWEEN TO_DATE('''|| coalesce (To_Char ( (SELECT PKG_LIST_ALEGPERIOADA_getDataS.WME_RESULT FROM PKG_LIST_ALEGPERIOADA_getDataS (NULL,NULL)) ,'dd.mm.yyyy') ,'')|| ''', ''dd.mm.yyyy'')
                        AND TO_DATE('''|| coalesce (To_Char ( (SELECT PKG_LIST_ALEGPERIOADA_getDataF.WME_RESULT FROM PKG_LIST_ALEGPERIOADA_getDataF (NULL,NULL)) ,'dd.mm.yyyy') ,'')|| ''', ''dd.mm.yyyy'')';
  IF aLISTID = 253 THEN
    sTipNC  := 58;
    sTable  := 'IESIRI';
    sTable1 := 'IESIRI1';
    sCamp   := 'CODIES';
    sCamp1  := 'CODIES1';
    gSuplCols := 'notecredit nc, notecredit1 nc1, iesiri i, npart p, nartobj o, ncont c, ncont casoc,nclasedisc clsdisc';
  ELSE
    sTipNC  := 59;
    sTable  := 'INTRARI';
    sTable1 := 'INTRARI1';
    sCamp   := 'CODINTR';
    sCamp1  := 'CODINTR1';
    gSuplCols := 'notecredit nc, notecredit1 nc1, intrari i, npart p, nartobj o, ncont c, ncont casoc,nclasedisc clsdisc';
  END IF;

  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_NOTECREDIT.gSuplCols',gSuplCols,false);

  PERFORM PKG_GLOBALS_SetSeparator (', ');

  WITH x AS
    (SELECT fnc_GetValConstantaLucru('ArtDiscAcVol') COD
      union ALL
     SELECT fnc_GetValConstantaLucru('ArtDiscAcCant') COD
      union ALL
     SELECT fnc_GetValConstantaLucru('ArtPenAc') COD
    )
  SELECT coalesce (string_agg (cod,', ') ,'') || coalesce (fnc_GetValConstantaLucru('ArtDiscAcTer') ,'')
  INTO sWhenObj
  FROM x
  WHERE COALESCE (x.cod::numeric, 0) &gt; 0;

  IF sWhenObj IS NOT NULL THEN
    sWhenObj := '
                WHEN I1.CodObiect IN (' || coalesce (sWhenObj,'') || ') THEN 0';
  END IF;
  sSelectV :=
      'INSERT INTO '|| tmpName ||'
       (NAV_CodDoc,
          NAV_TipDoc,
          NCDATAI,
          NCDATAS,
          TIPOPER,
          DOC,
          PART,
          ART,
          SUBUNITATEA,
          CONT,
          MONEDA,
          LOCATIE,
          CURS,
          VAL,
          VALLEI,
          DISCOUNT ' || coalesce (gUserFields ,'')
      || ')
      WITH ValAaux AS
        ( SELECT codncredit1, ValM, Sum (ValM) over (PARTITION BY codncredit) ValTot
          FROM (SELECT nc.codncredit, nc1.codncredit1,
                       SUM (CASE
                              WHEN i1.tiplinie IN (''T'', ''G'') AND i.tipdoc IN (3, 16, 21) THEN I1.RESTFACT - I1.TVA
                              WHEN i1.tiplinie IN (''T'', ''G'') THEN I1.RESTFACT'
                              || coalesce (sWhenObj,'') || '
                              WHEN i.tipdoc    IN (3, 16, 21) THEN I1.Cant * I1.PU - I1.TVA
                              ELSE I1.Cant  * I1.PU
                            END) ValM
                FROM NOTECREDIT              NC
                     INNER JOIN NOTECREDIT1  NC1 ON NC1.CODNCREDIT = NC.CODNCREDIT
                     INNER JOIN ' || coalesce (sTable,'')  || '  I   ON i.'  || coalesce (sCamp,'') || ' = nc1.coddoc AND nc1.tipdoc = i.tipdoc
                     INNER JOIN ' || coalesce (sTable1,'') || '  I1  ON i1.' || coalesce (sCamp,'') || ' = i.' || coalesce (sCamp,'') || '
                WHERE nc.tipdoc = ' || coalesce (sTipNC::varchar,'')
                      || coalesce (sFiltruNC,'') || '
                      AND nc1.tipoper = ''V''
                GROUP BY nc.codncredit, nc1.codncredit1
               ) a1_pg
        )
      SELECT nc.codncredit,' || coalesce (sTipNC::varchar,'') || ',
             nc.datastart, nc.datastop, ''VOLUM'', i.prefixdoc||i.nrdoc||''/''||TO_CHAR (i.datadoc, ''DD.MM.YYYY'') ,
             p.den_part, o.denumire, s.den_subunit, c.simbol, m.simbol, a.obs,
             (case when coalesce (G.CURS, 0) = 0 then 1 else G.CURS end ) ,
             ROUND (VA.ValM, 4) ,
             ROUND (VA.ValM * (case when coalesce (G.CURS, 0) = 0 then 1 else G.CURS end) , 4),
             coalesce (nc1.valoare,0) - coalesce (nc1.valoareold,0) ' || coalesce (gUserAlias ,'') || '
      FROM NOTECREDIT                                 NC
           INNER JOIN NOTECREDIT1                     NC1     ON NC1.CODNCREDIT       = NC.CODNCREDIT
           LEFT JOIN ' || coalesce (sTable,'') || '   I       ON i.' || coalesce (sCamp,'') || ' = NC1.Coddoc AND I.TipDoc = NC1.TipDoc
           LEFT JOIN VALAAUX                          VA      ON VA.CODNCREDIT1       = NC1.CODNCREDIT1
           LEFT JOIN NCONT                            C       ON C.CODCONT            = NC.CODCONTV
           LEFT JOIN NCONT                            CASOC   ON CASOC.CODCONT        = 0
           LEFT JOIN NPART                            P       ON P.CODPART            = NC.CODPART
           LEFT JOIN NSUBUNIT                         S       ON S.CODSUBUNIT         = NC.SUBUNITATEA
           LEFT JOIN NARTOBJ                          O       ON O.CODOBIECT          = 0
           LEFT JOIN GENERAL                          G       ON G.CODDOC             = NC1.Coddoc AND G.TipDoc = NC1.TipDoc
           LEFT JOIN NMONEDE                          M       ON M.CODMONEDA          = G.MONEDA
           LEFT JOIN NAGENDA                          A       ON A.CODAGENDA          = I.CODLOCATIE
           LEFT JOIN CONTRACT2                        C2      ON C2.CODCONTRACT2      = NC.CODCONTRACT2
           left join nclasedisc                       clsdisc on clsdisc.codclasedisc = nc1.codclasedisc '
           || coalesce (gSuplJoins ,'') || '
      WHERE NC.TIPDOC = ' || coalesce (sTipNC::varchar,'')
            || coalesce (sFiltruNC,'') || '
            AND NC1.TipOper = ''V'' '
            || coalesce ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'NC',NULL,NULL,NULL)) ,'');
  IF sTipNC = 58 THEN
    sSelectV := coalesce (sSelectV,'')
    || ' AND G.Semnificatie = 200';
  ELSE
    sSelectV := coalesce (sSelectV,'')
    || ' AND G.Semnificatie &lt;&gt; 500
    and G.Semnificatie &lt;&gt; 111
    and G.Semnificatie &lt;&gt; 200
    and G.Semnificatie &lt;&gt; 140';
  END IF;

  sDisc    := 'COALESCE (NC1.VALOARE,0) - COALESCE (NC1.VALOAREOLD,0) ,  ';
  sSelectT := '
    INSERT INTO ' || tmpName
    || ' (NCDATAI,
        NCDATAS,
        TIPOPER,
        DOC,
        PART,
        ART,
        SUBUNITATEA,
        CONT,
        MONEDA,
        LOCATIE,
        CURS,
        VAL,
        VALLEI,
        DISCOUNT,
        CANT,
        CONTASOC,
        TERMEN,
        DOCPLATA,
        VALPLATA,
        ZILEPLATA '
    || coalesce(gUserFields,'')
    || ')
    SELECT nc.datastart, nc.datastop, ''TERMEN'', i.prefixdoc||i.nrdoc||''/''||TO_CHAR (i.datadoc, ''DD.MM.YYYY'') ,
           p.den_part, o.denumire, s.den_subunit, c.simbol, m.simbol, a.obs,
           (case when coalesce (G.CURS, 0) = 0 then 1 else G.CURS end) ,
           CASE
             WHEN i.tipdoc IN (3, 16, 21) THEN i1.pu * i1.cant
             ELSE i1.pu * i1.cant + i1.tva
           END,
           CASE
             WHEN i.tipdoc IN (3, 16, 21) THEN i1.pu * i1.cant
             ELSE i1.pu * i1.cant + i1.tva
           END  * ( case when coalesce (G.CURS, 0) = 0 then 1 else G.CURS end) , '
    || coalesce (sDisc,'')
    || '   I1.CANT,
           CASOC.SIMBOL, OB.TERMEN,
           T1.DOC||T1.NRDOC||''/''||TO_CHAR (T1.DATADOC, ''DD.MM.YYYY'') ,
           STG.VALOARE * (CASE WHEN i.tipdoc IN (3, 16, 21) THEN i1.pu * i1.cant
                               ELSE i1.pu * i1.cant + i1.tva
                          END
                         ) / I.VALDOC,
           T1.DATADOC::date - I.DATADOC::date ' || coalesce(gUserAlias ,'') || '
    FROM NOTECREDIT                                NC
         INNER JOIN NOTECREDIT1                    NC1     ON NC1.CODNCREDIT       = NC.CODNCREDIT
         LEFT JOIN ' || coalesce (sTable1,'') || ' I1      ON i1.' || coalesce (sCamp1,'') || ' = NC1.Coddoc
         LEFT JOIN ' || coalesce (sTable,'')  || ' I       ON i.'  || coalesce (sCamp,'')  || ' = i1.' || coalesce (sCamp,'') || ' AND I.TipDoc = NC1.TipDoc
         LEFT JOIN GENERAL                         G       ON G.CODDOC             = i.' || coalesce (sCamp,'') || ' AND G.TipDoc = NC1.TipDoc
         LEFT JOIN OBLIGPIF                        OB      ON OB.CODOBLIGPIF       = NC1.CODOBLIGSTINS
         LEFT JOIN OBLIGPIF                        OBS     ON OBS.CODOBLIGPIF      = NC1.CODOBLIGSTINGATOR
         LEFT JOIN STINGERE                        STG     ON STG.CODSTINSPIF      = OB.CODOBLIGPIF AND STG.CODSTINGATORPIF = OBS.CODOBLIGPIF
         LEFT JOIN GENERAL                         GS      ON OBS.CODGENERAL       = GS.CODGENERAL
         LEFT JOIN TREZOR1                         T1      ON T1.CODTREZOR1        = GS.CODDOC
         LEFT JOIN TREZOR                          T       ON T.CODTREZOR          = T1.CODTREZOR AND GS.TIPDOC = T.Tipdoc
         LEFT JOIN NARTOBJ                         O       ON O.CodObiect          = I1.CodObiect
         LEFT JOIN NPART                           P       ON P.CODPART            = NC.CODPART
         LEFT JOIN NSUBUNIT                        S       ON S.CODSUBUNIT         = NC.SUBUNITATEA
         LEFT JOIN NCONT                           C       ON C.CODCONT            = NC.CODCONTT
         LEFT JOIN NCONT                           CASOC   ON CASOC.CODCONT        = PKG_LIST_BASE_UTILS_iCont_CodCont (OB.icont, OB.codpart, i.an * 12 + i.luna, OB.semnificatie)
         LEFT JOIN NMONEDE                         M       ON M.CODMONEDA          = coalesce (G.MONEDA, 0)
         LEFT JOIN NAGENDA                         A       ON I.CODLOCATIE         = A.CODAGENDA
         LEFT JOIN CONTRACT2                       C2      ON NC.CODCONTRACT2      = C2.CODCONTRACT2
         left join nclasedisc                      clsdisc on clsdisc.codclasedisc = nc1.codclasedisc '
    || coalesce (gSuplJoins ,'') || '
    WHERE NC.TIPDOC = ' || coalesce (sTipNC::varchar,'')
          || coalesce (sFiltruNC,'') || '
          AND NC1.TipOper = ''T'' '
          || coalesce ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'NC',NULL,NULL,NULL)) ,'');

  IF sTipNC = 58 THEN
    sSelectT := coalesce (sSelectT,'')
    || ' AND G.semnificatie &lt;&gt; 240
    and G.semnificatie &lt;&gt; 500
    and G.semnificatie &lt;&gt; 211
    and G.semnificatie &lt;&gt; 210';
  ELSE
    sSelectT := coalesce (sSelectT,'')
    || ' AND G.semnificatie &lt;&gt; 140
    and G.semnificatie &lt;&gt; 600
    and G.semnificatie &lt;&gt; 130';
  END IF;

  sSelectC := '
      INSERT INTO ' || tmpName
      || ' (NCDATAI,
          NCDATAS,
          TIPOPER,
          DOC,
          PART,
          ART,
          SUBUNITATEA,
          CONT,
          MONEDA,
          LOCATIE,
          CURS,
          VAL,
          VALLEI,
          DISCOUNT,
          CANT,
          PRET,
          PROCDISC ' || coalesce (gUserFields ,'') || ')
      WITH CumulCant AS
        (SELECT nc.codncredit, i1.codobiect, c1.codcontract1,
                sum (i1.cant * i1.pu - CASE WHEN i.tipdoc IN (3, 16, 21) THEN i1.tva ELSE 0 END) / sum (i1.cant) pretmediu,
                sum (i1.cant) totalcant
          FROM NOTECREDIT                               NC
               INNER JOIN NOTECREDIT1                   NC1 ON NC1.CODNCREDIT  = NC.CODNCREDIT
               INNER JOIN '|| coalesce (sTable1,'')|| ' I1  ON i1.'|| coalesce (sCamp1,'')|| ' = nc1.coddoc
               INNER JOIN '|| coalesce (sTable,'')|| '  I   ON i1.'|| coalesce (sCamp ,'')|| ' = i.'|| coalesce (sCamp,'')|| ' AND nc1.tipdoc = i.tipdoc
               LEFT JOIN contract2                      c2  ON c2.codcontract2 = nc.codcontract2
               LEFT JOIN contract1                      c1  on c1.codcontract  = c2.codcontract AND c1.codobiect = i1.codobiect
          WHERE nc.tipdoc = ' || coalesce (sTipNC::varchar,'')
                || coalesce (sFiltruNC,'') || '
                AND nc1.tipoper = ''C''
          GROUP BY nc.codncredit, i1.codobiect, c1.codcontract1
        )
      SELECT nc.datastart, nc.datastop, ''CANTITATE'', i.prefixdoc||i.nrdoc||''/''||TO_CHAR (i.datadoc, ''DD.MM.YYYY'') ,
             p.den_part, o.denumire, s.den_subunit, c.simbol, m.simbol, a.obs,
             (case when coalesce (G.CURS, 0) = 0 then 1 else G.CURS end) ,
             I1.cant * I1.PU,
             I1.cant * I1.PU * (case when coalesce (G.CURS, 0) = 0 then 1 else G.CURS end) ,
             COALESCE (NC1.VALOARE,0) - COALESCE (NC1.VALOAREOLD,0) ,
             i1.cant, i1.pu,
             100 * CASE
                     WHEN i1.cant = 0 THEN 1
                     WHEN i1.pu = 0 THEN 1
                     ELSE NC1.Valoare / (I1.cant * I1.PU * (case when coalesce (G.CURS, 0) = 0 then 1 else G.CURS end))
                   END ' || coalesce (gUserAlias ,'') || '
      FROM NOTECREDIT                               NC
        INNER JOIN NOTECREDIT1                      NC1     ON NC1.CODNCREDIT       = NC.CODNCREDIT
        LEFT JOIN '|| coalesce (sTable1,'')|| '     I1      ON i1.'|| coalesce (sCamp1,'')|| ' = nc1.coddoc
        LEFT JOIN '|| coalesce (sTable,'')|| '      I       ON i1.'|| coalesce (sCamp ,'')|| ' = i.'|| coalesce (sCamp,'')|| ' AND nc1.tipdoc = i.tipdoc
        LEFT JOIN CumulCant                         CC      ON CC.CODNCREDIT        = NC.CODNCREDIT AND CC.CODOBIECt = I1.CODOBIECT
        LEFT JOIN NARTOBJ                           O       ON O.CodObiect          = I1.CodObiect
        LEFT JOIN NCONT                             C       ON C.CODCONT            = NC.CODCONTC
        LEFT JOIN NCONT                             CASOC   ON CASOC.CODCONT        = 0
        LEFT JOIN NPART                             P       ON P.CODPART            = NC.CODPART
        LEFT JOIN NSUBUNIT                          S       ON S.CODSUBUNIT         = NC.SUBUNITATEA
        LEFT JOIN GENERAL                           G       ON G.CODDOC             = i.'|| coalesce (sCamp,'')|| ' AND G.TipDoc = NC1.TipDoc
        LEFT JOIN NMONEDE                           M       ON M.CODMONEDA          = G.MONEDA
        LEFT JOIN NAGENDA                           A       ON A.CODAGENDA          = I.CODLOCATIE
        LEFT JOIN CONTRACT2                         C2      ON NC.CODCONTRACT2      = C2.CODCONTRACT2
        left join nclasedisc                        clsdisc on clsdisc.codclasedisc = nc1.codclasedisc '
      || coalesce (gSuplJoins ,'') || '
      WHERE NC.TIPDOC = ' || coalesce (sTipNC::varchar,'')
            || coalesce (sFiltruNC,'') || '
            AND NC1.TipOper = ''C'' '
            || coalesce ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'NC',NULL,NULL,NULL)) ,'');

  IF sTipNC = 58 THEN
    sSelectC := coalesce (sSelectC,'')
    || ' AND g.semnificatie not in (500, 240, 211, 100, 140, 400) ';
  ELSE
    sSelectC := coalesce (sSelectC,'')
    || ' AND g.semnificatie not in (500, 111, 200, 140, 300) ';
  END IF;

  sSelectP := '
      INSERT INTO ' || tmpName
      || ' (NCDATAI,
          NCDATAS,
          TIPOPER,
          DOC,
          PART,
          ART,
          SUBUNITATEA,
          CONT,
          MONEDA,
          LOCATIE,
          CURS,
          VAL,
          VALLEI,
          DISCOUNT,
          CONTASOC,
          TERMEN,
          DOCPLATA,
          VALPLATA,
          ZILEPLATA ' || coalesce (gUserFields ,'')
          || ')
      SELECT nc.datastart, nc.datastop, ''PENALIZARI'', i.prefixdoc||i.nrdoc||''/''||TO_CHAR (i.datadoc, ''DD.MM.YYYY'') ,
             p.den_part, o.denumire, s.den_subunit, c.simbol, m.simbol, a.obs,
             (case when coalesce (G.CURS, 0) = 0 then 1 else G.CURS end) ,
             OB.VALOARE,
             OB.VALOARE * (case when coalesce (G.CURS, 0) = 0 then 1 else G.CURS end )  ,
             COALESCE (NC1.VALOARE,0) - COALESCE (NC1.VALOAREOLD,0) ,
             CASOC.SIMBOL, OB.TERMEN,
             T1.DOC||T1.NRDOC||''/''||TO_CHAR (T1.DATADOC, ''DD.MM.YYYY'') ,
             STG.VALOARE,
             T1.DATADOC::date - I.DATADOC::date ' || coalesce (gUserAlias ,'') || '
      FROM NOTECREDIT                              NC
        INNER JOIN NOTECREDIT1                     NC1     ON NC1.CODNCREDIT       = NC.CODNCREDIT
        LEFT JOIN ' || coalesce (sTable,'') || '   I       ON i.' || coalesce (sCamp,'') || ' = NC1.Coddoc AND I.TipDoc = NC1.TipDoc
        LEFT JOIN GENERAL                          G       ON G.CODDOC             = NC1.Coddoc AND G.TipDoc = NC1.TipDoc
        LEFT JOIN OBLIGPIF                         OB      ON OB.CODOBLIGPIF       = NC1.CODOBLIGSTINS
        LEFT JOIN OBLIGPIF                         OBS     ON OBS.CODOBLIGPIF      = NC1.CODOBLIGSTINGATOR
        LEFT JOIN STINGERE                         STG     ON STG.CODSTINSPIF      = OB.CODOBLIGPIF AND STG.CODSTINGATORPIF = OBS.CODOBLIGPIF
        LEFT JOIN GENERAL                          GS      ON OBS.CODGENERAL       = GS.CODGENERAL
        LEFT JOIN TREZOR1                          T1      ON T1.CODTREZOR1        = GS.CODDOC
        LEFT JOIN TREZOR                           T       ON T.CODTREZOR          = T1.CODTREZOR AND GS.TIPDOC = T.Tipdoc
        LEFT JOIN NARTOBJ                          O       ON O.CodObiect          = 0
        LEFT JOIN NPART                            P       ON P.CODPART            = NC.CODPART
        LEFT JOIN NSUBUNIT                         S       ON S.CODSUBUNIT         = NC.SUBUNITATEA
        LEFT JOIN NCONT                            C       ON C.CODCONT            = NC.CODCONTP
        LEFT JOIN NCONT                            CASOC   ON CASOC.CODCONT        = PKG_LIST_BASE_UTILS_iCont_CodCont (OB.icont, OB.codpart, i.an * 12 + i.luna, OB.semnificatie)
        LEFT JOIN NMONEDE                          M       ON M.CODMONEDA          = coalesce (G.MONEDA, 0)
        LEFT JOIN NAGENDA                          A       ON I.CODLOCATIE         = A.CODAGENDA
        LEFT JOIN CONTRACT2                        C2      ON NC.CODCONTRACT2      = C2.CODCONTRACT2
        left join nclasedisc                       clsdisc on clsdisc.codclasedisc = nc1.codclasedisc '
      || coalesce (gSuplJoins ,'') || '
      WHERE NC.TIPDOC = ' || coalesce (sTipNC::varchar,'')
            || coalesce (sFiltruNC,'') || '
            AND NC1.TipOper = ''P'' '
            || coalesce ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'NC',NULL,NULL,NULL)) ,'');

  PERFORM LIST_EXECUTE_IMMEDIATE (sSelectv, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE (sselectt, aListID, aListVer);
  EXECUTE 'DELETE FROM ' || coalesce (tmpName,'') || ' WHERE coalesce(discount, 0) = 0 AND TIPOPER = ''TERMEN'' ';
  PERFORM LIST_EXECUTE_IMMEDIATE (sSelectc, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE (sSelectp, aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_planifstoc_processlist</obj_name>
  <obj_hashval>af32cb0ac3d404083314ad5cca093df7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_planifstoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       varchar := '';
  sSelect       varchar := '';
  sSelect1       varchar := '';
  vAnPrec       numeric;
  vLunaPrec     numeric;
  gSuplCols      VARCHAR := 'NARTOBJ NAO, NART NA, NUM NUM, NPART PROD, NCLASEA CA';
   gUserFields    VARCHAR := '';
  gUserAlias     VARCHAR := '';
  gNullAlias     VARCHAR := '';
  gSuplJoins     VARCHAR := '';
  vDataStart    date    := to_date(current_setting('PKG_LIST_BASE_PLANIFSTOC.vDataStart', true),'dd.mm.yyyy');
  vDataFin       date    := to_date(current_setting('PKG_LIST_BASE_PLANIFSTOC.vDataFin'  , true),'dd.mm.yyyy');
  vAllGestCmd    boolean := current_setting('PKG_LIST_BASE_PLANIFSTOC.vAllGestCmd' , true)::boolean;
  vNoTermen      boolean := current_setting('PKG_LIST_BASE_PLANIFSTOC.vNoTermen'   , true)::boolean;
  vAllGestStoc  boolean := current_setting('PKG_LIST_BASE_PLANIFSTOC.vAllGestStoc', true)::boolean;
BEGIN
  --Adina 30.06.2021 - modif.param.fct.pkg_list_selfisamag_setallparams din bool in numeric
  --Adina 02 septembrie 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_PLANIFSTOC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  PERFORM pkg_list_base_utils_make_config_luna_ioart();
  SELECT newan,newluna INTO vAnPrec, vLunaPrec FROM pkg_globals_Calculeaza_Luna_Precedenta(Extract(Year FROM vDataStart)::numeric, Extract(Month FROM vDataStart)::numeric, vAnPrec, vLunaPrec);
  PERFORM pkg_globals_SetLunaTemp(Extract(Year FROM vDataStart)::numeric, Extract(Month FROM vDataStart)::numeric);
  PERFORM pkg_globals_SetLunaPrecedenta(vAnPrec, vLunaPrec);
  PERFORM PKG_LIST_SELFISAMAG_setAllParams(NULL, NULL, '01' || '.' || to_char(getLUNALUCRU(), '00') || '.' || to_char(getANLUCRU(), '0000'), 0, 0, 0);

  DELETE FROM TMP_GESTCMD;
  sSelect := 'INSERT INTO TMP_GESTCMD (CODGEST, CODOBIECT, DEN_GEST)
  SELECT DISTINCT C1.GESTACT, C1.CODOBIECT, G.DEN_GEST
  FROM COMANDA1 C1
       INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
       INNER JOIN NGEST   G ON G.CODGEST     = C1.GESTACT ';

  IF  NOT vAllGestCmd THEN
    sSelect := sSelect || ' INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = G.CODGEST::varchar AND TMP.FILTRU = ''CODGESTCMD'' ';
  END IF;

  sSelect := sSelect || 'WHERE coalesce(C.INCHISA, 0) = 0
    AND C.Operat = 1 AND coalesce(C.Anulat, 0) &lt;&gt; 1 AND C.TipDoc = 18 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || ' AND C1.GESTACT &gt; 0 ' || coalesce(chr(13),'');

  IF  NOT vNoTermen THEN
    sSelect := sSelect || ' AND C1.TERMEN BETWEEN ''' || vDataStart::varchar || ''' AND ''' || vDataFin::varchar || '''';
  END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);

  DELETE FROM TMP_PLANIFSTOC;

  IF  NOT vNoTermen THEN
    sSelect := '
    INSERT INTO TMP_PLANIFSTOC (CODOBIECT, CANT, CODGEST, FILTRU, CANTREZ, SERIE, TG)
    SELECT
      V.CODOBIECT,
      sum(V.REST),
      V.CODGEST,
      ''STOCINISER'',
      sum(coalesce(V.CANTREZ,0)),
      SER.SERIE,
      to_char(V.TG, ''dd.mm.yyyy'')
    FROM v_stoc_ini_planif v
         inner join ngest g on v.codgest = g.codgest ' || coalesce(pkg_list_base_utils_COND_SUBUNIT('g', 'codsubunit',NULL,NULL),'');

    IF  NOT vAllGestStoc THEN
      sSelect := sSelect || ' INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = G.CODGEST::varchar AND TMP.FILTRU = ''CODGESTSTOC'' ';
    END IF;

    sSelect := sSelect || ' left join nserii ser on v.codserie = ser.codserie
      WHERE v.rest &lt;&gt; 0
      group by v.codobiect, v.codgest, ser.serie, v.tg';

    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);

    DELETE FROM tmp_planifstoc_clona;

    INSERT INTO tmp_planifstoc_clona
    SELECT * FROM tmp_planifstoc;

    sSelect := '
    INSERT INTO TMP_PLANIFSTOC (CODOBIECT, CANT, CODGEST, FILTRU, SERIE, TG)
    SELECT
      V.CODOBIECT,
      SUM(V.REST),
      g.codgest,
      ''SERTGINI'',
      SER.SERIE,
      CASE WHEN V.TG IS NULL THEN '''' ELSE to_char(V.TG, ''dd.mm.yyyy'') END
    FROM v_stoc_ini_planif v
         inner join ngest g on v.codgest = g.codgest ' || coalesce(pkg_list_base_utils_COND_SUBUNIT('g', 'codsubunit',NULL,NULL),'');

    IF  NOT vAllGestStoc THEN
      sSelect := sSelect || ' INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = G.CODGEST::varchar AND TMP.FILTRU = ''CODGESTSTOC'' ';
    END IF;

    sSelect := sSelect || ' left join nserii ser on v.codserie = ser.codserie
      WHERE v.rest &lt;&gt; 0
      group by v.codobiect, g.codgest, ser.serie, v.tg';

    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);

    sSelect := '
    INSERT INTO TMP_PLANIFSTOC (CODOBIECT, CANT, CODGEST, FILTRU, CANTREZ)
    SELECT
      V.CODOBIECT,
      sum(V.CANT),
      V.CODGEST,
      ''STOCINI'',
      sum(coalesce(V.CANTREZ,0))
    FROM tmp_planifstoc_clona v
    group by v.codobiect, v.codgest';

    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);

    sSelect := '
    INSERT INTO TMP_PLANIFSTOC (CODOBIECT, CANT, CODGEST, FILTRU)
    SELECT CODOBIECT, sum(REST), CODGEST, ''INTRARI''
    FROM (
          SELECT
            NS.CODOBIECT,
            CASE WHEN coalesce(NSE.CODNIRSER, 0) = 0 THEN NS.CANTNIR ELSE NSE.CANTNIR END REST,
            N.GEST CODGEST
          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 ' || coalesce(pkg_list_base_utils_COND_SUBUNIT('g', 'codsubunit',NULL,NULL),'');

    IF  NOT vAllGestStoc THEN
      sSelect := sSelect || ' INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = G.CODGEST::varchar AND TMP.FILTRU = ''CODGESTSTOC'' ';
    END IF;

    sSelect := sSelect || ' LEFT  JOIN NIRSER NSE ON NS.CODNIRSTOC = NSE.CODNIRSTOC
          WHERE
            N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 12, 13) AND  N.ANULAT = 0 AND N.OPERAT = 1
            AND N.DATANIR BETWEEN ''' || to_date('01' || '.' || to_char(getLUNALUCRU(), '00') || '.' || to_char(getANLUCRU(), '0000'), 'dd.mm.yyyy')::varchar || ''' AND ''' || last_day(to_date('01' || '.' || to_char(getLUNALUCRU(), '00') || '.' || to_char(getANLUCRU(), '0000'), 'dd.mm.yyyy'))::varchar || ''' AND IO.MG &lt;&gt; 5
        ) A1_PG
    GROUP BY codobiect, codgest';

    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);

    sSelect := '
    INSERT INTO TMP_PLANIFSTOC (CODOBIECT, CANT, CODGEST, FILTRU, SERIE, TG)
    SELECT CODOBIECT, sum(REST), codgest, ''SERTGIN'', SERIE, TG
    FROM (
          SELECT
            NS.CODOBIECT,
            CASE WHEN coalesce(NSE.CODNIRSER, 0) = 0 THEN NS.CANTNIR ELSE NSE.CANTNIR END REST,
            g.codgest,
            SER.SERIE,
            case when ns.tg is null then case when nse.tg is null then '''' else to_char(nse.tg,''dd.mm.yyyy'') end
                 else to_char(ns.tg,''dd.mm.yyyy'')
            end TG
          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 ' || coalesce(pkg_list_base_utils_COND_SUBUNIT('g', 'codsubunit',NULL,NULL),'');

    IF  NOT vAllGestStoc THEN
      sSelect := sSelect || ' INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = G.CODGEST::varchar AND TMP.FILTRU = ''CODGESTSTOC'' ';
    END IF;

    sSelect := sSelect || ' LEFT  JOIN NIRSER NSE ON NS.CODNIRSTOC = NSE.CODNIRSTOC
            LEFT  JOIN NSERII        SER ON SER.CODSERIE = NSE.CODSERIE
          WHERE
            N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 12, 13) AND  N.ANULAT = 0 AND N.OPERAT = 1
            AND N.DATANIR BETWEEN ''' || to_date('01' || '.' || to_char(getLUNALUCRU(), '00') || '.' || to_char(getANLUCRU(), '0000'), 'dd.mm.yyyy')::varchar || ''' AND ''' || last_day(to_date('01' || '.' || to_char(getLUNALUCRU(), '00') || '.' || to_char(getANLUCRU(), '0000'), 'dd.mm.yyyy'))::varchar || ''' AND IO.MG &lt;&gt; 5
          ) A2_PG GROUP BY codobiect, codgest, serie, tg';

    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);

    sSelect := '
    INSERT INTO TMP_PLANIFSTOC (CODOBIECT, CANT, CODGEST, FILTRU)
    SELECT codobiect, sum(canties) canties, codgest, ''IES''
    FROM (
          SELECT
            ns.codobiect,
            CASE WHEN L.TIPLIVR = 15 THEN - L1.CANT ELSE L1.CANT END canties,
            GESTCMD.CODGEST
          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 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('G', 'CODSUBUNIT',NULL,NULL),'') || '
            INNER JOIN TMP_GESTCMD    GESTCMD ON G.CODGEST     = GESTCMD.CODGEST  AND GESTCMD.CODOBIECT = NS.CODOBIECT
            INNER JOIN TMP_IOART_LUNA io      ON io.codioart   = ns.codioart
          WHERE L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15 ,16, 19, 20, 21, 23, 24) AND L.OPERAT = 1 AND L.ANULAT = 0
            AND io.mg &lt;&gt; 5
            AND l.operat = 1 AND l.anulat = 0
            AND l.datalivr BETWEEN ''' || to_date('01' || '.' || to_char(getLUNALUCRU(), '00') || '.' || to_char(getANLUCRU(), '0000'), 'dd.mm.yyyy')::varchar || ''' AND ''' || last_day(to_date('01' || '.' || to_char(getLUNALUCRU(), '00') || '.' || to_char(getANLUCRU(), '0000'), 'dd.mm.yyyy'))::varchar || '''
         ) A3_PG
    GROUP BY codobiect, codgest';

    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);

    sSelect := '
    INSERT INTO TMP_PLANIFSTOC (CODOBIECT, CANT, CODGEST, FILTRU, SERIE, TG)
    SELECT codobiect, sum(canties) canties, codgest, ''SERTGIES'', SERIE, TG
    FROM (
          SELECT
            ns.codobiect,
            CASE WHEN L.TIPLIVR = 15 THEN - L1.CANT ELSE L1.CANT END canties,
            g.codgest,
            SER.SERIE,
            case when ns.tg is null then case when nse.tg is null then '''' else to_char(nse.tg,''dd.mm.yyyy'') end
                 else to_char(ns.tg,''dd.mm.yyyy'')
            end TG
          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 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('G', 'CODSUBUNIT',NULL,NULL),'') || '
            INNER JOIN TMP_GESTCMD    GESTCMD ON G.CODGEST     = GESTCMD.CODGEST  AND GESTCMD.CODOBIECT = NS.CODOBIECT
            INNER JOIN TMP_IOART_LUNA io      ON io.codioart   = ns.codioart
            LEFT  JOIN NIRSER         NSE     ON NS.CODNIRSTOC = NSE.CODNIRSTOC and l1.codnirser = nse.codnirser
            LEFT  JOIN NSERII         SER     ON SER.CODSERIE  = NSE.CODSERIE
          WHERE L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15 ,16, 19, 20, 21, 23, 24) AND L.OPERAT = 1 AND L.ANULAT = 0
            AND io.mg &lt;&gt; 5
            AND l.datalivr BETWEEN ''' || to_date('01' || '.' || to_char(getLUNALUCRU(), '00') || '.' || to_char(getANLUCRU(), '0000'), 'dd.mm.yyyy')::varchar || ''' AND ''' || last_day(to_date('01' || '.' || to_char(getLUNALUCRU(), '00') || '.' || to_char(getANLUCRU(), '0000'), 'dd.mm.yyyy'))::varchar || '''
         ) A4_PG
    GROUP BY codobiect, codgest, serie, tg';

    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);

    sSelect := '
    INSERT INTO TMP_PLANIFSTOC (CODOBIECT, CANT, CODGEST, FILTRU)
    SELECT codobiect, sum(canties) canties, gest, ''IES0''
    FROM (
      SELECT
        ns.codobiect,
        -ns.cantfurn canties,
        n.gest
      FROM nir n
        INNER JOIN ngest          g  ON g.codgest = n.gest ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('G', 'CODSUBUNIT',NULL,NULL),'') || '
        INNER JOIN nirstoc        ns ON ns.codnir = n.codnir
        INNER JOIN TMP_IOART_LUNA io ON io.codioart = ns.codioart ';

    IF  NOT vAllGestCmd THEN
      sSelect := sSelect || ' INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = G.CODGEST::varchar AND TMP.FILTRU = ''CODGESTSTOC'' ';
    END IF;

    sSelect := sSelect || ' WHERE n.tipnir IN (19, 20, 21, 22, 23, 24, 25)
        and not exists (select gestcmd.codgest from TMP_gestcmd GESTCMD where gestcmd.codgest = g.codgest AND GESTCMD.CODOBIECT = NS.CODOBIECT)
        AND io.mg &lt;&gt; 5
        AND n.datanir BETWEEN ''' || to_date('01' || '.' || to_char(getLUNALUCRU(), '00') || '.' || to_char(getANLUCRU(), '0000'), 'dd.mm.yyyy')::varchar || ''' AND ''' || last_day(to_date('01' || '.' || to_char(getLUNALUCRU(), '00') || '.' || to_char(getANLUCRU(), '0000'), 'dd.mm.yyyy'))::varchar || '''
      UNION ALL
      SELECT
        ns.codobiect,
        l1.cant canties,
        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 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('G', 'CODSUBUNIT',NULL,NULL),'') || '
        INNER JOIN TMP_IOART_LUNA io ON io.codioart   = ns.codioart';

    IF  NOT vAllGestCmd THEN
      sSelect := sSelect || ' INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = G.CODGEST::varchar AND TMP.FILTRU = ''CODGESTSTOC'' ';
    END IF;

    sSelect := sSelect || '
      WHERE l.tiplivr IN (14, 16, 19, 20, 21, 22, 23, 24, 25)
        and not exists (select gestcmd.codgest from tmp_gestcmd gestcmd where gestcmd.codgest = g.codgest AND GESTCMD.CODOBIECT = NS.CODOBIECT )
        AND io.mg &lt;&gt; 5
        AND l.operat = 1 AND l.anulat = 0
        AND l.datalivr BETWEEN ''' || to_date('01' || '.' || to_char(getLUNALUCRU(), '00') || '.' || to_char(getANLUCRU(), '0000'), 'dd.mm.yyyy')::varchar || ''' AND ''' || last_day(to_date('01' || '.' || to_char(getLUNALUCRU(), '00') || '.' || to_char(getANLUCRU(), '0000'), 'dd.mm.yyyy'))::varchar || '''
    ) A5_PG
    GROUP BY codobiect, gest';

    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);

    sSelect := '
    INSERT INTO TMP_PLANIFSTOC (CODOBIECT, CANT, CODGEST, FILTRU, SERIE, TG)
    SELECT codobiect, sum(canties) canties, codgest, ''SERTGIES0'', SERIE, TG
    FROM (
      SELECT
        ns.codobiect,
        ns.cantfurn canties,
        g.codgest,
        SER.SERIE,
        case when ns.tg is null then case when nse.tg is null then '''' else to_char(nse.tg,''dd.mm.yyyy'') end
             else to_char(ns.tg,''dd.mm.yyyy'')
        end TG
      FROM nir n
        INNER JOIN ngest          g  ON g.codgest   = n.gest ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('G', 'CODSUBUNIT',NULL,NULL)::varchar ,'') || '
        INNER JOIN nirstoc        ns ON ns.codnir   = n.codnir
        INNER JOIN TMP_IOART_LUNA io ON io.codioart = ns.codioart ';

    IF  NOT vAllGestCmd THEN
      sSelect := sSelect || ' INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = G.CODGEST::varchar AND TMP.FILTRU = ''CODGESTSTOC'' ';
    END IF;

    sSelect := sSelect || '
        LEFT  JOIN NIRSER NSE ON NS.CODNIRSTOC = NSE.CODNIRSTOC
        LEFT  JOIN NSERII SER ON SER.CODSERIE  = NSE.CODSERIE
      WHERE n.tipnir IN (19, 20, 21, 22, 23, 24, 25)
        and not exists (select gestcmd.codgest from TMP_gestcmd GESTCMD where gestcmd.codgest = g.codgest AND GESTCMD.CODOBIECT = NS.CODOBIECT)
        AND io.mg &lt;&gt; 5
        AND n.datanir BETWEEN ''' || to_date('01' || '.' || to_char(getLUNALUCRU(), '00') || '.' || to_char(getANLUCRU(), '0000'), 'dd.mm.yyyy')::varchar || ''' AND ''' || last_day(to_date('01' || '.' || to_char(getLUNALUCRU(), '00') || '.' || to_char(getANLUCRU(), '0000'), 'dd.mm.yyyy'))::varchar || '''
      UNION ALL
      SELECT
        ns.codobiect,
        -l1.cant canties,
        g.codgest,
        SER.SERIE,
        case when ns.tg is null then case when nse.tg is null then '''' else to_char(nse.tg,''dd.mm.yyyy'') end
             else to_char(ns.tg,''dd.mm.yyyy'')
        end TG
      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 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('G', 'CODSUBUNIT',NULL,NULL),'') || '
        INNER JOIN TMP_IOART_LUNA io ON io.codioart   = ns.codioart';

    IF  NOT vAllGestCmd THEN
      sSelect := sSelect || ' INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = G.CODGEST::varchar AND TMP.FILTRU = ''CODGESTSTOC'' ';
    END IF;

    sSelect := sSelect || '
        LEFT  JOIN NIRSER NSE ON NS.CODNIRSTOC = NSE.CODNIRSTOC and l1.codnirser = nse.codnirser
        LEFT  JOIN NSERII SER ON SER.CODSERIE  = NSE.CODSERIE
      WHERE l.tiplivr IN (14, 16, 19, 20, 21, 22, 23, 24, 25)
        and not exists (select gestcmd.codgest from tmp_gestcmd gestcmd where gestcmd.codgest = g.codgest AND GESTCMD.CODOBIECT = NS.CODOBIECT )
        AND io.mg &lt;&gt; 5
        AND l.operat = 1 AND l.anulat = 0
        AND l.datalivr BETWEEN ''' || to_date('01' || '.' || to_char(getLUNALUCRU(), '00') || '.' || to_char(getANLUCRU(), '0000'), 'dd.mm.yyyy')::varchar || ''' AND ''' || last_day(to_date('01' || '.' || to_char(getLUNALUCRU(), '00') || '.' || to_char(getANLUCRU(), '0000'), 'dd.mm.yyyy'))::varchar || '''
    ) A6_PG
    GROUP BY codobiect, codgest, serie, tg';

    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);

    DROP INDEX IF EXISTS tmp_planifstoc_idxaa;
    CREATE INDEX tmp_planifstoc_idxaa ON tmp_planifstoc(filtru);

    INSERT INTO tmp_planifstoc(codobiect, tg, cant, serie, codgest, filtru)
    SELECT codobiect, tg, cant, serie, codgest, 'SG'
    FROM (
           SELECT codobiect, tg, sum(cant) CANT, serie, codgest
           FROM tmp_planifstoc
           WHERE filtru = ANY (VALUES ('SERTGINI'),('SERTGIN'),('SERTGIES'),('SERTGIES0'))
           GROUP BY codobiect, tg, serie, codgest
--        SELECT codobiect, tg, sum(cant) CANT, serie, codgest
--        FROM (
--              SELECT codobiect, tg, sum(cant) CANT, serie, codgest
--               FROM tmp_planifstoc
--               WHERE filtru = 'SERTGINI'
--               GROUP BY codobiect, tg, serie, codgest
--              union ALL
--              SELECT codobiect, tg, sum(cant) CANT, serie, codgest
--               FROM tmp_planifstoc
--               WHERE filtru = 'SERTGIN'
--               GROUP BY codobiect, tg, serie, codgest
--              union ALL
--              SELECT codobiect, tg, sum(cant) CANT, serie, codgest
--               FROM tmp_planifstoc
--               WHERE filtru = 'SERTGIES'
--               GROUP BY codobiect, tg, serie, codgest
--              union ALL
--              SELECT codobiect, tg, sum(cant) CANT, serie, codgest
--               FROM tmp_planifstoc
--               WHERE filtru = 'SERTGIES0'
--               GROUP BY codobiect, tg, serie, codgest
--              ) A_PG
--        GROUP BY codobiect, codgest, tg, serie
       ) B_PG
    WHERE cant &gt; 0;

    DELETE FROM tmp_planifstoc WHERE filtru = 'SERTGINI';
    DELETE FROM tmp_planifstoc WHERE filtru = 'SERTGIN';
    DELETE FROM tmp_planifstoc WHERE filtru = 'SERTGIES';
    DELETE FROM tmp_planifstoc WHERE filtru = 'SERTGIES0';
  ELSE
    sSelect := '
    INSERT INTO TMP_PLANIFSTOC (CODOBIECT, CANT, CODGEST, FILTRU, SERIE, TG)
    SELECT codobiect, sum(REST) cant, codgest, ''SG'', SERIE, TG
    FROM (
      SELECT
        ns.codobiect,
        coalesce(ns.rest,0) rest,
        g.codgest,
        SER.SERIE,
        case
          when ns.tg is null then
            case
              when nse.tg is null then ''''
              else to_char(nse.tg,''dd.mm.yyyy'')
            end
          else to_char(ns.tg,''dd.mm.yyyy'')
        end TG
      FROM NIRSTOC NS
        INNER JOIN nir            n  ON N.CODNIR    = NS.CODNIR
        INNER JOIN ngest          g  ON g.codgest   = n.gest ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('G', 'CODSUBUNIT',NULL,NULL),'') || '
        INNER JOIN TMP_IOART_LUNA io ON io.codioart = ns.codioart ';

    IF  NOT vAllGestCmd THEN
      sSelect := sSelect || ' INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = G.CODGEST::varchar AND TMP.FILTRU = ''CODGESTSTOC'' ';
    END IF;

    sSelect := sSelect || '
        LEFT  JOIN NIRSER NSE ON NS.CODNIRSTOC = NSE.CODNIRSTOC
        LEFT  JOIN NSERII SER ON SER.CODSERIE  = NSE.CODSERIE
      WHERE N.OPERAT = 1 AND coalesce(N.ANULAT,0) = 0
        AND io.mg &lt;&gt; 5 ) A7_PG
    GROUP BY codobiect, codgest, serie, tg';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);

    sSelect := '
    INSERT INTO TMP_PLANIFSTOC (CODOBIECT, CANT, CODGEST, FILTRU)
    SELECT codobiect, sum(CANT), codgest, ''STOCINI''
    FROM TMP_PLANIFSTOC
    WHERE FILTRU = ''SG''
    GROUP BY codobiect, codgest';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);

    sSelect := '
    INSERT INTO TMP_PLANIFSTOC (CODOBIECT, CANT, CODGEST, FILTRU)
    SELECT DISTINCT codobiect, 0, codgest, ''INTRARI''
    FROM TMP_PLANIFSTOC
    WHERE FILTRU = ''SG'' ';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);

    sSelect := '
    INSERT INTO TMP_PLANIFSTOC (CODOBIECT, CANT, CODGEST, FILTRU)
    SELECT DISTINCT codobiect, 0, codgest, ''IES''
    FROM TMP_PLANIFSTOC
    WHERE FILTRU = ''SG'' ';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);

    sSelect := '
    INSERT INTO TMP_PLANIFSTOC (CODOBIECT, CANT, CODGEST, FILTRU)
    SELECT DISTINCT codobiect, 0, codgest, ''IES0''
    FROM TMP_PLANIFSTOC
    WHERE FILTRU = ''SG'' ';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
  END IF;

  DROP INDEX IF EXISTS tmp_planifstoc_idxaa;
  CREATE INDEX tmp_planifstoc_idxaa ON tmp_planifstoc(filtru);

  INSERT INTO tmp_planifstoc(codobiect, tg, cant, serie, codgest, filtru)
  SELECT tmp.codobiect, tgcursor.tg, cantcursor.cant, sercursor.serie, tmp.codgest, 'SERTG'
  FROM (
        SELECT  DISTINCT codobiect, codgest
        FROM tmp_planifstoc
        WHERE filtru = 'SG'
       )   tmp
          LEFT JOIN (
                      SELECT STRING_AGG(tg,',') TG, codobiect, codgest
                      FROM (SELECT  DISTINCT tg, codobiect, codgest FROM tmp_planifstoc WHERE filtru = 'SG') C_PG
                      GROUP BY codobiect, codgest
                    ) tgcursor ON  tgcursor.codobiect = tmp.codobiect and  tmp.codgest = tgcursor.codgest
          LEFT JOIN (  SELECT STRING_AGG(serie,',') SERIE, codobiect, codgest
                       FROM (SELECT  DISTINCT serie, codobiect, codgest FROM tmp_planifstoc WHERE filtru = 'SG') D_PG
                      GROUP BY codobiect, codgest
                    ) sercursor ON  sercursor.codobiect = tmp.codobiect and  tmp.codgest = sercursor.codgest
          LEFT JOIN (  SELECT sum(cant) CANT, codobiect, codgest
                      FROM tmp_planifstoc
                      WHERE filtru = 'SG'
                      GROUP BY codobiect, codgest
                    ) cantcursor ON  cantcursor.codobiect = tmp.codobiect and  tmp.codgest = cantcursor.codgest;

  sInsert := 'INSERT INTO ' || tmpName || '(
     Articol,
     UM,
     Clasa,
     GestCmd,
     Masa,
     CODINTERN,
     CODEXTERN,
     StocIni,
     StocBlocat,
     CantAcc,
     Rest,
     CantIes,
     Intrari,
     StocFin,
     Rez,
     Serie,
     TG,
     GestStoc,
     ParPalet,
     ParCutie
   ' || gUserFields || ')';

  sSelect := '
  WITH
    CC AS (
      SELECT C1.CodObiect,
        SUM(C1.CantComandat) CantC,
        SUM(C1.CantAcceptat) CantA,
        SUM(C1.RestAcceptat) RestA,
        C1.GESTACT CODGEST,
        CMDSERTG.REST
      FROM COMANDA1 C1
           INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
           INNER JOIN TMP_GESTCMD GESTCMD ON C1.GESTACT = GESTCMD.CODGEST AND GESTCMD.CODOBIECT = C1.CODOBIECT
           LEFT  JOIN (SELECT C1.CODCOMANDA1, SUM(R.REST) REST
                       FROM REZERVATS R
                            INNER JOIN COMANDA1 C1 ON R.CODCOMANDA1 = C1.CODCOMANDA1
                            INNER JOIN COMANDA  C  ON C.CODCOMANDA  = C1.CODCOMANDA
                            INNER JOIN NIRSTOC  NS ON NS.CODNIRSTOC = R.CODNIRSTOC
                            INNER JOIN NIR         ON NS.CODNIR     = NIR.CODNIR' || coalesce(chr(13),'');

  IF  NOT vAllGestStoc THEN
    sSelect := sSelect || '   INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = NIR.GEST::varchar AND TMP.FILTRU = ''CODGESTSTOC'' ' || coalesce(chr(13),'');
  END IF;

  sSelect := sSelect ||
                       ' WHERE coalesce(C.INCHISA, 0) = 0
                             AND C.Operat = 1 AND coalesce(C.Anulat, 0) = 0 AND C.TipDoc = 18 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || coalesce(chr(13),'');

  IF  NOT vNoTermen THEN
    sSelect := sSelect || '    AND C1.TERMEN BETWEEN ''' || vDataStart::varchar || ''' AND ''' || vDataFin::varchar || '''' || coalesce(chr(13),'');
  END IF;

  sSelect := sSelect || 'GROUP BY C1.CODCOMANDA1) CMDSERTG ON C1.CODCOMANDA1 = CMDSERTG.CODCOMANDA1
      WHERE coalesce(C.INCHISA, 0) = 0
        AND C.Operat = 1 AND coalesce(C.Anulat, 0) &lt;&gt; 1 AND C.TipDoc = 18 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || '
        AND C1.TERMEN BETWEEN ''' || vDataStart::varchar || ''' AND ''' || vDataFin::varchar || '''
      GROUP BY C1.CodObiect, C1.GESTACT, CMDSERTG.REST),
    STOCBLOCAT AS (
      SELECT SUM(NSE.REST) CANT, NS.CODOBIECT, GESTCMD.CODGEST
      FROM NIRSER NSE
           INNER JOIN NIRSTOC     NS      ON NSE.CODNIRSTOC  = NS.CODNIRSTOC
           INNER JOIN NIR                 ON NIR.CODNIR      = NS.CODNIR
           INNER JOIN TMP_GESTCMD GESTCMD ON GESTCMD.CODGEST = NIR.GEST AND GESTCMD.CODOBIECT = NS.CODOBIECT
      WHERE NSE.STARE = 4
      GROUP BY NS.CODOBIECT, GESTCMD.CODGEST
      )
  SELECT
    OBJ.DENUMIRE,
    NUM.DEN_UM,
    CA.DEN_CLASEA,
    GestCmd.DEN_GEST,
    coalesce(OBJ.Masa,0),
    OBJ.CODINTERN,
    OBJ.CODEXTERN,
    coalesce(SI.CANT,0),
    coalesce(StocBlocat.CANT,0),
    coalesce(CC.CantA,0),
    coalesce(CC.RestA,0),
    coalesce(IES.Cant,0),
    coalesce(INTR.Cant,0),
    CASE
      WHEN coalesce(SI.CANT,0) + coalesce(INTR.Cant,0) - coalesce(IES.Cant,0) &lt; 0 THEN 0
      ELSE coalesce(SI.CANT,0) + coalesce(INTR.Cant,0) - coalesce(IES.Cant,0)
    END,
    CC.REST,
    SERTG.SERIE,
    SERTG.TG,
    GestCmd.DEN_GEST,
    PKG_LIST_BASE_PLANIFSTOC_GETPARBYCODEXTERN(''PALET'', OBJ.CODOBIECT),
    PKG_LIST_BASE_PLANIFSTOC_GETPARBYCODEXTERN(''CUTIE'', OBJ.CODOBIECT) ' || gUserAlias || '
  FROM TMP_GESTCMD GESTCMD
    INNER JOIN CC                   ON CC.CODGEST           = GESTCMD.CODGEST AND CC.CODOBIECT = GESTCMD.CODOBIECT
    INNER JOIN NARTOBJ OBJ          ON CC.CODOBIECT         = OBJ.CODOBIECT
    INNER JOIN NART NA              ON NA.CODARTICOL        = OBJ.CODARTICOL
    INNER JOIN NUM                  ON NUM.CODUM            = NA.UM
    LEFT  JOIN NCLASEA CA           ON CA.CODCLASEA         = NA.CLASA
    LEFT  JOIN TMP_PLANIFSTOC SI    ON GESTCMD.CODGEST      = SI.CODGEST    AND SI.CODOBIECT       = OBJ.CODOBIECT AND SI.FILTRU    = ''STOCINI''
    LEFT  JOIN TMP_PLANIFSTOC INTR  ON GESTCMD.CODGEST      = INTR.CODGEST  AND INTR.CODOBIECT     = OBJ.CODOBIECT AND INTR.FILTRU  = ''INTRARI''
    LEFT  JOIN TMP_PLANIFSTOC IES   ON IES.CODOBIECT        = OBJ.CODOBIECT AND GESTCMD.CODGEST    = IES.CODGEST   AND IES.FILTRU   = ''IES''
    LEFT  JOIN TMP_PLANIFSTOC SERTG ON SERTG.CODOBIECT      = OBJ.CODOBIECT AND GESTCMD.CODGEST    = SERTG.CODGEST AND SERTG.FILTRU = ''SERTG''
    LEFT  JOIN STOCBLOCAT           ON STOCBLOCAT.CODOBIECT = OBJ.CODOBIECT AND STOCBLOCAT.CODGEST = GESTCMD.CODGEST ' || gSuplJoins || '
  WHERE
    coalesce(na.tiparticol,0::varchar) = 0::varchar and
    (coalesce(SI.CANT,0) &lt;&gt; 0 OR
     coalesce(INTR.CANT,0) &lt;&gt; 0 OR
     coalesce(StocBlocat.CANT,0) &lt;&gt; 0 OR
     coalesce(CC.CantA,0) &lt;&gt; 0 OR
     coalesce(CC.RestA,0) &lt;&gt; 0 OR
     coalesce(IES.Cant,0) &lt;&gt; 0) ';

  IF vAllGestCmd THEN
    sSelect1 := '
    WITH
      CC AS (
        SELECT C1.CodObiect,
          SUM(C1.CantComandat) CantC,
          SUM(C1.CantAcceptat) CantA,
          SUM(C1.RestAcceptat) RestA,
          CMDSERTG.REST
        FROM COMANDA1 C1
             INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda
             LEFT  JOIN (SELECT C1.CODCOMANDA1, SUM(R.REST) REST
                         FROM REZERVATS R
                              INNER JOIN COMANDA1 C1 ON R.CODCOMANDA1 = C1.CODCOMANDA1
                              INNER JOIN COMANDA  C  ON C.CODCOMANDA  = C1.CODCOMANDA
                              INNER JOIN NIRSTOC  NS ON NS.CODNIRSTOC = R.CODNIRSTOC
                              INNER JOIN NIR         ON NS.CODNIR     = NIR.CODNIR' || coalesce(chr(13),'');

    IF  NOT vAllGestStoc THEN
      sSelect1 := sSelect1 || ' INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = NIR.GEST::varchar AND TMP.FILTRU = ''CODGESTSTOC'' ' || coalesce(chr(13),'');
    END IF;

    sSelect1 := sSelect1 || 'WHERE coalesce(C.INCHISA, 0) = 0
                               AND C.Operat = 1 AND coalesce(C.Anulat, 0) = 0 AND C.TipDoc = 18 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || coalesce(chr(13),'');

    IF  NOT vNoTermen THEN
      sSelect1 := sSelect1 || '  AND C1.TERMEN BETWEEN ''' || vDataStart::varchar || ''' AND ''' || vDataFin::varchar || '''' || coalesce(chr(13),'');
    END IF;

    sSelect1 := sSelect1 || 'GROUP BY C1.CODCOMANDA1) CMDSERTG ON C1.CODCOMANDA1 = CMDSERTG.CODCOMANDA1
        WHERE coalesce(C.INCHISA, 0) = 0
              AND C.Operat = 1 AND coalesce(C.Anulat, 0) &lt;&gt; 1 AND C.TipDoc = 18 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || '
              AND C1.TERMEN BETWEEN ''' || vDataStart::varchar || ''' AND ''' || vDataFin::varchar || '''
              and not exists (select gestcmd.codgest from tmp_gestcmd gestcmd where gestcmd.codgest = c1.gestact AND GESTCMD.CODOBIECT = C1.CODOBIECT)
        GROUP BY C1.CodObiect, CMDSERTG.REST),
      STOCBLOCAT AS (
      SELECT SUM(NSE.REST) CANT, NS.CODOBIECT, GESTCMD.CODGEST
      FROM NIRSER NSE
           INNER JOIN NIRSTOC     NS      ON NSE.CODNIRSTOC  = NS.CODNIRSTOC
           INNER JOIN NIR                 ON NIR.CODNIR      = NS.CODNIR
           INNER JOIN TMP_GESTCMD GESTCMD ON GESTCMD.CODGEST = NIR.GEST AND GESTCMD.CODOBIECT = NS.CODOBIECT
      WHERE NSE.STARE = 4
      GROUP BY NS.CODOBIECT, GESTCMD.CODGEST
      )
    SELECT
      OBJ.DENUMIRE,
      NUM.DEN_UM,
      CA.DEN_CLASEA,
      ''...nedefinita...'',
      coalesce(OBJ.Masa,0),
      OBJ.CODINTERN,
      OBJ.CODEXTERN,
      coalesce(SI.CANT,0),
      coalesce(StocBlc.CANT,0),
      coalesce(CC.CantA,0),
      coalesce(CC.RestA,0),
      coalesce(IES.Cant,0),
      coalesce(INTR.Cant,0),
      CASE
        WHEN coalesce(SI.CANT,0) + coalesce(INTR.Cant,0) - coalesce(IES.Cant,0) &lt; 0 THEN 0
        ELSE coalesce(SI.CANT,0) + coalesce(INTR.Cant,0) - coalesce(IES.Cant,0)
      END,
      CC.REST,
      SERTG.SERIE,
      SERTG.TG,
      GI.DEN_GEST,
      PKG_LIST_BASE_PLANIFSTOC_GETPARBYCODEXTERN(''PALET'', OBJ.CODOBIECT),
      PKG_LIST_BASE_PLANIFSTOC_GETPARBYCODEXTERN(''CUTIE'', OBJ.CODOBIECT) ' || gUserAlias || '
    FROM (SELECT OBJ.CODOBIECT, G.CODGEST FROM NARTOBJ OBJ, NGEST G WHERE OBJ.CODOBIECT &gt; 0 AND G.CODGEST &gt; 0) OBJGEST
      INNER JOIN NGEST GI ON GI.CODGEST = OBJGEST.CODGEST';

    IF  NOT vAllGestStoc THEN
      sSelect1 := sSelect1 || '
        INNER JOIN TMP_MANEVRA_LISTE TMP ON TMP.VALOARE = GI.CODGEST::varchar AND TMP.FILTRU = ''CODGESTSTOC'' ';
    END IF;

    sSelect1 := sSelect1 || '
      INNER JOIN NARTOBJ OBJ          ON OBJ.CODOBIECT   = OBJGEST.CODOBIECT
      INNER JOIN NART NA              ON NA.CODARTICOL   = OBJ.CODARTICOL
      INNER JOIN NUM                  ON NUM.CODUM       = NA.UM
      LEFT  JOIN CC                   ON CC.CODOBIECT    = OBJ.CODOBIECT
      LEFT  JOIN NCLASEA CA           ON CA.CODCLASEA    = NA.CLASA
      LEFT  JOIN TMP_PLANIFSTOC IES   ON IES.CODOBIECT   = OBJGEST.CODOBIECT AND IES.CODGEST = OBJGEST.CODGEST AND IES.FILTRU   = ''IES0''
      LEFT  JOIN TMP_PLANIFSTOC SERTG ON SERTG.CODOBIECT = OBJ.CODOBIECT     AND GI.CODGEST  = SERTG.CODGEST   AND SERTG.FILTRU = ''SERTG''
      LEFT  JOIN (SELECT TMP.CANT, TMP.CODOBIECT, TMP.CODGEST
                  FROM TMP_PLANIFSTOC TMP ';

    IF  NOT vAllGestStoc THEN
      sSelect1 := sSelect1 || '
                       INNER JOIN TMP_MANEVRA_LISTE TM ON TMP.CODGEST::varchar = TM.VALOARE AND TM.FILTRU = ''CODGESTSTOC'' ';
    END IF;

    sSelect1 := sSelect1 || '
                  WHERE TMP.FILTRU = ''STOCINI''
                 ) SI ON SI.CODOBIECT = OBJ.CODOBIECT AND GI.CODGEST = SI.CODGEST
       LEFT  JOIN (SELECT TMP.CANT, TMP.CODOBIECT, TMP.CODGEST
                  FROM TMP_PLANIFSTOC TMP ';

    IF  NOT vAllGestStoc THEN
      sSelect1 := sSelect1 || '
                       INNER JOIN TMP_MANEVRA_LISTE TM ON TMP.CODGEST::varchar = TM.VALOARE AND TM.FILTRU = ''CODGESTSTOC'' ';
    END IF;

    sSelect1 := sSelect1 || '
                  WHERE TMP.FILTRU = ''INTRARI''
                 ) INTR ON INTR.CODOBIECT = OBJ.CODOBIECT AND GI.CODGEST = INTR.CODGEST
      LEFT  JOIN (SELECT SUM(CANT) CANT,CODOBIECT, CODGEST FROM STOCBLOCAT GROUP BY CODOBIECT,CODGEST ) STOCBLC ON STOCBLC.CODOBIECT = OBJ.CODOBIECT AND STOCBLC.CODGEST = GI.CODGEST
      ' || gSuplJoins || '
    WHERE
      coalesce(na.tiparticol,0::varchar) = 0::varchar and
      (coalesce(SI.CANT,0) &lt;&gt; 0 OR
       coalesce(INTR.CANT,0) &lt;&gt; 0 OR
       coalesce(CC.CantA,0) &lt;&gt; 0 OR
       coalesce(CC.RestA,0) &lt;&gt; 0 OR
       coalesce(IES.Cant,0) &lt;&gt; 0) AND coalesce(GI.CODGEST,0) &gt; 0';
  END IF;

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

  IF vAllGestCmd THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect1, aListID, aListVer);
    sSelect := 'delete from ' || tmpName || ' where CantAcc = 0 and GestCmd = ''...nedefinita...'' ';
    EXECUTE sSelect;
  END IF;

  DROP INDEX IF EXISTS tmp_planifstoc_idxaa;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regevfisc_add_list_params</obj_name>
  <obj_hashval>d20a97f69da9a670b9afaafc0f0a77dd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regevfisc_add_list_params()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC   RECORD;
  aCont   numeric;
  aRulaj   numeric;
BEGIN
  --Adina 01 octombrie 2020
  aCont := (fnc_GetValConstanta('CCheltImpProfit', getANLUCRU(), getlunalucru()))::numeric;

  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN (SELECT   TIPPROFIT, TIPAN, ELEMSIMVENIT, ELEMSIMCHELT, DEDUCERI, DEDREZLEG, DEDPROFITR, DEDALTE, CHELTAFVENIT, CHELTPRADM,
                        CHELTPRNEDED, PIERDERE, PROFITCONTA, PROFITIMPOZ, SUMAMAX, CHELTSPONSOR, IMPOZITPROFIT, IMPOZITPROFITD, AN, TRIMESTRU,
                        TOTALRULAJV, TOTALVENITURI, TOTALSUMEV, TOTALRULAJC, TOTALCHELT, TOTALSUMEC, OBS, SUBUNITATEA, AMOFISC, CHELTDOBPREC,
                        PROVFISC, CREDITFISCEXT, IMPPROFREINV, ALTESCUTIRI, CIFRAAFACERI, s.den_subunit, CREDITFISCAL, IMPOZITPROFITC, IMPPROFDIF,
                        ANGENERARE, LUNAGENERARE, SPONSORREPORT,
                        fnc_GetValConstanta('ProcImpProfit', getANLUCRU(), getlunalucru()) PRODIMPPROFIT
                FROM   dprofit d
                      LEFT JOIN nsubunit s ON  d.subunitatea = s.codsubunit
                WHERE coddprofit = current_setting('PKG_LIST_BASE_REGEVFISC.vCodDProfit', true)::numeric
               )
  LOOP
    IF  v_rec.tipprofit = 1 THEN
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Tip',                                         'Trimestrial');
    ELSE
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Tip',                                         'Anual');
    END IF;

    PERFORM pkg_list_Struct_ADAUGA_PARAM('Elemente similare veniturilor',                 TO_CHAR(v_rec.ELEMSIMVENIT,   'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Elemente similare cheltuielilor',               TO_CHAR(v_rec.ELEMSIMCHELT,   'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Deduceri fiscale',                               TO_CHAR(v_rec.DEDUCERI,       'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Rezerva legala deductibila',                     TO_CHAR(v_rec.DEDREZLEG,      'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Profit scutit',                                 TO_CHAR(v_rec.DEDPROFITR,     'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Alte sume deductibile',                         TO_CHAR(v_rec.DEDALTE,        'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Cheltuieli aferente veniturilor neimpozabile',   TO_CHAR(v_rec.CHELTAFVENIT,   'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Cheltuieli protocol admise',                     TO_CHAR(v_rec.CHELTPRADM,     'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Cheltuieli protocol nedeductibile',             TO_CHAR(v_rec.CHELTPRNEDED,   'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Pierdere din anii precedenti',                   TO_CHAR(v_rec.PIERDERE,       'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Profit contabil',                               TO_CHAR(v_rec.PROFITCONTA,    'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Profit impozabil',                               TO_CHAR(v_rec.PROFITIMPOZ,    'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Suma maxima deductibila',                       TO_CHAR(v_rec.SUMAMAX,        'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Cheltuieli sponsorizari deductibile',           TO_CHAR(v_rec.CHELTSPONSOR,   'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Impozit pe profit',                             TO_CHAR(v_rec.IMPOZITPROFIT,  'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Impozit pe profit declarat',                     TO_CHAR(v_rec.IMPOZITPROFITD, 'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('An',                                             v_rec.An::varchar);

    IF  v_rec.tipprofit = 1 THEN
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Trimestru',                                   v_rec.trimestru::varchar);
    ELSE
      PERFORM pkg_list_Struct_ADAUGA_PARAM('Trimestru',                                   '');
    END IF;

    PERFORM pkg_list_Struct_ADAUGA_PARAM('Observatii',                                     v_rec.OBS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Subunitatea',                                   v_rec.den_subunit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Amortizare fiscala',                             TO_CHAR(v_rec.AMOFISC,         'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Cheltuieli cu dobanzile',                       TO_CHAR(v_rec.CHELTDOBPREC,   'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Provizioane fiscale',                           TO_CHAR(v_rec.PROVFISC,       'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Credit fiscal extern',                           TO_CHAR(v_rec.CREDITFISCEXT,   'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Impozit pe profit scutit',                       TO_CHAR(v_rec.IMPPROFREINV,   'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Alte scutiri si reduceri',                       TO_CHAR(v_rec.ALTESCUTIRI,     'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Cifra de afaceri',                               TO_CHAR(v_rec.CIFRAAFACERI,   'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Credit fiscal',                                 TO_CHAR(v_rec.CREDITFISCAL,   'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Impozit profit contabilizat anterior',           TO_CHAR(v_rec.IMPOZITPROFITC, 'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Impozit pe profit inainte de scaderea sumelor', TO_CHAR(v_rec.IMPPROFDIF,     'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Suma din spons. reportata',                     TO_CHAR(v_rec.SPONSORREPORT,   'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Procent impozit pe profit',                     v_rec.ProdImpProfit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Total venituri',                                 TO_CHAR(v_rec.TotalRulajV,     'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Total cheltuieli',                               TO_CHAR(v_rec.TotalRulajC,     'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Venituri neimpozabile',                         TO_CHAR(v_rec.TotalVenituri,   'fm9G999G999G990D0099'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Cheltuieli nedeductibile',                       TO_CHAR(v_rec.TotalChelt,     'fm9G999G999G990D0099'));
    EXIT ;
  END LOOP;

  aRulaj := 0;

  BEGIN
    SELECT sum(coalesce(rulaj, 0)) INTO aRulaj FROM dprofitc WHERE codcont = aCont;
  EXCEPTION WHEN others THEN
    aRulaj := 0;
  END;

  PERFORM pkg_list_Struct_ADAUGA_PARAM('Cheltuieli impozit profit(rulaj)',                 TO_CHAR(aRulaj, 'fm9G999G999G990D0099'));
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_processlist</obj_name>
  <obj_hashval>b0462fbe4f6603d77e5c4a1fa40018e2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vInsert     varchar := '';
  vInsSTOCREAL  varchar := '';
  vInsSTOCPER   varchar := '';
  vInsSTOCREZ   varchar := '';
  vInsSTOCCOM   varchar := '';
  vInsIES_PER   varchar := '';
  vInsFaraIES_PER varchar := '';
  vInsLAST_NS   varchar := '';
  vItemSGest    varchar := ' ,NULL GEST, NULL CODLOCATIE';
  vItemGGest    varchar := '';
  vZile       NUMERIC := to_date(to_char(current_setting('PKG_LIST_BASE_STOCEP.vDataFin',true)::date, 'dd.mm.yyyy'),'dd.mm.yyyy') - to_date(to_char(current_setting('PKG_LIST_BASE_STOCEP.vDataIni',true)::date, 'dd.mm.yyyy'),'dd.mm.yyyy') + 1;
  vSelIoArt     varchar := '';
  vFromIes_Per  varchar := '';
  vJoin       varchar := '';
  vWhere      varchar := '';
  vCateGest     NUMERIC;
  vCateLGest    NUMERIC;
  sColMinMax    varchar := ', NAOS.STOCMIN, NAOS.STOCMED, NAOS.STOCMAX';
  sUltNirstoc   varchar := '';
  gSuplCols     VARCHAR := 'NARTOBJ NAO, NART NA, NARTOBJSUBUNIT NAOS, NUM NUM, NPART PROD, NCLASEA NCA, NIRSTOC UNS';
  gUserFields   VARCHAR := '';
  gUserAlias    VARCHAR := '';
  gNullAlias    VARCHAR := '';
  gSuplJoins    VARCHAR := '';
  vToataFirma   boolean := current_setting('PKG_LIST_BASE_STOCEP.vToataFirma',true)::boolean;
  vToateGest    boolean := current_setting('PKG_LIST_BASE_STOCEP.vToateGest', true)::boolean;
  vToateArt     boolean := current_setting('PKG_LIST_BASE_STOCEP.vToateArt', true)::boolean;
  vTipMedie   NUMERIC := current_setting('PKG_LIST_BASE_STOCEP.vTipMedie',  true)::numeric;
  vUltAchiz   boolean := current_setting('PKG_LIST_BASE_STOCEP.vUltAchiz',  true)::boolean;
  vInclEpuiz    boolean := current_setting('PKG_LIST_BASE_STOCEP.vInclEpuiz', true)::boolean;
BEGIN
  --Florin 28.09.2022 - fixat 55716
  --Florin 27.07.2022 - sinc. Oracle (22.07.2022)
  --Laura 02.11.2021 - sinc Oracle (12.11.2021)
  --Laura 21.10.2021 - sinc Oracle (20.10.2021)
  --Laura 13.10.2021 - sinc Oracle (13.10.2021)
  --Adina 20.04.2021 - sinc.Oracle
  --Adina iulie + 03 septembrie 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NAO.CODOBIECT',NULL,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = NAO.CODOBIECT',NULL,NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_STOCEP.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  IF  GETSUBUNITATE() = 1 THEN
    sColMinMax := ', NAO.STOCMIN, NAO.STOCMED, NAO.STOCMAX';
  END IF;

  IF NOT vToataFirma THEN
    IF vToateArt THEN
        vItemSGest := ' ,N.GEST, NULL::numeric';
        vItemGGest := ' ,N.GEST, NULL::numeric';
      ELSE
      vItemSGest := ' ,N.GEST, coalesce(NS.CODLOCATIE,0)::numeric CODLOCATIE';
      vItemGGest := ' ,N.GEST, coalesce(NS.CODLOCATIE,0)::numeric';
    END IF;
  END IF;

  vWhere := '
  WHERE NOT NS.CODIOART IN (SELECT DISTINCT CODIOART FROM IOART1 WHERE MG = 5)' || PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG', 'CODSUBUNIT', '
    AND',NULL);

  IF  NOT vToateGest THEN
    SELECT COUNT( 1) INTO vCateGest  FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODGEST';
    if vToateArt then
        vCateLGest := 0;
      ELSE
      SELECT COUNT( 1) INTO vCateLGest FROM TMP_MANEVRA_LISTE WHERE FILTRU = 'CODLOCATIE';
    END IF;
  END IF;

  IF vToateGest THEN
    NULL;
  ELSIF vCateLGest = 0 THEN
    vWhere := vWhere || '
    AND N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
  ELSE
    vWhere := vWhere || '
    AND (N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') OR NS.CODLOCATIE::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'')) ';
  END IF;

  vInsSTOCREAL := 'INSERT INTO TMP_LST_STOCEP_STOCREAL(CODOBIECT, GEST, CODLOCATIE, CANT, VALTOTIN)
  SELECT NS.CODOBIECT' || vItemSGest || ', SUM(NS.REST) CANT, SUM(NS.REST * (NS.PRET - NS.ADAOS)) ValTotIn
  FROM NIRSTOC NS
    INNER JOIN NIR   N  ON N.CODNIR   = NS.CODNIR
    INNER JOIN NGEST NG ON NG.CODGEST = N.GEST' || pkg_list_base_stocep_getJoinFilterArt('NS') ||
  vWhere || pkg_list_base_stocep_getWhereFilterArt('NS') || '
  GROUP BY NS.CODOBIECT' || vItemGGest;

  vInsSTOCPER := 'INSERT INTO TMP_LST_STOCEP_STOCPER(CODOBIECT, GEST, CODLOCATIE, STOCFIN, PZISTOC, UZISTOC)
  SELECT
    NS.CODOBIECT' || vItemSGest || ', SUM(ns.cantnir - coalesce(lp.iestot,0)) stocfin,
    CASE
      WHEN SUM(case when n.datanir &lt; ' || current_setting('PKG_LIST_BASE_STOCEP.sDataIni',true) || ' then ns.cantnir else 0 end) - sum (coalesce(lp.iesprec,0)) = 0
      THEN MIN(CASE WHEN N.DATANIR &gt;= ' || current_setting('PKG_LIST_BASE_STOCEP.sDataIni',true) || ' THEN (N.DATANIR + 1 - ' || current_setting('PKG_LIST_BASE_STOCEP.sDataIni',true) || ') ELSE ' || vZile::varchar || ' END)
      ELSE 1
    END PZISTOC,
    CASE
      WHEN SUM(ns.cantnir - coalesce(lp.iestot,0)) = 0
      THEN MAX(CASE WHEN coalesce(lp.ultimalivr,' || current_setting('PKG_LIST_BASE_STOCEP.sDataIni',true) || ') &lt;= ' || current_setting('PKG_LIST_BASE_STOCEP.sDataIni',true) || ' THEN 1 ELSE (lp.ultimalivr + 1 - ' || current_setting('PKG_LIST_BASE_STOCEP.sDataIni',true) || ')  END)
      ELSE ' || vZile || '
    END UZISTOC
  FROM NIRSTOC NS
    INNER JOIN NIR   N  ON N.CODNIR   = NS.CODNIR
    INNER JOIN NGEST NG ON NG.CODGEST = N.GEST
    LEFT JOIN (
      SELECT
        l1.codnirstoc,
        sum (case when l.datalivr &lt; ' || current_setting('PKG_LIST_BASE_STOCEP.sDataIni',true) || ' then l1.cant*(case when l.tiplivr=15 then -1 else 1 end) else 0 end) iesprec,
        sum (l1.cant* (case when l.tiplivr=15 then -1 else 1 end)) iestot, max(l.datalivr) ultimalivr
      FROM livr l INNER JOIN livr1 l1 ON l1.codlivr = l.codlivr
      WHERE L.DATALIVR &lt;= ' || current_setting('PKG_LIST_BASE_STOCEP.sDataFin',true) || '
      GROUP BY l1.codnirstoc
    ) lp ON lp.codnirstoc = ns.codnirstoc ' ||
    pkg_list_base_stocep_getJoinFilterArt('NS') ||
    vWhere|| pkg_list_base_stocep_getWhereFilterArt('NS') ||'
    AND n.datanir &lt;= ' || current_setting('PKG_LIST_BASE_STOCEP.sDataFin',true) || '
  GROUP BY NS.CODOBIECT' || vItemGGest;

  vFromIes_Per := '
  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   NG  ON NG.CODGEST    = N.GEST
    LEFT  JOIN NIRSTOC NSD ON NSD.CODLIVR1  = L1.CODLIVR1
    LEFT  JOIN IESIRI1 I1  ON I1.CODIES     = L.CODIES    AND I1.CODIES1    = L1.CODIES1
    LEFT  JOIN IESIRI  I   ON I.CODIES      = I1.CODIES
    LEFT  JOIN TRANSF1 T1  ON T1.CODTRANSF  = L.CODTRANSF AND T1.CODTRANSF1 = L1.CODIES1'
    || pkg_list_base_stocep_getJoinFilterArt('NS') ||
    vWhere|| pkg_list_base_stocep_getWhereFilterArt('NS') ||'
    AND L.TIPLIVR::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''TIPLIVR'')
    AND L.DATALIVR BETWEEN ' || current_setting('PKG_LIST_BASE_STOCEP.sDataIni',true) || ' AND ' || current_setting('PKG_LIST_BASE_STOCEP.sDataFin',true) || '
    AND (L.TIPLIVR &lt;&gt; 12 OR NSD.CODIOART IN (SELECT DISTINCT CODIOART FROM IOART1 WHERE MG = 5))  ';

  IF  vTipMedie = 2 THEN
    EXECUTE 'SELECT COUNT(DISTINCT L.DATALIVR) ' || vFromIes_Per INTO vZile;
  END IF;

  vInsIES_PER := 'INSERT INTO TMP_LST_STOCEP_IES_PER(CODOBIECT, GEST, CODLOCATIE, CANT, CANTAS, CANTT, VALTOTACH, VALTOTOUT)
  SELECT NS.CODOBIECT' || vItemSGest || ',
    SUM(L1.CANT) CANT, SUM((case when L.TIPLIVR=23 then L1.CANT else 0 end)) CANTAS, SUM((case when L.TIPLIVR=12 then L1.CANT else 0 end)) CANTT,
    SUM(L1.CANT * (NS.PRET - NS.ADAOS)) ValTotAch, SUM(case when coalesce(i.moneda,0) in (0,1) then 1 else i.curs end * (L1.CANT * coalesce(I1.PU,T1.PU) - case when i.tipdoc = 16 then l1.cant/i1.cant*i1.tva else 0 end)) ValTotOut ' || vFromIes_Per || '
  GROUP BY NS.CODOBIECT' || vItemGGest || '
  HAVING SUM(L1.CANT) &lt;&gt; 0';

  if vToateArt then
    IF NOT vToataFirma THEN
      vInsFaraIES_PER :=
      'INSERT INTO TMP_LST_STOCEP_IES_PER(CODOBIECT, GEST, CODLOCATIE, CANT, CANTAS, CANTT, VALTOTACH, VALTOTOUT)
    SELECT O.CODOBIECT, TMP.GEST, 0, 0, 0, 0, 0, 0
    FROM NARTOBJ O
      LEFT JOIN TMP_LST_STOCEP_STOCREAL TMP ON TMP.CODOBIECT = O.CODOBIECT '
      || pkg_list_base_stocep_getJoinFilterArt('O') ||
      ' WHERE NOT EXISTS (SELECT T.CODOBIECT FROM TMP_LST_STOCEP_IES_PER T WHERE T.CODOBIECT = O.CODOBIECT AND T.GEST = TMP.GEST) AND COALESCE(O.INACTIV,0) = 0 '
      || pkg_list_base_stocep_getWhereFilterArt('O');
  ELSE
      vInsFaraIES_PER :=
      'INSERT INTO TMP_LST_STOCEP_IES_PER(CODOBIECT, GEST, CODLOCATIE, CANT, CANTAS, CANTT, VALTOTACH, VALTOTOUT)
    SELECT O.CODOBIECT, 0, 0, 0, 0, 0, 0, 0
      FROM NARTOBJ O'
      || pkg_list_base_stocep_getJoinFilterArt('O') ||
      ' WHERE NOT EXISTS (SELECT T.CODOBIECT FROM TMP_LST_STOCEP_IES_PER T WHERE T.CODOBIECT = O.CODOBIECT) AND COALESCE(O.INACTIV,0) = 0'
      || pkg_list_base_stocep_getWhereFilterArt('O');
    end if;
  end if;

  vInsSTOCREZ := 'INSERT INTO TMP_LST_STOCEP_STOCREZ(CODOBIECT, REZERVAT)
    SELECT NS.CODOBIECT, SUM(R.REST) REZERVAT
    FROM REZERVATS R
      INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = R.CODNIRSTOC '
      || pkg_list_base_stocep_getJoinFilterArt('NS') ||
      ' WHERE coalesce(R.REST,0) &lt;&gt; 0 '
      || pkg_list_base_stocep_getWhereFilterArt('NS') ||
      ' GROUP BY NS.CODOBIECT';

  vInsSTOCCOM := 'INSERT INTO TMP_LST_STOCEP_STOCCOM(CODOBIECT, RESTCOM)
    SELECT C1.CODOBIECT, SUM(C1.RESTACCEPTAT) RestCom
    FROM COMANDA C INNER JOIN COMANDA1 C1 ON C1.CODCOMANDA = C.CODCOMANDA '
      || pkg_list_base_stocep_getJoinFilterArt('C1') ||
      ' WHERE coalesce(C1.RESTACCEPTAT,0) &lt;&gt; 0 AND C.TipDoc = 18 '
      || pkg_list_base_stocep_getWhereFilterArt('C1') ||
      ' GROUP BY C1.CODOBIECT';

  vInsLAST_NS := 'INSERT INTO TMP_LST_STOCEP_LAST_NS(CODOBIECT, CODNIRSTOC)';
  IF vUltAchiz THEN
    CALL PRC_AL_CHECK('NPART1');
    vInsLAST_NS := vInsLAST_NS || '
      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 )  as CODNIRSTOC
     FROM NIRSTOC NS'
    || pkg_list_base_stocep_getJoinFilterArt('NS') ||
     ' WHERE coalesce(NS.CODNIRSTOCPARINTE,0) = 0 '
    || pkg_list_base_stocep_getWhereFilterArt('NS');
  ELSE
    vInsLAST_NS := vInsLAST_NS || ' SELECT 0 CODOBIECT, 0 CODNIRSTOC ';
  END IF;

  IF vToataFirma THEN
    SELECT den_subunit INTO vItemSGest
    FROM nsubunit WHERE codsubunit = GETSUBUNITATE();

    vItemSGest := '''' || vItemSGest || ''', NULL';
    vJoin := '
    LEFT JOIN TMP_LST_STOCEP_STOCREAL SR ON SR.CODOBIECT = IP.CODOBIECT
    LEFT JOIN TMP_LST_STOCEP_STOCPER  SP ON SP.CODOBIECT = IP.CODOBIECT';
  ELSE
    IF vToateArt then
        vItemSGest := 'NG.DEN_GEST, NULL';
        vJoin      := '
      LEFT JOIN TMP_LST_STOCEP_STOCREAL SR ON SR.CODOBIECT = IP.CODOBIECT AND SR.GEST = IP.GEST
      LEFT JOIN TMP_LST_STOCEP_STOCPER  SP ON SP.CODOBIECT = IP.CODOBIECT AND SP.GEST = IP.GEST
      LEFT JOIN NGEST    NG ON NG.CODGEST    = IP.GEST';
    ELSE
      vItemSGest := 'NG.DEN_GEST, NL.DENUMIRE';
      vJoin := '
        LEFT JOIN TMP_LST_STOCEP_STOCREAL SR ON SR.CODOBIECT  = IP.CODOBIECT AND SR.GEST = IP.GEST AND SR.CODLOCATIE = IP.CODLOCATIE
        LEFT JOIN TMP_LST_STOCEP_STOCPER  SP ON SP.CODOBIECT  = IP.CODOBIECT AND SP.GEST = IP.GEST AND SP.CODLOCATIE = IP.CODLOCATIE
        LEFT JOIN NGEST                   NG ON NG.CODGEST    = IP.GEST
        LEFT JOIN NLOCATII                NL ON NL.CODLOCATIE = IP.CODLOCATIE';
      END IF;
  END IF;

  vInsert := 'INSERT INTO ' || tmpName || '(
    CodObiect, Gest, LGest, Articol, UM, Stoc, TotVanz, TotIesAS, TotIesT, Zile, MedieVanz,
    ZileLich, PmAchiz, PmVanzare,
    CodExtern, CodIntern, Producator, DurataMax, StocMin, StocMed, StocMax, ClasaA,
    StocFinPer, PZiStocPer, UZiStocPer, Rezervat, RestCom, UltFurn, UltPrAchiz, UltIOArt' || gUserFields || ')
  SELECT
    NAO.CodObiect, ' || vItemSGest || ', NAO.DENUMIRE, NUM.DEN_UM, SR.CANT, IP.CANT, IP.CANTAS, IP.CANTT, ' || vZile || ', (IP.CANT * ' || current_setting('PKG_LIST_BASE_STOCEP.vIndCrest',true) || ' / ' || vZile::varchar || ') MEDIEVANZ,
    CASE WHEN IP.CANT = 0 THEN 0 ELSE SR.CANT / (IP.CANT * ' || current_setting('PKG_LIST_BASE_STOCEP.vIndCrest',true) || ' / ' || vZile::varchar || ') END, CASE WHEN IP.CANT = 0 THEN 0 ELSE IP.VALTOTACH / IP.CANT END, CASE WHEN IP.CANT = 0 THEN 0 ELSE IP.VALTOTOUT / IP.CANT END,
    NAO.CODEXTERN, NAO.CODINTERN, PROD.DEN_PART PRODUCATOR, NAO.DURMAXAPROV' || sColMinMax || ', NCA.DEN_CLASEA,
    SP.STOCFIN, SP.PZISTOC, SP.UZISTOC, SREZ.REZERVAT, SCOM.RESTCOM, UF.DEN_PART, UNS.PRET - coalesce(UNS.ADAOS,0),IOLP.DEN_IOPART' || gUserAlias || '
  FROM TMP_LST_STOCEP_IES_PER IP
    INNER JOIN NARTOBJ NAO ON NAO.CODOBIECT = IP.CODOBIECT' ||
    vJoin || '
    LEFT JOIN TMP_LST_STOCEP_LAST_NS LNS  ON LNS.CODOBIECT  = NAO.CODOBIECT
    LEFT JOIN NIRSTOC                UNS  ON UNS.CODNIRSTOC = LNS.CODNIRSTOC
    LEFT JOIN NPART1                 PLST ON PLST.CODPART   = UNS.FURN AND EXTRACT(YEAR FROM UNS.DATAACHIZ)*12+EXTRACT(MONTH FROM UNS.DATAACHIZ) BETWEEN PLST.ALSTART AND PLST.ALSTOP
    LEFT JOIN IOPART                 IOLP ON IOLP.CODIOPART = PLST.CODIOPART
    LEFt JOIN NPART                  UF   ON UF.CODPART     = UNS.FURN
    LEFT JOIN TMP_LST_STOCEP_STOCREZ SREZ ON SREZ.CODOBIECT = NAO.CODOBIECT
    LEFT JOIN TMP_LST_STOCEP_STOCCOM SCOM ON SCOM.CODOBIECT = NAO.CODOBIECT
    LEFT 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 = ' || GETSUBUNITATE()::varchar || '
    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 NA.TIPARTICOL = 0::varchar';

  IF  NOT vInclEpuiz and not vToateArt THEN
    vInsert := vInsert || '
    AND SR.CANT &lt;&gt; 0';
  END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE( 'TRUNCATE TABLE TMP_LST_STOCEP_STOCREAL', aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE( 'TRUNCATE TABLE TMP_LST_STOCEP_STOCPER',  aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE( 'TRUNCATE TABLE TMP_LST_STOCEP_IES_PER',  aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE( 'TRUNCATE TABLE TMP_LST_STOCEP_STOCREZ',  aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE( 'TRUNCATE TABLE TMP_LST_STOCEP_STOCCOM',  aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE( 'TRUNCATE TABLE TMP_LST_STOCEP_LAST_NS',  aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE( vInsSTOCREAL, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE( vInsSTOCPER,  aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE( vInsSTOCREZ,  aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE( vInsSTOCCOM,  aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE( vInsIES_PER,  aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE( vInsLAST_NS,  aListID, aListVer);
  if vToateArt then
      PERFORM LIST_EXECUTE_IMMEDIATE(vInsFaraIES_PER,  aListID, aListVer);
    end if;
  PERFORM LIST_EXECUTE_IMMEDIATE( vInsert,      aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topfurnani_processlist</obj_name>
  <obj_hashval>2de0063b0f37b2ed0549b754d5b0b57b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topfurnani_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC         RECORD;
  sInsert       varchar := '';
  gSuplCols     VARCHAR := 'NPART P';
   gUserFields   VARCHAR := '';
  gUserAlias     VARCHAR := '';
  gNullAlias     VARCHAR := '';
  gSuplJoins     VARCHAR := '';
  sSQL           varchar := '';
  vLunaStart    NUMERIC(10);
  vLunaFin      NUMERIC(10);
BEGIN
  --Florin 17.01.2023 - fixat 56831
  --Florin 16.12.2022 - sinc. Oracle
  --Florin 09.08.2021 - sinc. Oracle (50677)
  --Adina 07 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_TOPFURNANI.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;
  vLunaStart := current_setting('pkg_list_base_topcliani.vLunaStart', TRUE);
  vLunaFin   := current_setting('pkg_list_base_topcliani.vLunaFin', TRUE);

  IF pkg_list_base_topcliani_TotiPart() THEN
    INSERT INTO tmp_manevra_liste(filtru, valoare)
    SELECT 'CODPART', codpart
    FROM npart
    WHERE codpart &gt; 0;
  END IF;

  delete from tmp_toppeani;
  IF  getSUBUNITATE() &gt; 1 THEN
    INSERT INTO tmp_toppeani(an, val, codpart)
    SELECT mana.valoare::numeric, G.ValTot_Val, manp.valoare::numeric
    FROM tmp_manevra_liste mana, tmp_manevra_liste manp,
         (SELECT SUM(S.ValTot_Val) VALTOT_VAL, S.An, S.Partener
          FROM (
                SELECT SUM(I.ValDoc) VALTOT_VAL, I.An, I.Partener
                FROM INTRARI I
                WHERE I.Subunitatea = getSUBUNITATE() AND I.TipDoc NOT IN (2, 3) AND  COALESCE(I.Anulat, 0) = 0
                AND  COALESCE(I.Initializari, 0) = 0 AND  I.Operat = 1
                AND I.Luna &gt;= vLunaStart AND I.Luna &lt;= vLunaFin
                GROUP BY I.An, I.Partener
                union ALL
                SELECT SUM(I.ValDoc) VALTOT_VAL, I.An, I.Partener
                FROM INTRARI I
                WHERE I.Subunitatea = current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric AND  I.TipDoc = 3 AND  COALESCE(I.Anulat, 0) = 0
                AND  COALESCE(I.Initializari, 0) = 0
                AND I.Luna &gt;= vLunaStart AND I.Luna &lt;= vLunaFin
                AND  I.Operat = 1
                GROUP BY I.An, I.Partener
               ) S
          GROUP BY S.An, S.Partener
         ) G
    WHERE mana.filtru = 'AN' and  manp.filtru = 'CODPART' AND  G.An = mana.valoare::numeric AND  G.Partener = manp.valoare::numeric;
  ELSE
    INSERT INTO tmp_toppeani(an, val, codpart)
    SELECT mana.valoare::numeric, G.ValTot_Val, manp.valoare::numeric
    FROM  tmp_manevra_liste mana, tmp_manevra_liste manp,
          ( SELECT SUM(S.ValTot_Val) VALTOT_VAL, S.An, S.Partener
            FROM (
                  SELECT SUM(I.ValDoc) VALTOT_VAL, I.An, I.Partener
                  FROM INTRARI I
                  WHERE I.TipDoc NOT IN (2, 3) AND  COALESCE(I.Anulat, 0) = 0 AND  COALESCE(I.Initializari, 0) = 0
                            AND I.Luna &gt;= vLunaStart AND I.Luna &lt;= vLunaFin
                  AND  I.Operat = 1
                  GROUP BY I.An, I.Partener
                  union ALL
                  SELECT SUM(I.ValDoc) VALTOT_VAL, I.An, I.Partener
                  FROM INTRARI I
                  WHERE I.TipDoc = 3 AND  COALESCE(I.Anulat, 0) = 0 AND  COALESCE(I.Initializari, 0) = 0
                  AND I.Luna &gt;= vLunaStart AND I.Luna &lt;= vLunaFin
                  AND  I.Operat = 1
                  GROUP BY I.An, I.Partener
                 ) S
            GROUP BY S.An, S.Partener
          ) G
    WHERE mana.filtru = 'AN' and  manp.filtru = 'CODPART' AND  G.An = mana.valoare::numeric AND  G.Partener = manp.valoare::numeric;
  END IF;

  sInsert :=  ' insert into ' || tmpName || ' (CodPart, Den_Part' || gUserFields || ') ' ||
              ' select man.valoare::numeric, p.den_part ' || gUserAlias ||
              ' from tmp_manevra_liste man ' ||
              '      inner join npart p on man.valoare::numeric = p.codpart ' || gSuplJoins ||
              ' where man.filtru = ''CODPART'' ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  FOR v_rec IN (SELECT an, COALESCE(val, 0) VAL, codpart FROM tmp_toppeani)
  LOOP
    sInsert :=   ' update ' || tmpName ||
                ' set ' ||
                '   AN' || coalesce(v_rec.an::varchar,'') || ' = ' ||replace((v_Rec.Val)::varchar, ',', '.') ||
                ' where CodPart = ' || coalesce(v_Rec.Codpart::varchar ,'');
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  END LOOP;


  sInsert :=  'DO LANGUAGE PLPGSQL $$ '|| coalesce(chr(13),'') ||
              'DECLARE v_rec record; ' || coalesce(chr(13),'') ||
              'begin ' || coalesce(chr(13),'') ||
              '  for v_rec in (select tmp.codpart, tp.val ' || coalesce(chr(13),'') ||
              '                from ' || tmpName || ' tmp ' || coalesce(chr(13),'') ||
              '                     left join (select sum(val) val, codpart from tmp_toppeani group by codpart) tp on tp.codpart = tmp.codpart ' || coalesce(chr(13),'') ||
              '               ) loop ' || coalesce(chr(13),'') ||
              '    if coalesce(v_rec.val,0) = 0 then ' || coalesce(chr(13),'') ||
              '      delete from ' || tmpName || ' where CodPart = v_rec.CodPart; ' || coalesce(chr(13),'') ||
              '    end if; ' || coalesce(chr(13),'') ||
              '  end loop;             ' || coalesce(chr(13),'') ||
              'END $$;';

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  sSQL := 'create temporary table TMP_AA as
            select tmp.codpart, tp.val
            from '|| tmpName || ' tmp
                    left join (select sum(val) val, codpart from tmp_toppeani group by codpart) tp on tp.codpart = tmp.codpart ';
  EXECUTE sSQL;
  FOR v_rec IN (SELECT * FROM TMP_AA) LOOP
    IF coalesce(v_rec.val,0) = 0 THEN
      sInsert := 'delete from '|| tmpName || ' where CodPart = '|| COALESCE(v_rec.CodPart::varchar,'') ;
      PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
    END IF;
  END LOOP;
  DROP TABLE TMP_AA;
  DELETE FROM tmp_toppeani;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_jurnvanz_setperioada</obj_name>
  <obj_hashval>140ac28770bbdf7d6a5de7c18a5fe7be</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_jurnvanz_setperioada(pan numeric, pluna numeric, ptip numeric, psubunit numeric, pexclnoeconomicactiv numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnLunaIni NUMERIC;
  vAnLunaFin NUMERIC := pAn * 12 + pLuna;
  vSubunit   NUMERIC := Coalesce(pSubunit, getsubunitate());
  vDataIni   DATE;
  vDataFin   DATE;
  vLunaIni   NUMERIC;
BEGIN
  --Florin 19.12.2012 - sinc. Oracle
  --Florin 19.08.2020
  --Florin 08.12.2020 - fixat #38200
  IF    pTip = 3/*anual      */ THEN vLunaIni := 1;
  ELSIF pTip = 2/*semestrial */ THEN vLunaIni := CASE WHEN pLuna &gt; 6 THEN 7 ELSE 1 END;
  ELSIF pTip = 1/*trimestrial*/ THEN vLunaIni := CASE WHEN pLuna &gt; 9 THEN 10 WHEN pLuna &gt; 6 THEN 7 WHEN pLuna &gt; 3 THEN 4 ELSE 1 END;
  ELSIF pTip = 0/*lunar      */ THEN vLunaIni := pLuna;
  END IF;
  vAnLunaIni := pAn * 12 + vLunaIni;
  vDataIni   := To_Date(To_Char(pAn,'fm0000')||'.'||To_Char(vLunaIni,'fm00'), 'yyyy.mm' );
  vDataFin   := Last_Day(To_Date(To_Char(pAn,'fm0000')||'.'||To_Char(pLuna,'fm00'), 'yyyy.mm' ));

  PERFORM set_config('PKG_LIST_BASE_JURNVANZ.vAnLista'  , pAn                 ::varchar, false);
  PERFORM set_config('PKG_LIST_BASE_JURNVANZ.vLunaLista', pLuna               ::varchar, false);
  PERFORM set_config('PKG_LIST_BASE_JURNVANZ.vAnLunaIni', vAnLunaIni          ::varchar, false);
  PERFORM set_config('PKG_LIST_BASE_JURNVANZ.vAnLunaFin', vAnLunaFin          ::varchar, false);
  PERFORM set_config('PKG_LIST_BASE_JURNVANZ.vTip'      , pTip                ::varchar, false);
  PERFORM set_config('PKG_LIST_BASE_JURNVANZ.vSubunit'  , vSubunit            ::varchar, false);
  PERFORM set_config('PKG_LIST_BASE_JURNVANZ.bExclNEA'  , pExclNoEconomicActiv::varchar, false);
  PERFORM set_config('PKG_LIST_BASE_JURNVANZ.vDataIni'  , to_char(vDataIni, 'dd.mm.yyyy')           , false);
  PERFORM set_config('PKG_LIST_BASE_JURNVANZ.vDataFin'  , to_char(vDataFin, 'dd.mm.yyyy')           , false);

  CALL UMPLE_TMP_AL_CURSLINIE(vAnLunaIni, vAnLunaFin);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_incfact_stingerevalida</obj_name>
  <obj_hashval>5c380f537a83e501920219334a299dfc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_incfact_stingerevalida(acoddoc numeric, atipdoc numeric)
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  semnif numeric;
begin
  --Bogdan 03.09.2020
  BEGIN
    SELECT semnificatie INTO semnif FROM GENERAL WHERE coddoc = acoddoc AND  tipdoc = atipdoc;
  EXCEPTION WHEN others THEN
      semnif := 600;
  END;
  IF  semnif &lt;&gt; 600 THEN
    return  1;
  ELSE
    return 0;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_inventar_rest_setrestaurant</obj_name>
  <obj_hashval>e5884c88030198ab8d1af716a355593a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_inventar_rest_setrestaurant(acodrestaurant numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 25 septembrie 2020
  perform set_config('PKG_LIST_BASE_INVENTAR_REST.vCodRestaurant',(aCodRestaurant)::varchar,false);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_lansetichete_get_nratrib</obj_name>
  <obj_hashval>96e970e65dc601ad9f52ea6e8c2c5a39</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_lansetichete_get_nratrib()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 13.10.2020
  RETURN current_setting('PKG_LIST_BASE_LANSETICHETE.vNrAtrib', true)::numeric;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_mariridimin_settiplista</obj_name>
  <obj_hashval>77327d5d67d78147bfddf0aa823b7f49</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_mariridimin_settiplista(p_tiplista numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.10.2020
  perform set_config('PKG_LIST_BASE_MARIRIDIMIN.vTipLista',(p_tipLista)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_matrcv_processlist</obj_name>
  <obj_hashval>f59d261a5afc7c3624e8176920fdbc75</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_matrcv_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 := '';

  sInsTmp  varchar;
  sInsert  varchar;
  vCVenitN numeric;
  vCNeterm numeric;
  vCSemif  numeric;
  vCProdR  numeric;
  vCPartS  numeric;
BEGIN
  --Adina 05.05.2021 - alstart,alstop
  --Bogdan 26.08.2020
  CALL PRC_AL_CHECK('ngest1',0);

  gSuplCols := 'ncont c, ngest g, centrecost cc, ncont c9';

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

  vCVenitN := COALESCE( NULLIF(fnc_getvalconstantalucru('CVenitNetermin'), '')::numeric, -1);
  vCNeterm := COALESCE( NULLIF(fnc_getvalconstantalucru('CNeterm'       ), '')::numeric, -1);
  vCSemif  := COALESCE( NULLIF(fnc_getvalconstantalucru('CSemifab'      ), '')::numeric, -1);
  vCProdR  := COALESCE( NULLIF(fnc_getvalconstantalucru('CProdRezid'    ), '')::numeric, -1);
  vCPartS  := COALESCE( NULLIF(fnc_getvalconstantalucru('CPartidaSimpla'), '')::numeric, -1);

  IF vCVenitN &lt;= 0 THEN
      SELECT COALESCE(Max(CODCONT), -1) INTO vCVenitN FROM NCONT WHERE SIMBOL = '711';
  END IF;

  sInsTMP := 'INSERT INTO tmp_lst_matrcv(
                       tiplinie, codcont, codgest, codcentru, codcont9,
                       valaloc,
                       valnealoc,
                       vanzari,
                       marfuri,
                       alteactiv,
                       elemfinanc,
                       elemexcept,
                       chimpprof,
                       valtot,
                       totaltip )
          WITH G1 AS (
                  SELECT distinct
                      codgest,
                      cheltuieli      codcont9_01,
                      cheltuieliind   codcont9_02,
                      cheltuieliind   codcont9_03,
                      cheltuieliaux   codcont9_11,
                      cheltuieliadmin codcont9_12,
                      cheltuielidesf  codcont9_13
                  FROM ngest1
                    WHERE ' || coalesce(getanlunalucru()::varchar,'') || ' BETWEEN ALSTART and ALSTOP
                  ),
            J AS (
                  SELECT
                    CASE
                      WHEN j.contd = ' || coalesce(vCVenitN::varchar,'') || ' AND j.contc = ' || coalesce(vCNeterm::varchar,'') || ' THEN 312
                      WHEN j.contd = ' || coalesce(vCVenitN::varchar,'') || ' AND j.contc = ' || coalesce(vCSemif::varchar ,'') || ' AND j.tipdoc IN (16,19,20) THEN 322
                      WHEN j.contd = ' || coalesce(vCVenitN::varchar,'') || ' AND j.contc = ' || coalesce(vCSemif::varchar ,'') || ' AND j.tipdoc IN (24)       THEN 323
                      WHEN j.contd = ' || coalesce(vCVenitN::varchar,'') || ' AND j.contc = ' || coalesce(vCSemif::varchar ,'') || ' AND j.tipdoc IN (14,15)    THEN 332
                      WHEN j.contd = ' || coalesce(vCVenitN::varchar,'') || ' AND j.contc = ' || coalesce(vCSemif::varchar ,'') || ' AND j.tipdoc IN (13)       THEN 342
                      WHEN j.contd = ' || coalesce(vCVenitN::varchar,'') || ' AND (select wme_result from PKG_CATEGCONST_ESTECONTPENTRU(null,j.contc, ''CPRODUSEANIMALE'')) &gt; 0 AND j.tipdoc IN (16,19,20) THEN 412
                      WHEN j.contd = ' || coalesce(vCVenitN::varchar,'') || ' AND (select wme_result from PKG_CATEGCONST_ESTECONTPENTRU(null,j.contc, ''CPRODUSEANIMALE'')) &gt; 0 AND j.tipdoc IN (13)       THEN 422
                      WHEN j.contd = ' || coalesce(vCVenitN::varchar,'') || ' AND (select wme_result from PKG_CATEGCONST_ESTECONTPENTRU(null,j.contc, ''CPRODUSEANIMALE'')) &gt; 0 AND j.tipdoc IN (14,15)    THEN 432
                      WHEN j.contd = ' || coalesce(vCVenitN::varchar,'') || ' AND j.contc = ' || coalesce(vCProdR::varchar ,'') || ' AND j.tipdoc IN (16,19,20) THEN 452
                      WHEN j.contd = ' || coalesce(vCVenitN::varchar,'') || ' AND j.contc = ' || coalesce(vCProdR::varchar ,'') || ' AND j.tipdoc IN (24)       THEN 453
                      WHEN j.contd = ' || coalesce(vCVenitN::varchar,'') || ' AND j.contc = ' || coalesce(vCProdR::varchar ,'') || ' AND j.tipdoc IN (13)       THEN 462
                      WHEN j.contd = ' || coalesce(vCVenitN::varchar,'') || ' AND j.contc = ' || coalesce(vCProdR::varchar ,'') || ' AND j.tipdoc IN (14,15)    THEN 472
                      WHEN j.tipdoc = 76 AND dc.faza = 1 THEN 710
                      WHEN j.tipdoc = 76 AND dc.faza = 2 THEN 720
                      WHEN j.tipdoc = 76 AND dc.faza = 3 THEN 730
                      WHEN j.tipdoc = 76 AND dc.faza = 4 THEN 740
                      WHEN j.tipdoc = 72 THEN 750
                      WHEN c.clasa  =  6 THEN 100
                      WHEN c.clasa  =  7 THEN 200
                    END tiplinie,
                    c.codcont, g.codgest,
                    coalesce(j.codcentru,0) codcentru,
                    coalesce(cc.tipaloc,-1) tipaloc,
                    CASE WHEN c.clasa = 7 THEN -j.valoare ELSE j.valoare END valoare,
                    c.simbol,
                    coalesce(
                    ( case cc.tipchelt
                        when 1 then g1.codcont9_01
                        when 2 then g1.codcont9_02
                        when 3 then g1.codcont9_03
                        when 11 then g1.codcont9_11
                        when 12 then g1.codcont9_12
                        when 13 then g1.codcont9_13 end),0) codcont9
                FROM jurnal j
                    INNER JOIN ncont        c  ON c.codcont    = j.contd
                    INNER JOIN ngest        g  ON g.codgest    = j.gest
                    LEFT  JOIN centrecost   cc ON cc.codcentru = j.codcentru
                    LEFT  JOIN g1              ON g1.codgest   = j.gest
                    LEFT  JOIN DistribChelt dc On dc.CodDistribChelt = J.CodDoc AND j.tipdoc = 76
                  WHERE j.LUNA = ' || coalesce(getlunalucru()::varchar,'') || ' AND j.AN = ' || coalesce(getAnLucru()::varchar,'') || ' AND c.clasa IN (6,7,9) '
                        || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'J',NULL,NULL,NULL)),'')
                        || ' AND CASE WHEN c.clasa = 9 AND j.tipdoc IN (72,76) AND c.codcont &lt;&gt; ' || coalesce(vCPartS::varchar,'') || ' THEN 1
                                      WHEN c.clasa = 9 THEN 0
                                      ELSE 1 END = 1
                             AND j.TIPDOC &lt;&gt; 32
                UNION ALL
                 SELECT
                    CASE
                      WHEN j.contc = ' || coalesce(vCVenitN::varchar,'') || ' AND j.contd = ' || coalesce(vCNeterm::varchar,'') || ' THEN 311
                      WHEN j.contc = ' || coalesce(vCVenitN::varchar,'') || ' AND j.contd = ' || coalesce(vCSemif::varchar,'') || ' AND j.tipdoc IN (7)     THEN 321
                      WHEN j.contc = ' || coalesce(vCVenitN::varchar,'') || ' AND j.contd = ' || coalesce(vCSemif::varchar,'') || ' AND j.tipdoc IN (14,15) THEN 331
                      WHEN j.contc = ' || coalesce(vCVenitN::varchar,'') || ' AND j.contd = ' || coalesce(vCSemif::varchar,'') || ' AND j.tipdoc IN (13)    THEN 341
                      WHEN j.contc = ' || coalesce(vCVenitN::varchar,'') || ' AND (select wme_result from PKG_CATEGCONST_ESTECONTPENTRU(null, j.contd, ''CPRODUSEANIMALE'')) &gt; 0 AND j.tipdoc IN (7)     THEN 411
                      WHEN j.contc = ' || coalesce(vCVenitN::varchar,'') || ' AND (select wme_result from PKG_CATEGCONST_ESTECONTPENTRU(null, j.contd, ''CPRODUSEANIMALE'')) &gt; 0 AND j.tipdoc IN (13)    THEN 421
                      WHEN j.contc = ' || coalesce(vCVenitN::varchar,'') || ' AND (select wme_result from PKG_CATEGCONST_ESTECONTPENTRU(null, j.contd, ''CPRODUSEANIMALE'')) &gt; 0 AND j.tipdoc IN (14,15) THEN 431
                      WHEN j.contc = ' || coalesce(vCVenitN::varchar,'') || ' AND j.contd = ' || coalesce(vCProdR::varchar,'') || ' AND j.tipdoc IN (7)     THEN 451
                      WHEN j.contc = ' || coalesce(vCVenitN::varchar,'') || ' AND j.contd = ' || coalesce(vCProdR::varchar,'') || ' AND j.tipdoc IN (13)    THEN 461
                      WHEN j.contc = ' || coalesce(vCVenitN::varchar,'') || ' AND j.contd = ' || coalesce(vCProdR::varchar,'') || ' AND j.tipdoc IN (14,15) THEN 471
                      WHEN j.tipdoc = 76 AND dc.faza = 1 THEN 710
                      WHEN j.tipdoc = 76 AND dc.faza = 2 THEN 720
                      WHEN j.tipdoc = 76 AND dc.faza = 3 THEN 730
                      WHEN j.tipdoc = 76 AND dc.faza = 4 THEN 740
                      WHEN j.tipdoc = 72 THEN 750
                      WHEN c.clasa  =  6 THEN 100
                      WHEN c.clasa  =  7 THEN 200
                    END tiplinie,
                    c.codcont,
                    g.codgest,
                    coalesce(j.codcentru,0) codcentru,
                    coalesce(cc.tipaloc,-1) tipaloc,
                    CASE WHEN c.clasa = 7 THEN j.valoare ELSE -j.valoare END valoare,
                    c.simbol,
                    coalesce(
                      (case  cc.tipchelt
                            when  1 then g1.codcont9_01
                            when  2 then g1.codcont9_02
                            when  3 then g1.codcont9_03
                            when 11 then g1.codcont9_11
                            when 12 then g1.codcont9_12
                            when 13 then g1.codcont9_13 end),0) codcont9
                FROM jurnal j
                  INNER JOIN ncont        c  ON c.codcont    = j.contc
                  INNER JOIN ngest        g  ON g.codgest    = j.gest
                  LEFT  JOIN centrecost   cc ON cc.codcentru = j.codcentru
                  LEFT  JOIN g1              ON g1.codgest   = j.gest
                  LEFT  JOIN DistribChelt dc On dc.CodDistribChelt = J.CodDoc AND j.tipdoc = 76
                WHERE j.LUNA = ' || coalesce(getLunaLucru()::varchar,'') || ' AND j.AN = ' || coalesce(getAnLucru()::varchar,'') || ' AND c.clasa IN (6,7,9) '
                          || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'J',NULL,NULL,NULL)),'')
                          || ' AND CASE WHEN c.clasa = 9 AND j.tipdoc IN (72,76) AND c.codcont &lt;&gt; ' || coalesce(vCPartS::varchar,'') || ' THEN 1
                                        WHEN c.clasa = 9 THEN 0
                                        ELSE 1 END = 1
                               AND j.TIPDOC &lt;&gt; 32)
            SELECT
                tiplinie, codcont, codgest, codcentru, codcont9,
                sum(case when tipaloc = 0 then valoare else 0 end) valaloc,
                sum(case when tipaloc = 1 then valoare else 0 end) valnealoc,
                sum(CASE WHEN tipaloc IN (0,1) THEN 0
                         WHEN simbol IN (''701'',''702'',''703'') THEN valoare
                         ELSE 0 END) vanzari,
                sum(CASE WHEN tipaloc IN (0,1) THEN 0
                         WHEN simbol IN (''607'',''707'') THEN valoare
                         ELSE 0 END) marfuri,
                sum(CASE  WHEN tipaloc IN (0,1) THEN 0
                          WHEN simbol IN (''701'',''702'',''703'',
                                          ''607'',''707'',
                                          ''665'',''666'',''667'',''765'',''766'',''767'',
                                          ''000.000'',
                                          ''623'',''691''
                                         ) THEN 0
                        ELSE valoare
                      END    ) alteactiv,
              sum(CASE WHEN tipaloc IN (0,1) THEN 0 WHEN simbol IN (''665'',''666'',''667'',''765'',''766'',''767'') THEN valoare ELSE 0 END) elemfinanc,
              sum(CASE WHEN tipaloc IN (0,1) THEN 0 WHEN simbol IN (''000.000'')                                     THEN valoare ELSE 0 END) elemexcept,
              sum(CASE WHEN tipaloc IN (0,1) THEN 0 WHEN simbol IN (''623'',''691'')                                 THEN valoare ELSE 0 END) chimpprof,
              sum(valoare) valtot,
              0 totaltip
            FROM j
            GROUP BY tiplinie, codcont, codgest, codcentru, codcont9';
--
sInsert := 'INSERT INTO ' || tmpName || '(
                  Cont,
                  Denumire,
                  TipLinie,
                  ContAsoc, Gest, CentruCost,
                  totaloc, totnealoc, vanzari, marfuri, alteactiv, elemfinanc, elemexcept, chimpprof,
                  totalalt, total, totaltip, ord ' || coalesce(gUserFields,'') || ')
        SELECT
          c.Simbol,
          CASE
            WHEN tmp.tiplinie = 100 THEN c.Den_Cont
            WHEN tmp.tiplinie = 199 THEN ''Total cheltuieli''
            WHEN tmp.tiplinie = 200 THEN c.Den_Cont
            WHEN tmp.tiplinie = 299 THEN ''Total venituri''
            WHEN tmp.tiplinie = 311 THEN ''Productie neterminata_sfarsit perioada_Credit (+)''
            WHEN tmp.tiplinie = 312 THEN ''Productie neterminata_consum productie_Debit (-)''
            WHEN tmp.tiplinie = 321 THEN ''Produse semifinite_Productie Cost standard_Credit (+)''
            WHEN tmp.tiplinie = 322 THEN ''Produse semifinite_Vanzari Cost standard_Debit (-)''
            WHEN tmp.tiplinie = 323 THEN ''Produse semifinite_Consum productie Cost standard_Debit (-)''
            WHEN tmp.tiplinie = 331 THEN ''Produse semifinite_Dif Inventar_Credit (+)''
            WHEN tmp.tiplinie = 332 THEN ''Produse semifinite_Dif Inventar_Debit (-)''
            WHEN tmp.tiplinie = 341 THEN ''Produse semifinite_Abateri semifinite_Credit (+)''
            WHEN tmp.tiplinie = 342 THEN ''Produse semifinite_Abateri semifinite Debit (-)''
            WHEN tmp.tiplinie = 399 THEN ''Total productie in curs si semifabricate''
            WHEN tmp.tiplinie = 411 THEN ''Produse finite - Productie Cost standard_Credit (+)''
            WHEN tmp.tiplinie = 412 THEN ''Produse finite - Vanzari Cost standard_Debit (-)''
            WHEN tmp.tiplinie = 421 THEN ''Produse finite - Abateri_Credit (+)''
            WHEN tmp.tiplinie = 422 THEN ''Produse finite - Abateri_Debit (-)''
            WHEN tmp.tiplinie = 431 THEN ''Produse finite_Dif Inventar_Credit (+)''
            WHEN tmp.tiplinie = 432 THEN ''Produse finite_Dif Inventar_Debit (-)''
            WHEN tmp.tiplinie = 451 THEN ''Produse reziduale - Productie Cost standard_Credit (+)''
            WHEN tmp.tiplinie = 452 THEN ''Produse reziduale - Vanzari Cost standard_Debit (-)''
            WHEN tmp.tiplinie = 453 THEN ''Produse reziduale - Consum Cost standard_Debit (-)''
            WHEN tmp.tiplinie = 461 THEN ''Produse reziduale - Abateri_Credit (+)''
            WHEN tmp.tiplinie = 462 THEN ''Produse reziduale - Abateri_Debit (-)''
            WHEN tmp.tiplinie = 471 THEN ''Produse reziduale_Dif Inventar_Credit (+)''
            WHEN tmp.tiplinie = 472 THEN ''Produse reziduale_Dif Inventar_Debit (+)''
            WHEN tmp.tiplinie = 499 THEN ''Total produse finite si reziduale''
            WHEN tmp.tiplinie = 599 THEN ''Total rezultat luna''
            WHEN tmp.tiplinie = 699 THEN ''Cost productie preliminar''
            WHEN tmp.tiplinie = 710 THEN ''Distributii faza 1''
            WHEN tmp.tiplinie = 720 THEN ''Distributii faza 2''
            WHEN tmp.tiplinie = 730 THEN ''Distributii faza 3''
            WHEN tmp.tiplinie = 740 THEN ''Distributii faza 4''
            WHEN tmp.tiplinie = 750 THEN ''post calcul''
            WHEN tmp.tiplinie = 799 THEN ''Total decontari''
            WHEN tmp.tiplinie = 899 THEN ''Cost productie final''
          END denumire,
          CASE
            WHEN trunc(tmp.tiplinie/100) = 1 THEN ''01.Cheltuieli''
            WHEN trunc(tmp.tiplinie/100) = 2 THEN ''02.Venituri''
            WHEN trunc(tmp.tiplinie/100) = 3 THEN ''03.711-productie in curs si semifabricate''
            WHEN trunc(tmp.tiplinie/100) = 4 THEN ''04.711-produse finite si reziduale''
            WHEN trunc(tmp.tiplinie/100) = 5 THEN ''05.Rezultat luna''
            WHEN trunc(tmp.tiplinie/100) = 6 THEN ''06.Cost Preliminar''
            WHEN trunc(tmp.tiplinie/100) = 7 THEN ''07.Decontari interne''
            WHEN trunc(tmp.tiplinie/100) = 8 THEN ''08.Cost final''
          END tiplinie,
          c9.simbol, g.den_gest, cc.denumire,
          tmp.valaloc, tmp.valnealoc, tmp.vanzari,
          tmp.marfuri, tmp.alteactiv, tmp.elemfinanc,
          tmp.elemexcept, tmp.chimpprof,
          tmp.vanzari+tmp.marfuri+tmp.alteactiv+tmp.elemfinanc+tmp.elemexcept+tmp.chimpprof,
          tmp.valaloc + tmp.valnealoc, tmp.totaltip, tmp.TipLinie ' || coalesce(gUserAlias,'') || '
      FROM tmp_lst_matrcv tmp
        LEFT JOIN ncont      c  ON c.codcont    = tmp.codcont
        LEFT JOIN ngest      g  ON g.codgest    = tmp.codgest
        LEFT JOIN centrecost cc ON cc.codcentru = tmp.codcentru
        LEFT JOIN ncont      c9 ON c9.codcont   = tmp.codcont9' || coalesce(gSuplJoins,'');

    DELETE FROM tmp_lst_matrcv;

    EXECUTE sInsTmp;

    DELETE FROM tmp_lst_matrcv
    WHERE  valaloc    = 0
      AND  valnealoc  = 0
      AND  vanzari    = 0
      AND  marfuri    = 0
      AND  alteactiv  = 0
      AND  elemfinanc = 0
      AND  elemexcept = 0
      AND  chimpprof  = 0
      AND  valtot     = 0;

    INSERT INTO tmp_lst_matrcv
      SELECT Trunc(tiplinie / 100) * 100 + 99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Sum(valtot)
      FROM tmp_lst_matrcv
      GROUP BY Trunc(tiplinie / 100);

    INSERT INTO tmp_lst_matrcv
      SELECT 599, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Sum(totaltip * CASE WHEN  tiplinie=199 THEN -1 ELSE  1 END )
      FROM tmp_lst_matrcv
      WHERE tiplinie IN (199, 299, 399, 499);

    INSERT INTO tmp_lst_matrcv
      SELECT 699, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Sum(totaltip * CASE  WHEN  tiplinie=199 THEN 1 ELSE  -1 END )
      FROM tmp_lst_matrcv
      WHERE tiplinie IN (199, 299, 399);

    INSERT INTO tmp_lst_matrcv
      SELECT 899, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Sum(totaltip)
      FROM tmp_lst_matrcv
      WHERE tiplinie IN (699, 799);

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_matsa_processlist</obj_name>
  <obj_hashval>e862a8a1cc5797c7a9a827c4ff805e6d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_matsa_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 := '';
  gDataS  varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true);
  gDataF  varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true);
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  gSuplCols   varchar := 'comanda c, Comanda2 C2, Comanda3 C3, CMDProdMat CPM, Nartobj NAO, NUM UM, Nparccom NPC, NparcAut NPA';
BEGIN
  --Florin 24.05.2024 - fixat 62076
  --Florin 20.05.2024 - sinc. Oracle
  --Adina 14.10.2020
  PERFORM PKG_LIST_STRUCT_GOLESTE_PARAM();

  call pkg_list_struct_StartSuplCols();
  call pkg_list_struct_GetSuplCols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('pkg_list_base_matsa.gSuplCols', gSuplCols, false);

  IF  to_date(gDataS,'dd.mm.yyyy') = to_date(gDataF,'dd.mm.yyyy') THEN
    sPer := '= TO_DATE(''' || coalesce(gDataS,'') || ''',''dd.mm.yyyy'')';
  ELSE
    sPer := 'BETWEEN TO_DATE(''' || coalesce(gDataS,'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(gDataF,'') || ''',''dd.mm.yyyy'')';
  END IF;

  sInsert :=
  'INSERT INTO ' || tmpName || '(
      NAV_CodDoc,
      NAV_TipDoc,
      SERIADOC,
      NRDOC,
      DATADOC,
      ANULAT,
      OPERAT,
      INCHIS,
      CodExtern,
      ARTICOL,
      UM,
      CANTPROIECTATA,
      PRETARTICOL,
      REST,
      CLIENT,
      CIFCLIENT,
      MODEL,
      MARCA,
      NRINREG,
      ANFABRICATIE,
      CULOAREC,
      SERIECAROSERIE,
      SERIEMOTOR,
      LUCRARE,
      OBSERVATII,
      PLATITOR,
      CIFPLATITOR,
      GARANTIE,
      OPERATIE,
      DESCRIERE,
      DATAFIN,
      TIP,
      EXECUTAT,
      GESTIUNE,
      TIPCOLOANA ' || coalesce(gUserFields,'') || '
    )';

  sSelect := '
  SELECT
        C.CodComanda,
        C.TipDoc,
        C.SeriaDoc,
        C.NrDoc,
        C.DataDOC,
        (case coalesce(C.Anulat,0)  when 0 then ''Nu'' when 1 then ''Da'' end) Anulat,
        (case coalesce(C.Operat,0)  when 0 then ''Nu'' when 1 then ''Da'' end) Operat,
        (case coalesce(C.Inchisa,0) when 0 then ''Nu'' when 1 then ''Da'' end) Inchis,
        NAO.CodExtern,
        NAO.Denumire Articol,
        UM.Den_UM UM,
        CPM.Cant CantProiectata,
        CPM.Pret PretArticol,
        CPM.Rest Rest,
        Case when C.FaraFactura = 1 then ''Comanda interna'' else NPart.Den_Part end 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(NP.DEN_PART,NPart.Den_Part) Platitor,
        coalesce(CIF2.CodFiscal,CIF.CodFiscal) CIFPlatitor,
        (case coalesce(C2.Garantie,0) when 0 then ''Nu'' when 1 then ''Da'' end) Garantie,
        NO.Denumire Operatie,
        C3.Obs Descriere,
        C3.Data DataFin,
        (case coalesce(C3.Tip,0) when 0 then ''Solicitare'' when 1 then ''Constatare'' when 2 then ''Nefacturabila'' end) Tip,
        (case coalesce(C3.Executat,0) when 0 then ''Nu'' when 1 then ''Da'' end) Executat,
        NG.Den_gest Gestiune,
        NPC.TIPCOMANDA TIPCOLOANA ' || coalesce(gUserAlias,'') || '
      from   comanda c
            Left join Comanda2     C2    on C2.CodComanda     = C.CodComanda
            Left join Comanda3     C3    on C3.CodComanda2    = C2.CodComanda2
            Left join CMDProdMat   CPM   on CPM.CodComanda3   = C3.CodComanda3
            Left join Nartobj      NAO   on NAO.CodObiect     = CPM.CodObiect
            Left join NUM          UM    on Um.CodUm          = CPM.UMsec
            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'
      || coalesce(gSuplJoins,'') || '
      WHERE C.TipDoc = 92
      AND C.DataDoc::date ' || coalesce(sPer,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'');
  EXECUTE sInsert || sSelect;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_mifix_processlist</obj_name>
  <obj_hashval>dc329274064b658df978e1654f19ac5c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_mifix_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;
  sFiltru1 varchar;
  sFiltru2 varchar;
  dAuxDate date;
  cCMifix  text := Coalesce(fnc_GetValConstanta('CMifix', GETANLUCRU(),GETLUNALUCRU()), '-2');
  cCMF1    text := '';
  cCMF2    text := '';
BEGIN
  --Florin 16.10.2025 - fixat 66971
  --Florin 30.09.2025 - sinc. Oracle
  --Florin 30.05.2023 - sinc. Oracle
  --Florin 16.05.2023 - sinc. Oracle
  --Bogdan 21.09.2020
  gSuplCols := 'MIFIX MF, MIFIX1 MF1, MFCLASIF MFC, NIRSTOC NS, NIR NIR, NGEST NG, NARTOBJ NAO, NGEST NG_S, NGEST NG_D, NPART PC, NPART FURN, NLOCATII L, NARTAMB AA, CENTRECOST CC, NIRSER NSER, NSERII SER, FISAMF FMF';

  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_MIFIX.gSuplCols',gSuplCols,false);

  dAuxDate := To_Date (To_Char (getAnLucru() * 100 + getLunaLucru(), 'fm000000') , 'yyyymm');
  dAuxDate := Add_Months (dAuxDate, 1);
  dAuxDate := DATE_TRUNC ('DAY',dAuxDate);
  IF NOT current_setting ('PKG_LIST_BASE_MIFIX.v_ToateMF', true)::numeric = 1
    AND current_setting ('PKG_LIST_BASE_MIFIX.v_TipSelMF', true) ::numeric = 0 THEN
    sFiltru2 := '
        AND NS.CODOBIECT IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')';
  ELSIF NOT current_setting ('PKG_LIST_BASE_MIFIX.v_ToateMF', true)::numeric = 1
    AND current_setting ('PKG_LIST_BASE_MIFIX.v_TipSelMF', true) ::numeric = 1 THEN
    sFiltru1 := '
            AND MF.CODMIFIX IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODMIFIX'')';
  END IF;

  IF cCMifix &lt;&gt; '-2'THEN
    EXECUTE 'TRUNCATE TABLE TMP_MANEVRA';
    EXECUTE 'INSERT INTO TMP_MANEVRA (CODUNIC)
    WITH RECURSIVE tmpc (CODCONT) AS (
      SELECT codcont
      FROM ncont
      WHERE codcont IN ('||coalesce(cCMifix, '')||')
        AND codcont &lt;&gt; 0
      UNION ALL
      SELECT c.codcont
      FROM tmpc INNER JOIN ncont c ON c.codparinte = tmpc.codcont
    )
    SELECT codcont FROM tmpc ';

    cCMF1 := '
        WHEN FMF.CODOPERATIE = 2 AND CMF.CODUNIC IS NULL        THEN FMF.PretI';
    cCMF2 := '
      LEFT JOIN NIRSTOC     NSP   ON NSP.CODNIRSTOC   = NS.CODNIRSTOCPARINTE
      LEFT JOIN NIR         NP    ON NP.CODNIR        = NSP.CODNIR
      LEFT JOIN IOART1      IOA1P ON IOA1P.CODIOART   = NSP.CODIOART AND MF1.ANSTART*12+MF1.LUNASTART BETWEEN IOA1P.ALSTART AND IOA1P.ALSTOP
      LEFT JOIN TMP_MANEVRA CMF   ON CMF.CODUNIC      = IOA1P.CONT';
  END IF;

  IF current_setting ('PKG_LIST_BASE_MIFIX.v_Amo', true) ::numeric &gt; 0 THEN
    sInsert := 'INSERT INTO '|| tmpName
              || ' (
              Denumire,
              Categoria,
              CodClasif,
              AnFolos,
              LunaFolos,
              CodExtern,
              CodIntern,
              AnAmort,
              LunaAmort,
              DurataNorm,
              DurataUtil,
              NrInv,
              Document,
              DataDoc,
              Operatii,
              NrBuc,
              Debit,
              Credit,
              Ord,
              Sold,
              Obs,
              AmortLun,
              CentruCost,
              PretInitial'
                || coalesce (gUserFields ,'')
                || ')
          SELECT NAO.DENUMIRE,
            MFC.DENUMIRE Categoria,
            MFC.SIMBOL   CodClasif,
            MF.ANINTRARE,
            MF.LUNAINTRARE,
            NAO.CODEXTERN,
            NAO.CODINTERN,
            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,
            MF1.DURATAN                                                                                                    DurataNorm,
            MF1.DURATAF                                                                                                    DurataUtil,
            MF.NRINVENTAR,
            TMP.doc,
            TMP.DATAOPERATIE DataDoc,
            CASE
              WHEN FMF.CODOPERATIE IS NULL THEN
                case
                  when m1.stare = 3 then ''Casat  in luna''
                  when m1.stare = 4 then ''Vandut in luna''
                  when m1.tipreeval in (0,1) then case when (TMP.icontd = 4 and TMP.icontc = 10) or (TMP.icontd = 3 and TMP.icontc = 0) then
                 ''Amortizare ''|| m1.lunastart ||'' ''|| m1.anstart else ''Reevaluare ''|| m1.lunastart ||'' ''|| m1.anstart end
                  when m1.tipreeval is null then ''Amortizare ''|| m1.lunastart ||'' ''|| m1.anstart::varchar
                end
              ELSE
                CASE
                  WHEN TMP.INIT = 1 THEN ''Amortizare precedenta''
                  ELSE
                    CASE FMF.CODOPERATIE
                      WHEN 1 THEN ''Intrare in firma - ''||NG_D.DEN_GEST
                      WHEN 2 THEN ''Transfer intre gestiuni - ''||NG_S.DEN_GEST||'' - ''||NG_D.DEN_GEST
                      WHEN 3 THEN ''Modificare de pret''
                      WHEN 4 THEN ''Casare''
                      WHEN 5 THEN ''Vanzare''
                      WHEN 6 THEN ''Reevaluare     - valoare MF''
                      WHEN 7 THEN ''Reevaluare     - amortizare prec''
                      WHEN 8 THEN ''Marire de stoc - ''||NG_D.DEN_GEST
                      WHEN 9 THEN ''Modificare gestiune - ''||NG_S.DEN_GEST||'' - ''||NG_D.DEN_GEST
                      WHEN 10 THEN ''Modificare centru de cost''
                      WHEN 11 THEN ''Modificare tip contabil''
                      WHEN 12 THEN ''Punere in functiune''
                    END
                END
            END                   Operatie,
            coalesce (FMF.CANT,1) NrBuc,
            CASE
              WHEN TMP.INIT = 1                                       THEN 0
              WHEN FMF.CODFISAMF IS NULL                              THEN 0
              WHEN FMF.CODOPERATIE IN (1,8)                           THEN FMF.PretI'||
              cCMF1||'
              WHEN FMF.CODOPERATIE IN (2,6) AND FMF.PretE &gt; FMF.PretI THEN FMF.PretE - FMF.PretI
              WHEN FMF.CODOPERATIE = 3      AND FMF.PretE &gt; FMF.PretI THEN FMF.PretE - FMF.PretI
              ELSE 0
            END Debit,
            CASE
              WHEN TMP.CODFISAMF = 0 THEN round (
              (select wme_result from PKG_INCHIDERI_AMORTIZARELUNARA(null, M1.CODMIFIX, M1.ANSTART, M1.LUNASTART)),2)
              WHEN TMP.CODFISAMF &gt; 0 and tmp.init = 1 THEN MF1M.amo
              WHEN FMF.CODOPERATIE IN (4,5)           THEN FMF.PretE
              WHEN FMF.CODOPERATIE IN (2,6) AND FMF.PretI &gt; FMF.PretE THEN FMF.PretI - FMF.PretE
              WHEN FMF.CODOPERATIE = 3      AND FMF.PretI &gt; FMF.PretE THEN FMF.PretI - FMF.PretE
              ELSE 0
            END Credit,
            ROW_NUMBER() OVER (PARTITION BY MF.CODMIFIX ORDER BY TMP.DATAOPERATIE, TMP.CODFISAMF) Ord,
            SUM (
              CASE
                WHEN TMP.INIT = 1             THEN 0
                WHEN FMF.CODFISAMF IS NULL    THEN 0
                WHEN FMF.CODOPERATIE IN (1,8) THEN FMF.PretI
                WHEN FMF.CODOPERATIE IN (2,6) AND FMF.PretE &gt; FMF.PretI THEN FMF.PretE - FMF.PretI
                WHEN FMF.CODOPERATIE = 3      AND FMF.PretE &gt; FMF.PretI THEN FMF.PretE - FMF.PretI
                ELSE 0
              END -
              CASE
                WHEN TMP.CODFISAMF = 0 THEN round (
                (select wme_result from PKG_INCHIDERI_AMORTIZARELUNARA(null, M1.CODMIFIX, M1.ANSTART, M1.LUNASTART)),2)
                WHEN TMP.CODFISAMF &gt; 0 and tmp.init = 1 THEN MF1M.amo
                WHEN FMF.CODOPERATIE IN (4,5)           THEN FMF.PretE
                WHEN FMF.CODOPERATIE IN (2,6) AND FMF.PretI &gt; FMF.PretE THEN FMF.PretI - FMF.PretE
                WHEN FMF.CODOPERATIE = 3      AND FMF.PretI &gt; FMF.PretE THEN FMF.PretI - FMF.PretE
                ELSE 0
              END)
            OVER (PARTITION BY MF.CODMIFIX ORDER BY TMP.DATAOPERATIE, TMP.CODFISAMF RANGE UNBOUNDED PRECEDING) Sold,
            TMP.OBS,
            (SELECT 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)) AmortLun,
            cc.denumire,
            nsmin.pret '
                || coalesce (gUserAlias ,'')|| '
          FROM (SELECT MF.CODMIFIX,
                       FMF.CODFISAMF,
                      (SELECT Max (MF1.AnStart * 12 + MF1.LunaStart)
                       FROM MIFIX1 MF1
                       WHERE
                         MF1.CODMIFIX = MF.CODMIFIX
                         --AND MF1.PRET = FMF.PRETI
                         AND MF1.ANSTART * 12 + MF1.LUNASTART &lt;= '|| coalesce ( (   getANLUNALUCRU ())::varchar ,'')
                  || ') AL_MF1,
                      0 CODMIFIX1,
                      NULL ICONTD,
                      NULL ICONTC,
                      COALESCE(FMF.PREFIXDOC,'''')||COALESCE(FMF.NRDOC::VARCHAR,'''')||''/''||TO_CHAR(FMF.DATAOPERATIE,''DD.MM.YYYY'') doc,
                      FMF.DATAOPERATIE,
                      FMF.DATAOPERATIE DATAORDINE,
                      FMF.OBS,
                      0 Init,
                     (SELECT Min (MF1.AnStart * 12 + MF1.LunaStart)
                      FROM MIFIX1 MF1
                      WHERE
                          MF1.CODMIFIX = MF.CODMIFIX
                          --AND MF1.PRET = FMF.PRETI
                          AND MF1.ANSTART * 12 + MF1.LUNASTART &lt;= '|| coalesce ( (   getANLUNALUCRU ())::varchar ,'')
                 || ') MIN_MF1
                FROM MIFIX MF INNER JOIN FISAMF FMF ON FMF.CODMIFIX = MF.CODMIFIX
                WHERE
                  MF.TIP = ''MF''
                  AND FMF.DATAOPERATIE &lt; to_date ('''|| coalesce (To_Char (dAuxDate, 'dd.mm.yyyy') ,'')|| ''',''dd.mm.yyyy'') '
                  || coalesce (sFiltru1,'')|| '
                UNION ALL
                SELECT MF.CODMIFIX,
                      0  CODFISAMF,
                      (SELECT Max (MF1.AnStart * 12 + MF1.LunaStart) FROM MIFIX1 MF1 WHERE MF1.CODMIFIX = MF.CODMIFIX AND MF1.ANSTART * 12 + MF1.LUNASTART &lt;= '|| coalesce ( (   getANLUNALUCRU ())::varchar ,'')
                  || ') AL_MF1,
                      MF1.CODMIFIX1,
                      J1.ICONTD,
                      J1.ICONTC,
                      J1.DOCUMENT doc,
                      J1.DATADOC  DATAOPERATIE,
                      J1.DATADOC  DATAORDINE,
                      J1.OBS,
                      0 Init,
                      (SELECT Min (MF1.AnStart * 12 + MF1.LunaStart)
                       FROM MIFIX1 MF1
                       WHERE
                          MF1.CODMIFIX = MF.CODMIFIX
                          AND MF1.ANSTART * 12 + MF1.LUNASTART &lt;= '|| coalesce ( (   getANLUNALUCRU ())::varchar ,'')
                  || ') MIN_MF1
                FROM (SELECT *
                      FROM JURNAL1
                      WHERE DATADOC &lt; to_date ('''|| coalesce (To_Char (dAuxDate, 'dd.mm.yyyy') ,'')|| ''',''dd.mm.yyyy'')
                      AND TIPDOC = 36
                      AND ICONTD = 4) J1
                  INNER JOIN MIFIX    MF  ON MF.CODMIFIX = J1.CODDOC
                  INNER JOIN MIFIX1   MF1 ON MF1.CODMIFIX = MF.CODMIFIX
                                        AND MF1.Stare &lt;&gt; 3 AND MF1.Stare &lt;&gt; 4
                                        AND MF1.ANSTART * 12 + MF1.LUNASTART = J1.AN * 12 + J1.LUNA
                WHERE
                  MF.TIP = ''MF'' '
                  || coalesce (sFiltru1,'')|| '
                UNION ALL
                SELECT MF.CODMIFIX,
                      FMF.CODFISAMF,
                      (SELECT MAX (MF1.AnStart * 12 + MF1.LunaStart)
                       FROM MIFIX1 MF1
                       WHERE
                         MF1.CODMIFIX = MF.CODMIFIX
                         AND MF1.PRET = FMF.PRETI
                         AND MF1.ANSTART * 12 + MF1.LUNASTART &lt;= '|| coalesce ( (   getANLUNALUCRU ())::varchar ,'')
                  || ') AL_MF1,
                      0 CODMIFIX1,
                      NULL ICONTD,
                      NULL ICONTC,
                      COALESCE(FMF.PREFIXDOC,'''')||COALESCE(FMF.NRDOC::VARCHAR,'''')||''/''||TO_CHAR(FMF.DATAOPERATIE,''DD.MM.YYYY'') doc,
                      FMF.DATAOPERATIE,
                      FMF.DATAOPERATIE + 1 / 24 / 60 / 60 DATAORDINE,
                      FMF.OBS,
                      1 Init,
                      ( SELECT MIN (MF1.AnStart * 12 + MF1.LunaStart)
                        FROM MIFIX1 MF1
                        WHERE
                          MF1.CODMIFIX = MF.CODMIFIX
                          AND MF1.PRET = FMF.PRETI
                          AND MF1.ANSTART * 12 + MF1.LUNASTART &lt;= '|| coalesce ( (   getANLUNALUCRU ())::varchar ,'')
                  || ') MIN_MF1
                FROM MIFIX MF INNER JOIN FISAMF FMF ON FMF.CODMIFIX = MF.CODMIFIX
                WHERE
                  MF.TIP = ''MF''
                  AND extract (year from FMF.DATAOPERATIE) * 12 + extract (month from FMF.DATAOPERATIE) &lt; (SELECT ANINITIAL * 12 + LUNAINITIALA FROM FIRMALUNI) '
                  || coalesce (sFiltru1,'')
            || ')             tmp
            INNER JOIN MIFIX      MF   ON MF.CODMIFIX   = tmp.CODMIFIX
            INNER JOIN MIFIX1     MF1  ON MF1.CODMIFIX  = tmp.CODMIFIX AND MF1.ANSTART  * 12 + MF1.LUNASTART  = tmp.AL_MF1
            INNER JOIN MIFIX1     MF1M ON MF1M.CODMIFIX = tmp.CODMIFIX AND MF1M.ANSTART * 12 + MF1M.LUNASTART = tmp.MIN_MF1
            INNER JOIN MFCLASIF   MFC  ON MFC.CODCLASIF = MF1.CODCLASIF
            INNER JOIN NIRSTOC    NS   ON NS.CODNIRSTOC = MF1.CODNIRSTOC
            INNER JOIN NIR             ON NIR.CODNIR    = NS.CODNIR
            INNER JOIN NGEST      NG   ON NG.CODGEST    = NIR.GEST
            INNER JOIN NARTOBJ    NAO  ON NAO.CODOBIECT = NS.CODOBIECT
            LEFT  JOIN MIFIX1     M1   ON TMP.CODMIFIX1 = M1.CODMIFIX1
            LEFT  JOIN FISAMF     FMF  ON FMF.CODFISAMF = tmp.CODFISAMF
            LEFT  JOIN NGEST      NG_S ON NG_S.CODGEST  = FMF.GESTSURSA
            LEFT  JOIN NGEST      NG_D ON NG_D.CODGEST  = FMF.GESTDEST
            LEFT  JOIN NPART      PC   ON PC.CODPART    = MF1.CODPART
            LEFT  JOIN NPART      FURN ON FURN.CODPART  = NS.FURN
            LEFT  JOIN NLOCATII   L    ON L.CODLOCATIE  = MF1.CODLOCATIE
            LEFT  JOIN NARTAMB    AA   ON AA.CODOBIECT  = NS.CODOBIECT AND AA.UMSEC = NS.UMSEC
            LEFT  JOIN CENTRECOST CC   ON CC.CODCENTRU  = Coalesce (MF1.CODCENTRU,0)
            LEFT JOIN (
            select min(mf1.codnirstoc) codnirstoc, mf1.codmifix from mifix1 mf1 group by mf1.codmifix
            )                    mfmin ON mf1.codmifix     = mfmin.codmifix
            LEFT JOIN nirstoc    nsmin ON mfmin.codnirstoc = nsmin.codnirstoc
            LEFT JOIN nirser     nser  ON nser.codnirser   = mf1.codnirser
            LEFT JOIN nserii     ser   ON ser.codserie     = nser.codserie'||
            cCMF2 || coalesce (gSuplJoins ,'')|| '
          WHERE
            1 = 1 '
                || coalesce ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'NG', 'CODSUBUNIT',NULL,NULL)) ::varchar ,'')
                || coalesce (sFiltru2,'')|| '
          ORDER BY
            MF.CODMIFIX,
            TMP.DATAORDINE,
            TMP.CODFISAMF';
  ELSE
    sInsert := '
          INSERT INTO '|| tmpName
        || ' (Denumire,
              Categoria,
              CodClasif,
              AnFolos,
              LunaFolos,
              CodExtern,
              CodIntern,
              AnAmort,
              LunaAmort,
              DurataNorm,
              DurataUtil,
              NrInv,
              Document,
              DataDoc,
              Operatii,
              NrBuc,
              Debit,
              Credit,
              Ord,
              Sold,
              Obs,
              AmortLun,
              CentruCost,
              PretInitial'
                || coalesce (gUserFields ,'')
                || ')
          SELECT NAO.DENUMIRE,
            MFC.DENUMIRE Categoria,
            MFC.SIMBOL   CodClasif,
            MF.ANINTRARE,
            MF.LUNAINTRARE,
            NAO.CODEXTERN,
            NAO.CODINTERN,
            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,
            MF1.DURATAN                                                                                                    DurataNorm,
            MF1.DURATAF                                                                                                    DurataUtil,
            MF.NRINVENTAR,
            COALESCE(FMF.PREFIXDOC,'''')||COALESCE(FMF.NRDOC::VARCHAR,'''')||''/''||TO_CHAR(FMF.DATAOPERATIE,''DD.MM.YYYY'') doc,
            FMF.DATAOPERATIE       DataDoc,
            CASE FMF.CODOPERATIE
              WHEN  1 THEN ''Intrare in firma - ''||NG_D.DEN_GEST
              WHEN  2 THEN ''Transfer intre gestiuni - ''||NG_S.DEN_GEST||'' - ''||NG_D.DEN_GEST
              WHEN  3 THEN ''Modificare de pret''
              WHEN  4 THEN ''Casare''
              WHEN  5 THEN ''Vanzare''
              WHEN  6 THEN ''Reevaluare     - valoare MF''
              WHEN  7 THEN ''Reevaluare     - amortizare prec''
              WHEN  8 THEN ''Marire de stoc - ''||NG_D.DEN_GEST
              WHEN  9 THEN ''Modificare gestiune - ''||NG_S.DEN_GEST||'' - ''||NG_D.DEN_GEST
              WHEN 10 THEN ''Modificare centru de cost''
              WHEN 11 THEN ''Modificare tip contabil''
              WHEN 12 THEN ''Punere in functiune''
            END                   Operatie,
            Coalesce (FMF.CANT,1) NrBuc,
            CASE
              WHEN FMF.CODOPERATIE IN (1,8)                           THEN FMF.PretI'||
              cCMF1||'
              WHEN FMF.CODOPERATIE IN (2,6) AND FMF.PretE &gt; FMF.PretI THEN FMF.PretE - FMF.PretI
              WHEN FMF.CODOPERATIE = 3      AND FMF.PretE &gt; FMF.PretI THEN FMF.PretE - FMF.PretI
              ELSE 0
            END Debit,
            CASE
              WHEN FMF.CODOPERATIE IN (4,5) THEN FMF.PretE
              WHEN FMF.CODOPERATIE IN (2,6) AND FMF.PretI &gt; FMF.PretE THEN FMF.PretI - FMF.PretE
              WHEN FMF.CODOPERATIE = 3 AND FMF.PretI &gt; FMF.PretE THEN FMF.PretI - FMF.PretE
              ELSE 0
            END Credit,
            row_number() OVER (PARTITION BY MF.CODMIFIX ORDER BY FMF.DATAOPERATIE, FMF.CODFISAMF) Ord,
            SUM (
              CASE FMF.CODOPERATIE
                WHEN 1 THEN FMF.PRETI
                WHEN 2 THEN FMF.PRETE - FMF.PRETI
                WHEN 3 THEN FMF.PRETE - FMF.PRETI
                WHEN 4 THEN           - FMF.PRETE
                WHEN 5 THEN           - FMF.PRETE
                WHEN 6 THEN FMF.PRETE - FMF.PRETI
                WHEN 8 THEN FMF.PRETI
                ELSE 0
              END) OVER (PARTITION BY MF.CODMIFIX ORDER BY FMF.DATAOPERATIE, FMF.CODFISAMF RANGE UNBOUNDED PRECEDING) Sold,
            FMF.OBS,
            (select wme_result from PKG_INCHIDERI_AMORTIZARELUNARA(null, MF1.CODMIFIX, MF1.ANSTART, MF1.LUNASTART)) AmortLun,
            cc.denumire,
            nsmin.pret '
                || coalesce (gUserAlias ,'')|| '
          FROM (SELECT MF.CODMIFIX,
                       FMF.CODFISAMF,
                       (SELECT Max (MF1.AnStart * 12 + MF1.LunaStart)
                        FROM MIFIX1 MF1
                        WHERE
                          MF1.CODMIFIX = MF.CODMIFIX
                          --AND MF1.PRET = FMF.PRETI
                          AND MF1.ANSTART * 12 + MF1.LUNASTART &lt;= '|| coalesce ( (   getANLUNALUCRU ())::varchar ,'')
                   || ') AL_MF1
                FROM MIFIX MF INNER JOIN FISAMF FMF ON FMF.CODMIFIX = MF.CODMIFIX
                WHERE
                  MF.TIP = ''MF''
                  AND FMF.DATAOPERATIE &lt; to_date ('''|| coalesce (To_Char (dAuxDate, 'dd.mm.yyyy') ,'')|| ''',''dd.mm.yyyy'') '
                || coalesce (sFiltru1,'')
            || ') tmp
            INNER JOIN MIFIX      MF    ON MF.CODMIFIX   = tmp.CODMIFIX
            INNER JOIN FISAMF     FMF   ON FMF.CODFISAMF = tmp.CODFISAMF
            INNER JOIN MIFIX1     MF1   ON MF1.CODMIFIX  = tmp.CODMIFIX AND MF1.ANSTART * 12 + MF1.LUNASTART = tmp.AL_MF1
            INNER JOIN MFCLASIF   MFC   ON MFC.CODCLASIF = MF1.CODCLASIF
            INNER JOIN NIRSTOC    NS    ON NS.CODNIRSTOC = MF1.CODNIRSTOC
            INNER JOIN NIR              ON NIR.CODNIR    = NS.CODNIR
            INNER JOIN NGEST      NG    ON NG.CODGEST    = NIR.GEST
            INNER JOIN NARTOBJ    NAO   ON NAO.CODOBIECT = NS.CODOBIECT
            LEFT  JOIN NGEST      NG_S  ON NG_S.CODGEST  = FMF.GESTSURSA
            LEFT  JOIN NGEST      NG_D  ON NG_D.CODGEST  = FMF.GESTDEST
            LEFT  JOIN NPART      PC    ON PC.CODPART    = MF1.CODPART
            LEFT  JOIN NPART      FURN  ON FURN.CODPART  = NS.FURN
            LEFT  JOIN NLOCATII   L     ON L.CODLOCATIE  = MF1.CODLOCATIE
            LEFT  JOIN NARTAMB    AA    ON AA.CODOBIECT  = NS.CODOBIECT AND AA.UMSEC = NS.UMSEC
            LEFT  JOIN CENTRECOST CC    ON CC.CODCENTRU  = Coalesce (MF1.CODCENTRU,0)
            LEFT  JOIN (select min (mf1.codnirstoc) codnirstoc, mf1.codmifix from mifix1 mf1 group by mf1.codmifix
                       )          mfmin on mf1.codmifix     = mfmin.codmifix
            LEFT  JOIN nirstoc    nsmin ON mfmin.codnirstoc = nsmin.codnirstoc
            LEFT  JOIN nirser     nser  ON nser.codnirser   = mf1.codnirser
            LEFT  JOIN nserii     ser   ON ser.codserie     = nser.codserie'
            || cCMF2 || coalesce (gSuplJoins ,'')|| '
          WHERE
            1 = 1 '
                || coalesce ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'NG', 'CODSUBUNIT',NULL,NULL)) ::varchar ,'')
                || coalesce (sFiltru2,'')|| '
          ORDER BY
            MF.CODMIFIX,
            FMF.DATAOPERATIE,
            FMF.CODFISAMF ';
  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_naproviz5_processlist</obj_name>
  <obj_hashval>5ea254c0bef3b71a3816d041a41c1538</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz5_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  aSQL           varchar := '';
  sInsert       varchar := '';
  vUserID       NUMERIC;
  vSubunitatea   NUMERIC;
  vAnLucru       NUMERIC;
  vLunaLucru     NUMERIC;
  vDataRef       Date;
   gSuplCols      VARCHAR := 'NARTOBJ OBJ';
   gUserFields    VARCHAR := '';
  gUserAlias     VARCHAR := '';
  gNullAlias     VARCHAR := '';
  gSuplJoins     VARCHAR := '';
  v_flgArt       NUMERIC := CASE WHEN current_setting('PKG_LIST_SELFISAMAG.p_flgArt',true)::boolean THEN 1 ELSE 0 END ;
  v_RezUM1       NUMERIC := CASE WHEN current_setting('PKG_LIST_SELFISAMAG.p_RezUM1',true)::boolean THEN 1 ELSE 0 END ;
BEGIN
  --Adina 20.04.2021 - sinc.Oracle
  --Adina 11.12.2020 tuning
  --Adina 02 septembrie 2020
  perform set_config('PKG_LIST_BASE_NAPROVIZ5.vUserID'     ,current_setting('PKG_GLOBALS.USERID', true)::varchar,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ5.vSubunitatea',getSUBUNITATE()::varchar,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ5.vAnLucru'    ,getANLUCRU()::varchar   ,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ5.vLunaLucru'  ,getLUNALUCRU()::varchar ,false);
  perform set_config('PKG_LIST_BASE_NAPROVIZ5.vDataRef'    ,current_setting('PKG_LIST_SELFISAMAG.p_DataRef',true),false);

  vUserID       := current_setting('PKG_LIST_BASE_NAPROVIZ5.vUserID'         , true)::NUMERIC;
  vSubunitatea   := current_setting('PKG_LIST_BASE_NAPROVIZ5.vSubunitatea'    , true)::NUMERIC;
  vAnLucru       := current_setting('PKG_LIST_BASE_NAPROVIZ5.vAnLucru'        , true)::NUMERIC;
  vLunaLucru     := current_setting('PKG_LIST_BASE_NAPROVIZ5.vLunaLucru'      , true)::NUMERIC;
  vDataRef       := to_date(current_setting('PKG_LIST_BASE_NAPROVIZ5.vDataRef', true)::varchar, 'dd.mm.yyyy') ;

  DELETE FROM tmp_stocreal_nec5 WHERE userid = vUserID;
  DELETE FROM NECESAR5 WHERE USERID = vUserID;

  IF  v_flgArt = 1 THEN
    DELETE FROM tmp_manevra_liste WHERE filtru = 'CODOBIECT';
    IF v_RezUM1 THEN
      INSERT INTO tmp_manevra_liste(filtru, valoare)
      SELECT 'CODOBIECT', CodObiect FROM nartobj WHERE COALESCE(produspropriu, 0) = 0;
    ELSE
      INSERT INTO tmp_manevra_liste(filtru, valoare)
      SELECT 'CODOBIECT', CodObiect FROM nartobj;
    END IF;
  END IF;

  ALTER TABLE tmp_stocreal_nec5 SET UNLOGGED ;  --add 11.12.2020

  PERFORM PKG_LIST_BASE_NAPROVIZ5_MakeStocuri();
  PERFORM PKG_LIST_BASE_NAPROVIZ5_MakeIesiri();
  PERFORM PKG_LIST_BASE_NAPROVIZ5_MakeConsumuri();
  PERFORM PKG_LIST_BASE_NAPROVIZ5_MakeComenzi();

  ALTER TABLE NECESAR5 SET UNLOGGED ;  --add 11.12.2020

/*  --11.12.2020 inlocuit cu insertul de mai jos, pt.ca la update-uri crapa lista
  FOR v_rec IN
    ( SELECT obj.codobiect, obj.denumire, COALESCE(objs.stocmin, 0) STOCMIN, pkg_oferta_GetCodOferta1PretMin(obj.codobiect, vDataRef) CODOFERTA1
      FROM   tmp_manevra_liste tmp
            INNER JOIN nartobj obj ON  obj.codobiect::varchar = tmp.valoare
            LEFT JOIN nartobjsubunit objs ON  objs.codobiect = obj.codobiect and  objs.subunitate = vSubunitatea
      WHERE tmp.filtru = 'CODOBIECT'
    )
  LOOP
    INSERT INTO necesar5(codobiect, denumire, indicator, nrindicator, stocmin, cantmin, userid)
    VALUES(v_rec.codobiect, v_rec.denumire, 'Consum an precedent', 1, v_rec.stocmin, 0, vUserID);

    INSERT INTO NECESAR5(codobiect, denumire, indicator, nrindicator, stocmin, cantmin, userid)
    VALUES(v_rec.codobiect, v_rec.denumire, 'Consum efectiv an curent', 2, v_rec.stocmin, 0, vUserID);

    INSERT INTO NECESAR5(codobiect, denumire, indicator, nrindicator, stocmin, cantmin, userid)
    VALUES(v_rec.codobiect, v_rec.denumire, 'Stoc la moment', 3, v_rec.stocmin, 0, vUserID);

    INSERT INTO NECESAR5(codobiect, denumire, indicator, nrindicator, stocmin, cantmin, userid)
    VALUES(v_rec.codobiect, v_rec.denumire, 'Consum rezervat', 4, v_rec.stocmin, 0, vUserID);

    INSERT INTO NECESAR5(codobiect, denumire, indicator, nrindicator, stocmin, cantmin, userid)
    VALUES(v_rec.codobiect, v_rec.denumire, 'Comenzi in curs', 5, v_rec.stocmin, 0, vUserID);

    INSERT INTO NECESAR5(codobiect, denumire, indicator, nrindicator, stocmin, cantmin, userid)
    VALUES(v_rec.codobiect, v_rec.denumire, 'Propunere de cumparare', 6, v_rec.stocmin, 0, vUserID);

    INSERT INTO NECESAR5(codobiect, denumire, indicator, nrindicator, stocmin, cantmin, userid)
    VALUES(v_rec.codobiect, v_rec.denumire, 'Stoc prognozat', 7, v_rec.stocmin, 0, vUserID);

    for v_luni in 1..12 loop
      aSQL := 'update NECESAR5 NEC5 set '||
              '  L'||v_luni::varchar||' = case nrindicator '||
              '                    when 1 then (SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = NEC5.CODOBIECT AND TMP.TIP = ''IES'||V_LUNI::varchar||'P'')'||
              '                    when 2 then (SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = NEC5.CODOBIECT AND TMP.TIP = ''IES'||V_LUNI::varchar||''')'||
              '                    when 3 then (SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = NEC5.CODOBIECT AND TMP.TIP = ''S'  ||V_LUNI::varchar||''')'||
              '                    when 4 then (SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = NEC5.CODOBIECT AND TMP.TIP = ''C'  ||V_LUNI::varchar||''')'||
              '                    when 5 then (SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = NEC5.CODOBIECT AND TMP.TIP = ''COM'||V_LUNI::varchar||''')'||
              '                  end '||
              'where codobiect = '||v_rec.codobiect::varchar||' and userid = '||vUserID::varchar||' and nec5.codobiect = '||v_rec.codobiect::varchar;
      DELETE FROM X;
      --INSERT INTO X(TEST) VALUES(aSQL);
      EXECUTE aSQL;
    end loop;

    for v_luni in vLunaLucru..12 loop
      aSQL := 'update NECESAR5 NEC5 set '||
              '  L'||v_luni::varchar||' = 0'||
              'where L'||v_luni::varchar||' is null and userid = '||vUserID::varchar||' and nec5.codobiect = '||v_rec.codobiect::varchar;
      EXECUTE aSQL;
    end loop;

    for v_luni in vLunaLucru..12 loop
      aSQL := 'update NECESAR5 NEC5 set '||
              '  L'||v_luni::varchar||' = StocMin - (select tmp.L'||v_luni::varchar||' from NECESAR5 tmp where tmp.codobiect = nec5.codobiect and tmp.nrindicator = 3 and tmp.userid = nec5.userid )'||
              '                                    + (select tmp.L'||v_luni::varchar||' from NECESAR5 tmp where tmp.codobiect = nec5.codobiect and tmp.nrindicator = 4 and tmp.userid = nec5.userid )'||
              '                                    - (select tmp.L'||v_luni::varchar||' from NECESAR5 tmp where tmp.codobiect = nec5.codobiect and tmp.nrindicator = 5 and tmp.userid = nec5.userid )'||
              'where nrindicator = 6 and userid = '||vUserID::varchar||' and nec5.codobiect = '||v_rec.codobiect::varchar;
      EXECUTE aSQL;
      aSQL := 'update NECESAR5 NEC5 set '||
              '  L'||v_luni::varchar||' = 0 '||
              'where nrindicator = 6 and L'||v_luni::varchar||' &lt; 0 and userid = '||vUserID::varchar||' and nec5.codobiect = '||v_rec.codobiect::varchar;
      EXECUTE aSQL;
    end loop;

    for v_luni in vLunaLucru..12 loop
      aSQL := 'update NECESAR5 NEC5 set '||
              '  L'||v_luni::varchar||' = (select tmp.L'||v_luni::varchar||' from NECESAR5 tmp where tmp.codobiect = nec5.codobiect and tmp.nrindicator = 3 and tmp.userid = nec5.userid )'||
              '                          - (select tmp.L'||v_luni::varchar||' from NECESAR5 tmp where tmp.codobiect = nec5.codobiect and tmp.nrindicator = 4 and tmp.userid = nec5.userid )'||
              '                          + (select tmp.L'||v_luni::varchar||' from NECESAR5 tmp where tmp.codobiect = nec5.codobiect and tmp.nrindicator = 5 and tmp.userid = nec5.userid )'||
              '                          + (select tmp.L'||v_luni::varchar||' from NECESAR5 tmp where tmp.codobiect = nec5.codobiect and tmp.nrindicator = 6 and tmp.userid = nec5.userid )'||
              'where nrindicator = 7 and userid = '||vUserID::varchar||' and nec5.codobiect = '||v_rec.codobiect::varchar;
      EXECUTE aSQL;
    end loop;

    UPDATE NECESAR5 tmp SET
      pret = (SELECT COALESCE(o1.pret, 0)
              FROM oferta1 o1
              WHERE v_rec.codoferta1 = o1.codoferta1
             ),
      furnizor = (SELECT COALESCE(p.den_part, '')
                  FROM  oferta1 o1
                        INNER JOIN oferta o ON  o1.codoferta = o.codoferta
                        INNER JOIN npart p  ON  o.partener = p.codpart
                  WHERE v_rec.codoferta1 = o1.codoferta1
                 ),
      cantmin = ( SELECT COALESCE(o1.cantmin, 0)
                  FROM oferta1 o1
                  WHERE v_rec.codoferta1 = o1.codoferta1
                )
    WHERE tmp.userid = vUserID and  tmp.codobiect = v_rec.codobiect;
  END LOOP;
*/

  aSQL := 'INSERT INTO necesar5(codobiect, denumire, furnizor, indicator, nrindicator, stocmin, cantmin,
                                pret, ordine, l1,l2,l3,l4,l5,l6,l7,l8,l9,l10,l11,l12, userid)
           SELECT a.codobiect, a.denumire,
                 (SELECT COALESCE(p.den_part, '''')
                  FROM  oferta1 o1
                        INNER JOIN oferta o ON  o1.codoferta = o.codoferta
                        INNER JOIN npart p  ON  o.partener = p.codpart
                  WHERE o1.codoferta1 =  a.codoferta1
                 ) furnizor,
                 b.indicator, b.nrindicator,
                 a.stocmin,
                 (SELECT COALESCE(o1.cantmin, 0) FROM oferta1 o1 WHERE  o1.codoferta1 = a.codoferta1 ) cantmin,
                 (SELECT COALESCE(o1.pret, 0) FROM oferta1 o1 WHERE  o1.codoferta1 = a.codoferta1 ) pret,
                 NULL::NUMERIC ordine,
          ';
  for v_luni in 1..12 loop
    aSQL := aSQL ||
          '       CASE
                   when nrindicator=1 then COALESCE((SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = a.CODOBIECT AND TMP.TIP = ''IES'||V_LUNI::varchar||'P''),0)
                   when nrindicator=2 then COALESCE((SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = a.CODOBIECT AND TMP.TIP = ''IES'||V_LUNI::varchar||'''),0)
                   when nrindicator=3 then COALESCE((SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = a.CODOBIECT AND TMP.TIP = ''S'  ||V_LUNI::varchar||'''),0)
                   when nrindicator=4 then COALESCE((SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = a.CODOBIECT AND TMP.TIP = ''C'  ||V_LUNI::varchar||'''),0)
                   when nrindicator=5 then COALESCE((SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = a.CODOBIECT AND TMP.TIP = ''COM'||V_LUNI::varchar||'''),0)
                   when nrindicator=6 AND '||V_LUNI::varchar||'&gt;='||vLunaLucru::varchar||'
                        then
                          CASE WHEN
                             (StocMin
                             - COALESCE((SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = a.CODOBIECT AND TMP.TIP = ''S'  ||V_LUNI::varchar||'''),0)
                             + COALESCE((SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = a.CODOBIECT AND TMP.TIP = ''C'  ||V_LUNI::varchar||'''),0)
                             - COALESCE((SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = a.CODOBIECT AND TMP.TIP = ''COM'||V_LUNI::varchar||'''),0)
                             ) &lt; 0
                                THEN 0
                             ELSE
                               StocMin
                               - COALESCE((SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = a.CODOBIECT AND TMP.TIP = ''S'  ||V_LUNI::varchar||'''),0)
                               + COALESCE((SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = a.CODOBIECT AND TMP.TIP = ''C'  ||V_LUNI::varchar||'''),0)
                               - COALESCE((SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = a.CODOBIECT AND TMP.TIP = ''COM'||V_LUNI::varchar||'''),0)
                          END
                   when nrindicator=7 AND '||V_LUNI::varchar||'&gt;='||vLunaLucru::varchar||'
                        then
                             COALESCE((SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = a.CODOBIECT AND TMP.TIP = ''S'  ||V_LUNI::varchar||'''),0)
                           - COALESCE((SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = a.CODOBIECT AND TMP.TIP = ''C'  ||V_LUNI::varchar||'''),0)
                           + COALESCE((SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = a.CODOBIECT AND TMP.TIP = ''COM'||V_LUNI::varchar||'''),0)
                           + CASE WHEN 1&gt;=10 --  1&gt;=vLunaLucru
                                    THEN
                                        CASE WHEN
                                           (StocMin
                                           - COALESCE((SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = a.CODOBIECT AND TMP.TIP = ''S'  ||V_LUNI::varchar||'''),0)
                                           + COALESCE((SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = a.CODOBIECT AND TMP.TIP = ''C'  ||V_LUNI::varchar||'''),0)
                                           - COALESCE((SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = a.CODOBIECT AND TMP.TIP = ''COM'||V_LUNI::varchar||'''),0)
                                           ) &lt; 0
                                              THEN 0
                                           ELSE
                                             StocMin
                                             - COALESCE((SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = a.CODOBIECT AND TMP.TIP = ''S'  ||V_LUNI::varchar||'''),0)
                                             + COALESCE((SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = a.CODOBIECT AND TMP.TIP = ''C'  ||V_LUNI::varchar||'''),0)
                                             - COALESCE((SELECT coalesce(CANT,0) FROM tmp_stocreal_nec5 TMP WHERE TMP.USERID = '||VUSERID::varchar||' AND TMP.CODOBIECT = a.CODOBIECT AND TMP.TIP = ''COM'||V_LUNI::varchar||'''),0)
                                        END
                                  ELSE 0
                             END
                 END l'||V_LUNI::varchar||',
          ';
  end loop;

  aSQL := aSQL || vUserID::varchar ||' userid ';
  aSQL := aSQL ||
  'FROM
    (
      SELECT obj.codobiect, obj.denumire, COALESCE(objs.stocmin, 0) STOCMIN, pkg_oferta_GetCodOferta1PretMin(obj.codobiect, current_date) CODOFERTA1
      FROM   tmp_manevra_liste tmp
            INNER JOIN nartobj obj ON  obj.codobiect::varchar = tmp.valoare
            LEFT JOIN nartobjsubunit objs ON  objs.codobiect = obj.codobiect
                                          and (objs.codgest is null or objs.codgest = 0)
                                          and  objs.subunitate = '||vSubunitatea::varchar||'
      WHERE tmp.filtru = ''CODOBIECT''
    ) a
    CROSS JOIN
    (
      SELECT ''Consum an precedent''      indicator, 1 nrindicator
      UNION
      SELECT ''Consum efectiv an curent'' indicator, 2 nrindicator
      UNION
      SELECT ''Stoc la moment''           indicator, 3 nrindicator
      UNION
      SELECT ''Consum rezervat''          indicator, 4 nrindicator
      UNION
      SELECT ''Comenzi in curs''          indicator, 5 nrindicator
      UNION
      SELECT ''Propunere de cumparare''   indicator, 6 nrindicator
      UNION
      SELECT ''Propunere de cumparare''   indicator, 7 nrindicator
    ) b
  ';
  EXECUTE aSQL;

  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_NAPROVIZ5.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  sInsert := '
  INSERT INTO ' || tmpName || '(
    DENUMIRE,
    INDICATOR,
    STOCMIN,
    PRET,
    FURNIZOR,
    CANTMIN,
    ORDINE,
    L1,
    L2,
    L3,
    L4,
    L5,
    L6,
    L7,
    L8,
    L9,
    L10,
    L11,
    L12 ' || gUserFields || ')
  SELECT
    tmp.DENUMIRE,
    tmp.INDICATOR,
    tmp.STOCMIN,
    tmp.PRET,
    tmp.FURNIZOR,
    tmp.CANTMIN,
    tmp.NRINDICATOR,
    tmp.L1,
    tmp.L2,
    tmp.L3,
    tmp.L4,
    tmp.L5,
    tmp.L6,
    tmp.L7,
    tmp.L8,
    tmp.L9,
    tmp.L10,
    tmp.L11,
    tmp.L12 ' || gUserAlias || '
  FROM NECESAR5 tmp
    inner join nartobj obj on tmp.codobiect = obj.codobiect' || gSuplJoins || '
  where tmp.userid = ' || vUserID::varchar|| '
  order by nrindicator';

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  DELETE FROM tmp_stocreal_nec5 WHERE userid = vUserID;
  DELETE FROM NECESAR5 WHERE USERID = vUserID;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz6_processlist</obj_name>
  <obj_hashval>a3bec377e28ac55a347d91136432e07d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz6_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert        varchar := '';
  sSelect        varchar := '';
  vSelStocReal   varchar := '';
  vUserID        numeric;
  vCondSub_G     varchar := '';
  vSelIes_Per    varchar := '';
  vSelIes_PerP   varchar := '';
  vSelIes_Per12  varchar := '';
  vSelIes_Per3   varchar := '';
  vZiuaIniC      date;
  vZiuaFinC      date;
  vZiuaIni       date;
  vZiuaFin       date;
  vTipVanz       varchar := '';
  vToateGest     boolean;
  vToateIOArt    boolean;
  vCateGest      numeric;
  vCatelGest     numeric;
  vAux           varchar := '';
  sUltCant       varchar := '';
  vUltAchiz      BOOLEAN;
  vFiltruTermen  varchar := '';
  vCondSub_C     varchar := '';
  LastPret       NUMERIC(1);
  gSuplCols      VARCHAR := 'NARTOBJ NAO, NART NA, NARTOBJSUBUNIT NAOS, NUM NUM, NPART PROD, NCLASEA CLSA, NCLASEAS CLSAS';
  gUserFields    VARCHAR := '';
  gUserAlias     VARCHAR := '';
  gNullAlias     VARCHAR := '';
  gSuplJoins     VARCHAR := '';
BEGIN
  --Florin 26.02.2025 - fixat 64858
  --Florin 05.10.2023 - sinc. Oracle
  --Adina 20.04.2021 - sinc.Oracle
  --Adina 02 septembrie 2020
  --Florin 05.12.2020
  --Florin 07.12.2020 - fixat #41270
  BEGIN
    SELECT TO_NUMBER(COALESCE(fnc_getvalconstantalucru('LastPretGenCmdF'),'0')) INTO STRICT LastPret;
    EXCEPTION WHEN OTHERS THEN LastPret := 0;
  END;

  vUserId    := COALESCE(current_setting('PKG_GLOBALS.USERID', true)::numeric, 0);
  vCondSub_G := PKG_LIST_BASE_UTILS_COND_SUBUNIT('G', 'CODSUBUNIT',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_NAPROVIZ6.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  vZiuaIniC     := to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIniC', true),'dd.mm.yyyy');
  vZiuaFinC     := to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFinC', true),'dd.mm.yyyy');
  vZiuaIni      := to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaIni',  true),'dd.mm.yyyy');
  vZiuaFin      := to_date(current_setting('PKG_LIST_BASE_NAPROVIZ2.vZiuaFin',  true),'dd.mm.yyyy');
  vTipVanz      := COALESCE(current_setting('PKG_LIST_BASE_NAPROVIZ2.vTipVanz', true),'');
  vToateGest    := current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateGest', true)::boolean;   --(pkg_list_base_naproviz2_GetAllGest()  = 1);
  vToateIOArt   := current_setting('PKG_LIST_BASE_NAPROVIZ2.vToateIoart',true)::boolean;   --(pkg_list_base_naproviz2_GetAllIOArt() = 1);
  vUltAchiz     := current_setting('PKG_LIST_BASE_NAPROVIZ2.vUltAchiz',  true)::boolean;
  vCondSub_C    := PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL);
  vFiltruTermen := '';
--INSERT INTO X(VIEW_NAME, TEST) VALUES ('SINSERT1', SINSERT);
  IF  current_setting('PKG_LIST_BASE_NAPROVIZ2.vCuTermen', true)::boolean THEN
    vFiltruTermen := ' AND C1.TERMEN &lt;= ''' || coalesce(current_setting('PKG_LIST_BASE_NAPROVIZ2.vTermen', true),'') || ''' ';
  END IF;
--INSERT INTO X(VIEW_NAME, TEST) VALUES ('SINSERT2', SINSERT);
  DELETE FROM TMP_STOCREAL;
  DELETE FROM TMP_CMD WHERE USERID = VUSERID;

  sSelect := 'INSERT INTO tmp_cmd(codobiect,cantc,canta,resta,tip,userid,auxfield,D1,D2,D3)
  SELECT C1.CodObiect,
    SUM(C1.CantComandat) CantC,
    SUM(C1.CantAcceptat) CantA,
    SUM(C1.RestAcceptat) RestA, ''CF'',' || coalesce(vUserId::varchar,'') || ',
    String_Agg(C.nrdoc::varchar,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' order by C.nrdoc),
    C1.D1,C1.D2,C1.D3
  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 ' || coalesce(vCondSub_C,'') || '
    AND C1.RestAcceptat &gt; 0
  GROUP BY C1.CodObiect,C1.D1,C1.D2,C1.D3';
  EXECUTE sSelect;
--INSERT INTO X(VIEW_NAME, TEST) VALUES ('SINSERT3', SINSERT);
  vSelStocReal := '
  SELECT NS.CODOBIECT, SUM(NS.REST) CANT, ''REAL''
  FROM NIRSTOC NS
    INNER JOIN NIR   N ON N.CODNIR  = NS.CODNIR
    INNER JOIN NGEST G ON G.CODGEST = N.GEST ' || coalesce(vCondSub_G,'') || '
  WHERE NS.REST &lt;&gt; 0';

  vSelIes_Per := '
  SELECT NS.CODOBIECT, SUM(L1.CANT) CANT, ''IES''
  FROM LIVR L
    INNER JOIN LIVR1   l1 ON L1.CODLIVR    = L.CODLIVR
    INNER JOIN IESIRI  I  ON L.CODIES      = I.CODIES
    INNER JOIN IESIRI1 I1 ON I1.CODIES     = I.CODIES AND L1.CODIES1 = I1.CODIES1
    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 ' || coalesce(vCondSub_G,'') || '
  WHERE L.DATALIVR BETWEEN ''' || coalesce((vZiuaIniC)::varchar,'') || ''' AND ''' || coalesce((vZiuaFinC)::varchar,'') || '''
    AND coalesce(I.ANULAT,0) = 0 AND I.OPERAT = 1 AND I.TIPDOC IN (' || coalesce(vTipVanz,'') || ')';
--INSERT INTO X(VIEW_NAME, TEST) VALUES ('SINSERT4', SINSERT);
  vSelIes_Per12 := '
  SELECT NS.CODOBIECT, SUM(L1.CANT) CANT, ''IES12''
  FROM LIVR L
    INNER JOIN LIVR1   l1 ON L1.CODLIVR    = L.CODLIVR
    INNER JOIN IESIRI  I  ON L.CODIES      = I.CODIES
    INNER JOIN IESIRI1 I1 ON I1.CODIES     = I.CODIES AND L1.CODIES1 = I1.CODIES1
    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 ' || coalesce(vCondSub_G,'') || '
  WHERE L.DATALIVR BETWEEN to_date(''' || coalesce(to_char(add_months(vZiuaIniC, -12), 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') AND
    to_date(''' || coalesce(to_char(vZiuaIniC - 1, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')
    AND coalesce(I.ANULAT,0) = 0 AND I.OPERAT = 1 AND I.TIPDOC IN (' || coalesce(vTipVanz,'') || ')';
--INSERT INTO X(VIEW_NAME, TEST) VALUES ('SINSERT5', SINSERT);
  vSelIes_Per3 := '
  SELECT NS.CODOBIECT, SUM(L1.CANT) CANT, ''IES3''
  FROM LIVR L
    INNER JOIN LIVR1   l1 ON L1.CODLIVR    = L.CODLIVR
    INNER JOIN IESIRI  I  ON L.CODIES      = I.CODIES
    INNER JOIN IESIRI1 I1 ON I1.CODIES     = I.CODIES AND L1.CODIES1 = I1.CODIES1
    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 ' || coalesce(vCondSub_G,'') || '
  WHERE L.DATALIVR BETWEEN to_date(''' || coalesce(to_char(add_months(vZiuaIniC, -3), 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') AND
    to_date(''' || coalesce(to_char(vZiuaIniC - 1, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')
    AND coalesce(I.ANULAT,0) = 0 AND I.OPERAT = 1 AND I.TIPDOC IN (' || coalesce(vTipVanz,'') || ')';
--INSERT INTO X(VIEW_NAME, TEST) VALUES ('SINSERT6', SINSERT);
  vSelIes_PerP := '
  SELECT NS.CODOBIECT, SUM(L1.CANT) CANT, ''IESP''
  FROM LIVR L
    INNER JOIN LIVR1   l1 ON L1.CODLIVR    = L.CODLIVR
    INNER JOIN IESIRI  I  ON L.CODIES      = I.CODIES
    INNER JOIN IESIRI1 I1 ON I1.CODIES     = I.CODIES AND L1.CODIES1 = I1.CODIES1
    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.DATALIVR BETWEEN ''' || coalesce((vZiuaIni)::varchar,'') || ''' AND ''' || coalesce((vZiuaFin)::varchar,'') || '''
    AND coalesce(I.ANULAT,0) = 0 AND I.OPERAT = 1 AND I.TIPDOC IN (' || coalesce(vTipVanz,'') || ')';
--INSERT INTO X(VIEW_NAME, TEST) VALUES ('SINSERT7', SINSERT);
  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';
    vAux := '
        AND';
    IF  vCateLGest = 0 THEN
      vAux := coalesce(vAux,'') || ' N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
    ELSIF vCateGest = 0 THEN
      vAux := coalesce(vAux,'') || ' NS.CODLOCATIE::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'') ';
    ELSE
      vAux := coalesce(vAux,'') || ' (N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') OR NS.CODLOCATIE::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'')) ';
    END IF;
    vSelStocReal   := coalesce(vSelStocReal,'')  || coalesce(vAux,'');
    vSelIes_Per    := coalesce(vSelIes_Per,'')   || coalesce(vAux,'');
    vSelIes_Per12  := coalesce(vSelIes_Per12,'') || coalesce(vAux,'');
    vSelIes_Per3   := coalesce(vSelIes_Per3,'')  || coalesce(vAux,'');
    vSelIes_PerP   := coalesce(vSelIes_PerP,'')  || coalesce(vAux,'');
  END IF;
--INSERT INTO X(VIEW_NAME, TEST) VALUES ('SINSERT8', SINSERT);
  IF  NOT vToateIOArt THEN
    vAux := '
        AND NS.CODIOART::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
    vSelStocReal   := coalesce(vSelStocReal,'')  || coalesce(vAux,'');
    vSelIes_Per    := coalesce(vSelIes_Per,'')   || coalesce(vAux,'');
    vSelIes_Per12  := coalesce(vSelIes_Per12,'') || coalesce(vAux,'');
    vSelIes_Per3   := coalesce(vSelIes_Per3,'')  || coalesce(vAux,'');
    vSelIes_PerP   := coalesce(vSelIes_PerP,'')  || coalesce(vAux,'');
  END IF;
--INSERT INTO X(VIEW_NAME, TEST) VALUES ('SINSERT9', SINSERT);
  vSelStocReal := coalesce(vSelStocReal,'') || '
    GROUP BY NS.CODOBIECT';
  vSelIes_Per := coalesce(vSelIes_Per,'') || '
    GROUP BY NS.CODOBIECT';
  vSelIes_Per12 := coalesce(vSelIes_Per12,'') || '
    GROUP BY NS.CODOBIECT';
  vSelIes_Per3 := coalesce(vSelIes_Per3,'') || '
    GROUP BY NS.CODOBIECT';
  vSelIes_PerP := coalesce(vSelIes_PerP,'') || '
    GROUP BY NS.CODOBIECT';
  EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip) ' || coalesce(vSelStocReal,'');
  EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip) ' || coalesce(vSelIes_Per,'');
  EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip) ' || coalesce(vSelIes_Per12,'');
  EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip) ' || coalesce(vSelIes_Per3,'');
  EXECUTE 'INSERT INTO tmp_stocreal(codobiect,cant,tip) ' || coalesce(vSelIes_PerP,'');
  IF vUltAchiz THEN
    sSelect :=  'INSERT INTO tmp_cmd(codobiect,D1,tip,UserID)
                 SELECT CODOBIECT, MAX(CODNIRSTOC) CODNIRSTOC,''ULT'',' || coalesce(vUserID::varchar,'') ||
                ' FROM (SELECT NS.CODNIRSTOC,NS.CODNIR,NS.FURN,NS.CODNIRSTOCPARINTE,NS.CODOBIECT,NS.DATAACHIZ,
                              dense_rank() over(partition by NS.CODOBIECT order by NS.DATAACHIZ desc, NS.CODNIRSTOC desc) NR
                       FROM NIRSTOC NS
                            INNER JOIN NIR   N ON N.CODNIR  = NS.CODNIR
                            INNER JOIN NGEST G ON G.CODGEST = N.GEST ';
                if tmpName = 'TMP_LST_NAPR6' THEN
                  if LastPret &lt;&gt; 1 THEN
                    sSelect := sSelect||coalesce(vCondSub_G,'')||chr(13);
                  END IF;
                ELSE
                  sSelect := sSelect||coalesce(vCondSub_G,'')||chr(13);
                END IF;
                sSelect := sSelect||'WHERE NS.FURN &gt; 0 AND Nvl(NS.CODNIRSTOCPARINTE,0) = 0 AND N.TIPNIR IN (1,2,3,4,5,6)
                 ) xx
                 WHERE xx.NR=1
                 GROUP BY CODOBIECT';
    EXECUTE sSelect;

    sSelect :=  'INSERT INTO tmp_cmd(codobiect,D1,tip,UserID)
                 SELECT CODOBIECT, MAX(CODNIRSTOC) CODNIRSTOC,''PULT'',' || coalesce(vUserID::varchar,'') ||  '
                 FROM (
                       SELECT NS.CODOBIECT, NS.CODNIRSTOC
                              ,dense_rank() over(partition by NS.CODOBIECT order by NS.DATAACHIZ desc, NS.CODNIRSTOC desc) NR
                       FROM (SELECT CODNIRSTOC,CODNIR,FURN,CODNIRSTOCPARINTE,CODOBIECT,DATAACHIZ FROM NIRSTOC WHERE NOT DATAACHIZ IS NULL
                             EXCEPT  --MINUS
                             SELECT T.D1 codnirstoc, NSS.CODNIR,NSS.FURN,NSS.CODNIRSTOCPARINTE,NSS.CODOBIECT,NSS.DATAACHIZ
                             FROM TMP_CMD T
                                  INNER JOIN NIRSTOC NSS ON NSS.CODNIRSTOC = T.D1
                             WHERE T.USERID = ' || coalesce(VUSERID::varchar,'') || ' AND T.TIP = ''ULT''
                            ) NS
                            INNER JOIN NIR   N ON N.CODNIR  = NS.CODNIR
                            INNER JOIN NGEST G ON G.CODGEST = N.GEST ';
                if tmpName = 'TMP_LST_NAPR6' THEN
                  if LastPret &lt;&gt; 1 THEN
                    sSelect := sSelect||coalesce(vCondSub_G,'')||chr(13);
                  END IF;
                ELSE
                  sSelect := sSelect||coalesce(vCondSub_G,'')||chr(13);
                END IF;
                sSelect := sSelect||'WHERE NS.FURN &gt; 0 AND Nvl(NS.CODNIRSTOCPARINTE,0) = 0 AND N.TIPNIR IN (1,2,3,4,5,6)
                 ) xx
                 WHERE xx.NR=1
                 GROUP BY CODOBIECT';
    EXECUTE sSelect;
    sUltCant := 'UNS.CANTNIR ULTCANT';
  ELSE
    sUltCant := '0 ULTCANT';
  END IF;
--INSERT INTO X(VIEW_NAME, TEST) VALUES ('SINSERT', SINSERT);
  IF  tmpName = 'TMP_LST_NAPR6' THEN
    DELETE FROM TMP_LST_NAPR6;
    sInsert :=
   'INSERT INTO ' || tmpName || '(
      DENUMIRE,
      STOCMIN,
      STOC,
      CANT,
      CANTPREC,
      RATA,
      NECESAR,
      CODINTERN,
      CODEXTERN,
      UM,
      CODUM1,
      CODOBIECT,
      PRODUCATOR,
      ULTFURN,
      ULTPRACHIZ,
      CODULTFURN,
      CODLOCATIE,
      CODMONEDA,
      CODCATALOG,
      IES12,
      IES3,
      NECESAR2,
      PULTFURN,
      PULTPRACHIZ,
      RESTA_CF,
      ULTCANT
      )
    SELECT
      DENUMIRE,
      STOCMIN,
      STOC,
      CANT,
      CANTPREC,
      case when cantprec = 0 then 0 else CANT/CANTPREC end,
      case when cantprec = 0 then 0 else ROUND((CANT - STOC)*CANT/CANTPREC) end,
      CODINTERN,
      CODEXTERN,
      UM,
      CODUM1,
      CODOBIECT,
      PRODUCATOR,
      ULTFURN,
      ULTPRACHIZ,
      CODULTFURN,
      CODLOCATIE,
      CODMONEDA,
      CODCATALOG,
      IES12,
      IES3,
      NECESAR2,
      PULTFURN,
      PULTPRACHIZ,
      RESTA_CF,
      ULTCANT
    FROM (
    SELECT
      NAO.DENUMIRE,
      NAOS.STOCMIN,
      coalesce(SR.CANT,0) STOC,
      coalesce(IP.CANT,0) CANT,
      coalesce(IPP.CANT,0) CANTPREC,
      NAO.CODINTERN,
      NAO.CODEXTERN,
      NUM.DEN_UM UM,
      NUM1.CODUM1,
      NAO.CODOBIECT,
      PROD.DEN_PART PRODUCATOR,
      UF.DEN_PART ULTFURN,
      coalesce(UNS.PRET,0) - coalesce(UNS.ADAOS,0) ULTPRACHIZ,
      UF.CODPART CODULTFURN,
      UINTR.CODLOCATIE,
      UINTR.MONEDA CODMONEDA,
      case
        when NA.codexternart is null then NA.sufixcodextern
        when NA.sufixcodextern is null then NA.codexternart
        else NA.codexternart||''_''||NA.sufixcodextern
      end CODCATALOG,
      Round(coalesce(I12.CANT,0)/12,2) IES12,
      Round(coalesce(I3.CANT,0)/3,2) IES3,
      case when (coalesce(IP.CANT,0)+coalesce(IPP.CANT,0))/2 - coalesce(SR.CANT,0) &lt; 0 then 0 else (coalesce(IP.CANT,0)+coalesce(IPP.CANT,0))/2 - coalesce(SR.CANT,0) end NECESAR2,
      PUF.DEN_PART PULTFURN,
      coalesce(PUNS.PRET,0) - coalesce(PUNS.ADAOS,0) PULTPRACHIZ,
      CF.RESTA RESTA_CF,
      ' || coalesce(sUltCant,'') || '
    FROM NARTOBJ NAO
      INNER JOIN NART           NA    ON NA.CODARTICOL    = NAO.CODARTICOL
      INNER JOIN NUM                  ON NUM.CODUM        = NA.UM
      LEFT  JOIN TMP_CMD        X     ON X.CODOBIECT      = NAO.CODOBIECT AND X.TIP  = ''ULT''  AND X.USERID  = ' || coalesce(VUSERID::varchar,'') || '
      LEFT  JOIN TMP_CMD        PX    ON PX.CODOBIECT     = NAO.CODOBIECT AND PX.TIP = ''PULT'' AND PX.USERID = ' || coalesce(VUSERID::varchar,'') || '
      LEFT  JOIN NIRSTOC        UNS   ON UNS.CODNIRSTOC   = X.D1
      LEFT  JOIN NIR            UNIR  ON UNIR.CODNIR      = UNS.CODNIR
      LEFT  JOIN INTRARI        UINTR ON UINTR.CODINTR    = UNIR.CODINTR
      LEFT  JOIN NPART          UF    ON UF.CODPART       = UNS.FURN
      LEFT  JOIN NIRSTOC        PUNS  ON PUNS.CODNIRSTOC  = PX.D1
      LEFT  JOIN NPART          PUF   ON PUF.CODPART      = PUNS.FURN
      LEFT  JOIN NUM1                 ON NUM.CODUM        = NUM1.CODUM AND coalesce(NUM1.SECUNDARA,0) = 0
      LEFT  JOIN NARTOBJSUBUNIT NAOS  ON NAO.CODOBIECT    = NAOS.CODOBIECT
                                        and (NAOS.codgest is null or NAOS.codgest = 0)
                                        AND NAOS.SUBUNITATE = ' || current_setting('PKG_GLOBALS.SUBUNITATE', true) || '
      LEFT  JOIN TMP_STOCREAL   SR    ON SR.CODOBIECT     = NAO.CODOBIECT AND SR.TIP = ''REAL''
      LEFT  JOIN NPART          PROD  ON PROD.CODPART     = NAO.CODPRODUCATOR
      LEFT  JOIN TMP_STOCREAL   IP    ON IP.CODOBIECT     = NAO.CODOBIECT AND IP.TIP = ''IES''
      LEFT  JOIN TMP_STOCREAL   I12   ON I12.CODOBIECT    = NAO.CODOBIECT AND I12.TIP = ''IES12''
      LEFT  JOIN TMP_STOCREAL   I3    ON I3.CODOBIECT     = NAO.CODOBIECT AND I3.TIP = ''IES3''
      LEFT  JOIN TMP_STOCREAL   IPP   ON IPP.CODOBIECT    = NAO.CODOBIECT AND IPP.TIP = ''IESP''
      LEFT  JOIN NCLASEA        CLSA  ON CLSA.CODCLASEA   = NA.CLASA
      LEFT  JOIN NCLASEAS       CLSAS ON CLSAS.CODCLASEAS = NA.CLASASTATIST
      LEFT  JOIN TMP_CMD        CF    ON CF.CODOBIECT     = NAO.CODOBIECT AND CF.TIP = ''CF'' AND CF.USERID = ' || coalesce(VUSERID::varchar,'') || '
    WHERE NA.TIPARTICOL = 0::varchar AND coalesce(NAO.INACTIV,0) = 0 ';

    IF   current_setting('PKG_LIST_BASE_NAPROVIZ2.vClasa', true)::numeric &gt; 0 THEN
      sInsert := sInsert || ' and na.clasa = ' || current_setting('PKG_LIST_BASE_NAPROVIZ2.vClasa', true);
    END IF;
    IF  current_setting('PKG_LIST_BASE_NAPROVIZ2.vClasaS', true)::numeric &gt; 0 THEN
      sInsert := sInsert || ' and na.clasastatist = ' || current_setting('PKG_LIST_BASE_NAPROVIZ2.vClasaS', true);
    END IF;
    IF  current_setting('PKG_LIST_BASE_NAPROVIZ2.vProd', true)::numeric &gt; 0 THEN
      sInsert := sInsert || ' and nao.codproducator = ' || current_setting('PKG_LIST_BASE_NAPROVIZ2.vProd', true);
    END IF;
    sInsert := sInsert || ') A_PG';
  ELSE
    sInsert :=
    'INSERT INTO ' || tmpName || '(
      DENUMIRE,
      STOCMIN,
      STOC,
      CANT,
      CANTPREC,
      RATA,
      NECESAR,
      ULTFURN,
      ULTPRACHIZ,
      IES12,
      IES3,
      NECESAR2,
      PULTFURN,
      PULTPRACHIZ,
      RESTA_CF,
      ULTCANT ' || gUserFields || ')
    SELECT
      NAO.DENUMIRE,
      NAOS.STOCMIN,
      coalesce(SR.CANT,0) STOC,
      coalesce(IP.CANT,0) CANT,
      coalesce(IPP.CANT,0) CANTPREC,
      case when coalesce(IPP.CANT,0) = 0 then 0 else coalesce(IP.CANT,0)/coalesce(IPP.CANT,0) end RATA,
      case when coalesce(IPP.CANT,0) = 0 then 0 else ROUND((coalesce(IP.CANT,0) - coalesce(SR.CANT,0))*coalesce(IP.CANT,0)/coalesce(IPP.CANT,0)) end NECESAR,
      UF.DEN_PART ULTFURN,
      coalesce(UNS.PRET,0) - coalesce(UNS.ADAOS,0) ULTPRACHIZ,
      Round(coalesce(I12.CANT,0)/12,2) IES12,
      Round(coalesce(I3.CANT,0)/3,2) IES3,
      case when (coalesce(IP.CANT,0)+coalesce(IPP.CANT,0))/2 - coalesce(SR.CANT,0) &lt; 0 then 0 else (coalesce(IP.CANT,0)+coalesce(IPP.CANT,0))/2 - coalesce(SR.CANT,0) end NECESAR2,
      PUF.DEN_PART PULTFURN,
      coalesce(PUNS.PRET,0) - coalesce(PUNS.ADAOS,0) PULTPRACHIZ,
      CF.RESTA RESTA_CF,
      ' || coalesce(sUltCant,'') || '  ' || gUserAlias || '
    FROM NARTOBJ NAO
      INNER JOIN NART          NA    ON NA.CODARTICOL    = NAO.CODARTICOL
      INNER JOIN NUM                 ON NUM.CODUM        = NA.UM
      LEFT JOIN TMP_CMD        X     ON X.CODOBIECT      = NAO.CODOBIECT AND X.TIP  = ''ULT''  AND X.USERID  = ' || coalesce(VUSERID::varchar,'') || '
      LEFT JOIN TMP_CMD        PX    ON PX.CODOBIECT     = NAO.CODOBIECT AND PX.TIP = ''PULT'' AND PX.USERID = ' || coalesce(VUSERID::varchar,'') || '
      LEFT JOIN NIRSTOC        UNS   ON UNS.CODNIRSTOC   = X.D1
      LEFt JOIN NPART          UF    ON UF.CODPART       = UNS.FURN
      LEFT JOIN NIRSTOC        PUNS  ON PUNS.CODNIRSTOC  = PX.D1
      LEFT JOIN NPART          PUF   ON PUF.CODPART      = PUNS.FURN
      LEFT JOIN NARTOBJSUBUNIT NAOS  ON NAO.CODOBIECT    = NAOS.CODOBIECT
                                        and (NAOS.codgest is null or NAOS.codgest = 0)
                                        AND NAOS.SUBUNITATE = ' || current_setting('PKG_GLOBALS.SUBUNITATE', true) || '
      LEFT JOIN TMP_STOCREAL   SR    ON SR.CODOBIECT     = NAO.CODOBIECT AND SR.TIP = ''REAL''
      LEFT JOIN NPART          PROD  ON PROD.CODPART     = NAO.CODPRODUCATOR
      LEFT JOIN TMP_STOCREAL   IP    ON IP.CODOBIECT     = NAO.CODOBIECT AND IP.TIP = ''IES''
      LEFT JOIN TMP_STOCREAL   IPP   ON IPP.CODOBIECT    = NAO.CODOBIECT AND IPP.TIP = ''IESP''
      LEFT JOIN TMP_STOCREAL   I12   ON I12.CODOBIECT    = NAO.CODOBIECT AND I12.TIP = ''IES12''
      LEFT JOIN TMP_STOCREAL   I3    ON I3.CODOBIECT     = NAO.CODOBIECT AND I3.TIP = ''IES3''
      LEFT JOIN NCLASEA        CLSA  ON CLSA.CODCLASEA   = NA.CLASA
      LEFT JOIN NCLASEAS       CLSAS ON CLSAS.CODCLASEAS = NA.CLASASTATIST
      LEFT JOIN TMP_CMD        CF    ON CF.CODOBIECT     = NAO.CODOBIECT AND CF.TIP = ''CF'' AND CF.USERID = ' || coalesce(VUSERID::varchar,'') || '' || gSuplJoins || '
    WHERE NA.TIPARTICOL = 0::varchar AND coalesce(NAO.INACTIV,0) = 0 ';
  END IF;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  sInsert := 'update ' || tmpName || ' set necesar = 0 where necesar &lt; 0';
  EXECUTE sInsert;
  sInsert := 'update ' || tmpName || ' set necesar2 = case when trunc(necesar2) = necesar2 then necesar2 else trunc(necesar2) + 1 end';
  EXECUTE sInsert;
END;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nart_setguseralias</obj_name>
  <obj_hashval>11bc759382521c09139456a2749d516b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nart_setguseralias(aguseralias character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_NART.gUserAlias',agUserAlias,false);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nclasea_setjoinuri</obj_name>
  <obj_hashval>44528cd1c518292b38decd516463b109</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nclasea_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Adina iulie 2020
PERFORM Pkg_List_Struct_SetTableSpec( current_setting('PKG_LIST_BASE_NCLASEA.gSuplCols', true));
PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nir_gsupljoins</obj_name>
  <obj_hashval>8171c781839c74b2b3215abb44bbe6c1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_gsupljoins(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NIR.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_nir_guseralias</obj_name>
  <obj_hashval>5c85d77eeb44410829ec087247f977e4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_guseralias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NIR.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_nomartamb_setjoinuri</obj_name>
  <obj_hashval>d5ff55980bc085bfc65235f68cc76cc6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nomartamb_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
PERFORM Pkg_List_Struct_SetTableSpec( current_setting('PKG_LIST_BASE_NOMARTAMB.gSuplCols', true));
PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nomartamb_setparams</obj_name>
  <obj_hashval>1c14b6ef159365805174e23a2b6cd49c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nomartamb_setparams(ptoateart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_NOMARTAMB.vToateArt', pToateArt::varchar, false);
end;

$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nomgest_setjoinuri</obj_name>
  <obj_hashval>b08e75954949a992759d2da8eb9afd7b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nomgest_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Adina iulie 2020
PERFORM Pkg_List_Struct_SetTableSpec( current_setting('PKG_LIST_BASE_NOMGEST.gSuplCols', true));
PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_normeap_processlist</obj_name>
  <obj_hashval>81400b1a9d0c90e2b9e56cd51ea8fc14</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_normeap_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;
  AnLunaLucru numeric;
  sSelect0    varchar;
  sSelect1    varchar;
  gStocField  varchar;
  gStocAlias  varchar;
  vUserID     numeric;
BEGIN
  --Laura 04.11.2021 - sinc Oracle (04.11.2021)
  --Adina 16.04.2021 - alstart,alstop
  --Adina 18.02.2021 - dupa modif.Oracle din 17.02.2021
  --Bogdan 14.09.2020
  AnLunaLucru:= getanlucru() * 12 + getlunalucru();

  gSuplCols  := 'NARTOBJ OBJP, NARTOBJ OBJC, PRODCOMP PC, NCLASEA CLSCOMP, NGEST SECTIE';
  vUserID    := current_setting ('PKG_GLOBALS.USERID', true) ::numeric;
  gStocField := ' ';
  gStocAlias := ' ';

  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_NORMEAP.gSuplCols',gSuplCols,false);

  IF (PKG_LIST_BASE_CONSUM_PROD_GetAllArt() ) = 1 THEN
    DELETE FROM tmp_prodcomp_man WHERE userid = vuserid;

    INSERT INTO tmp_prodcomp_man (codprodcomp, cant, pret, userid)
    (SELECT PC.codprodcomp, PC.cant, PC.Pret, vUserID FROM prodcomp PC);
  END IF;

  sInsert := 'INSERT INTO ' || tmpName
            || ' (
            NAV_CodDoc,
            NAV_TipDoc,
            Tab,
            DenTab,
            CODNORMA,
            CODPRODCOMP,
            PR_ART,
            PR_CODEXTERN,
            PR_CODINTERN,
            SECTIE,
            PR_CANT,
            PR_PRET,
            PR_PRET_REF,
            COMP_ART,
            COMP_CODEXTERN,
            COMP_CODINTERN,
            COMP_CODCATALOG,
            COMP_UM,
            COMP_CANT,
            COMP_PRET,
            COMP_VALOARE,
            COMP_TIP,
            COMP_IOART,
            COMP_UM1,
            COMP_CANTUM1,
            COMP_D1,
            COMP_D2,
            COMP_D3,
            COMP_INLOCUIT,
            RETETAIMP,
            NORMAIMP,
            RETETAACTIVA,
            NORMAACTIVA,
            DATACREARE,
            DATAMODIFICARE'
            || coalesce (gUserFields ,'')
            || ') ';
  sSelect0 := '
        SELECT
          PC.CODPRODCOMP    NAV_CodDoc,
          504               NAV_TipDoc,
          ''Reteta''        Tab,
          PC.Obs            DenTab,
          null              CODNORMA,
          PC.CODPRODCOMP,
          OBJP.DENUMIRE    PR_ART,
          OBJP.CODEXTERN   PR_CODEXTERN,
          OBJP.CODINTERN   PR_CODINTERN,
          SECTIE.DEN_GEST  SECTIE,
          PC.CANT          PR_CANT,
          PC.PRET          PR_PRET,
          P1.PRETREFERINTA PR_PRET_REF,
          OBJC.DENUMIRE    COMP_ART,
          OBJC.CODEXTERN   COMP_CODEXTERN,
          OBJC.CODINTERN   COMP_CODINTERN,
          ARTC.CODEXTERNART ||''_'' ||ARTC.SUFIXCODEXTERN COMP_CODCATALOG,
          NUMC.DEN_UM               COMP_UM,
          MAT.CANT                  COMP_CANT,
          MAT.PRET                  COMP_PRET,
          MAT.PRET * MAT.CANT       COMP_VALOARE,
          case
            when MAT.Tip = 1 then ''Complex''
            when MAT.Tip = 2 then ''Reper''
            when MAT.Tip = 3 then ''Material''
            when MAT.Tip = 4 then ''Lohn''
            when MAT.Tip = 5 then ''Fix''
            else ''Material''
          end          COMP_TIP,
          CONTC.SIMBOL COMP_IOART,
          NUMC1.DEN_UM COMP_UM1,
          case when coalesce (MAT.CANTUM1,0) = 0 then null else MAT.CANTUM1 end COMP_CANTUM1,
          case when coalesce (MAT.D1,0) = 0 then null else MAT.D1 end COMP_D1,
          case when coalesce (MAT.D2,0) = 0 then null else MAT.D2 end COMP_D2,
          case when coalesce (MAT.D3,0) = 0 then null else MAT.D3 end COMP_D3,
          CASE
            WHEN NORNR.NRNORME = 0 THEN ''NU''
            WHEN NORNR.NRNORME = NORNROBJ.NRNORME THEN ''NU''
            ELSE ''DA''
          END COMP_INLOCUIT,
          CASE WHEN PC.IMPLICIT = 1 THEN ''DA'' ELSE ''NU'' END  RETETAIMP,
          NULL NORMAIMP,
          CASE WHEN PC.INACTIV = 1 THEN ''NU'' ELSE ''DA'' END  RETETAACTIVA,
          NULL          NORMAACTIVA,
          PC.DATACREARE DATACREARE,
          NULL DATAMODIFICARE '
            || coalesce (gUserAlias ,'') || '
        FROM PRODCOMP                   PC
          INNER JOIN TMP_PRODCOMP_MAN   TMP    ON PC.CodProdComp = TMP.CodProdComp
          INNER JOIN PRODMAT            MAT    ON PC.CODPRODCOMP = MAT.CODPRODCOMP
          INNER JOIN (SELECT MIN(INDEXLOCAL) INDEXLOCAL, CODPRODCOMP FROM PRODGEST GROUP BY CODPRODCOMP)  MINIDX ON MINIDX.CODPRODCOMP = PC.CODPRODCOMP
          INNER JOIN PRODGEST           PG     ON PG.CODPRODCOMP  = MINIDX.CODPRODCOMP AND PG.INDEXLOCAL = MINIDX.INDEXLOCAL
          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 (SELECT COUNT(*) NRNORME, CODPRODCOMP FROM NORMEMAT GROUP BY CODPRODCOMP)  NORNR ON NORNR.CODPRODCOMP = PC.CODPRODCOMP
          LEFT JOIN (SELECT COUNT(*) NRNORME, CODPRODCOMP, CODOBIECT FROM NORMEMAT GROUP BY CODPRODCOMP, CODOBIECT)   NORNROBJ ON NORNROBJ.CODPRODCOMP = PC.CODPRODCOMP AND NORNROBJ.CODOBIECT = MAT.CODOBIECT
          LEFT JOIN NARTIMPLICITE  CIMP     ON CIMP.CODARTICOL  = ARTC.CODARTICOL AND CIMP.CODSUBUNIT = getsubunitate()
          LEFT JOIN NARTOBJIMP     OIMP     ON OIMP.CODOBIECT   = OBJC.CODOBIECT  AND OIMP.CODSUBUNIT = GETSUBUNITATE()
          LEFT JOIN IOART          IOC      ON IOC.CODIOART     = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN CIMP.CONTIMPLICIT ELSE COALESCE(OIMP.CONTIMPLICIT,0) END
          LEFT JOIN IOART1      IOCLUNA  ON IOCLUNA.CODIOART = IOC.CODIOART AND '||AnLunaLucru::varchar||' BETWEEN IOCLUNA.ALStart and IOCLUNA.ALStop
          LEFT JOIN NCONT          CONTC    ON CONTC.CODCONT    = IOCLUNA.CONT
          LEFT JOIN pretm          pm       ON pm.codobiect     = OBJP.codobiect AND pm.implicit = 1 AND pm.subunitatea =  (case when getsubunitate() = 1 then 2 else getsubunitate() end)
          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 NARTOBJ1 P1      ON P1.CodObiect = OBJP.CodObiect AND '||AnLunaLucru::varchar||' BETWEEN P1.ALStart and P1.ALStop
          LEFT JOIN NARTOBJ1 C1      ON C1.CodObiect = OBJC.CodObiect AND '||AnLunaLucru::varchar||' BETWEEN C1.ALStart and C1.ALStop '
            || coalesce (gSuplJoins ,'') || '
          WHERE 1=1
--            coalesce (P1.AnStart * 12 + P1.LunaStart, 0) = (SELECT coalesce (MAX (AnStart * 12 + LunaStart) , 0)
--              FROM NARTOBJ1 WHERE CodObiect = P1.CodObiect AND AnStart * 12 + LunaStart &lt;= getanlucru() * 12 + getlunalucru())
--            AND coalesce (C1.AnStart * 12 + C1.LunaStart, 0) = (SELECT coalesce (MAX (AnStart * 12 + LunaStart) , 0)
--              FROM NARTOBJ1 WHERE CodObiect = C1.CodObiect AND AnStart * 12 + LunaStart &lt;= getanlucru() * 12 + getlunalucru())
            AND TMP.USERID = ' || coalesce (vUserID::varchar,'');
  sSelect1 := '
        SELECT
          PC.CODPRODCOMP    NAV_CodDoc,
          504               NAV_TipDoc,
          ''Norma''         Tab,
          NOR.NORMA         DenTab,
          NOR.CODNORMA,
          PC.CODPRODCOMP,
          OBJP.DENUMIRE    PR_ART,
          OBJP.CODEXTERN   PR_CODEXTERN,
          OBJP.CODINTERN   PR_CODINTERN,
          SECTIE.DEN_GEST  SECTIE,
          PC.CANT          PR_CANT,
          PC.PRET          PR_PRET,
          P1.PRETREFERINTA PR_PRET_REF,
          OBJC.DENUMIRE    COMP_ART,
          OBJC.CODEXTERN   COMP_CODEXTERN,
          OBJC.CODINTERN   COMP_CODINTERN,
          ARTC.CODEXTERNART ||''_'' ||ARTC.SUFIXCODEXTERN COMP_CODCATALOG,
          NUMC.DEN_UM               COMP_UM,
          MAT.CANT                  COMP_CANT,
          MAT.PRET                  COMP_PRET,
          MAT.PRET * MAT.CANT       COMP_VALOARE,
          null                      COMP_TIP,
          CONTC.SIMBOL              COMP_IOART,
          NUMC1.DEN_UM              COMP_UM1,
          case when coalesce (MAT.CANTUM1,0) = 0 then null else MAT.CANTUM1 end COMP_CANTUM1,
          case when coalesce (MAT.D1,0) = 0 then null else MAT.D1 end COMP_D1,
          case when coalesce (MAT.D2,0) = 0 then null else MAT.D2 end COMP_D2,
          case when coalesce (MAT.D3,0) = 0 then null else MAT.D3 end COMP_D3,
          CASE
            WHEN NORNR.NRNORME = 0 THEN ''NU''
            WHEN NORNR.NRNORME = NORNROBJ.NRNORME AND coalesce (MT.CODMAT,0) &gt; 0 THEN ''NU''
            WHEN coalesce (MT.CODMAT,0) = 0 THEN ''DA''
            ELSE ''DA''
          END COMP_INLOCUIT,
          CASE WHEN PC.IMPLICIT  = 1 THEN ''DA'' ELSE ''NU'' END RETETAIMP,
          CASE WHEN NOR.IMPLICIT = 1 THEN ''DA'' ELSE ''NU'' END NORMAIMP,
          CASE WHEN PC.INACTIV   = 1 THEN ''NU'' ELSE ''DA'' END RETETAACTIVA,
          CASE WHEN NOR.ACTIV    = 1 THEN ''DA'' ELSE ''NU'' END NORMAACTIVA,
          PC.DATACREARE,
          CASE WHEN NOR.DATAACTIV &gt; NOR.DATAINACTIV THEN NOR.DATAACTIV ELSE NOR.DATAINACTIV END '
            || coalesce (gUserAlias ,'') || '
        FROM PRODCOMP                  PC
          INNER JOIN TMP_PRODCOMP_MAN  TMP ON PC.CodProdComp = TMP.CodProdComp
          INNER JOIN PRODNORME         NOR ON PC.CODPRODCOMP = NOR.CODPRODCOMP
          INNER JOIN NORMEMAT          MAT ON PC.CODPRODCOMP = MAT.CODPRODCOMP AND NOR.CODNORMA = MAT.CODNORMA
          INNER JOIN (SELECT MIN (INDEXLOCAL) INDEXLOCAL, CODPRODCOMP FROM PRODGEST GROUP BY CODPRODCOMP) MINIDX ON MINIDX.CODPRODCOMP = PC.CODPRODCOMP
          INNER JOIN PRODGEST      PG     ON PG.CODPRODCOMP  = MINIDX.CODPRODCOMP AND PG.INDEXLOCAL = MINIDX.INDEXLOCAL
          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 (SELECT COUNT(*) NRNORME, CODPRODCOMP FROM PRODNORME GROUP BY CODPRODCOMP)                      NORNR    ON NORNR.CODPRODCOMP    = PC.CODPRODCOMP
          LEFT  JOIN (SELECT COUNT(*) NRNORME, CODPRODCOMP, CODOBIECT FROM NORMEMAT GROUP BY CODPRODCOMP, CODOBIECT) NORNROBJ ON NORNROBJ.CODPRODCOMP = PC.CODPRODCOMP AND NORNROBJ.CODOBIECT = MAT.CODOBIECT
          LEFT  JOIN PRODMAT        MT       ON MT.CODPRODCOMP   = PC.CODPRODCOMP AND MT.CODOBIECT = MAT.CODOBIECT
          LEFT  JOIN NARTIMPLICITE  CIMP     ON CIMP.CODARTICOL  = ARTC.CODARTICOL AND CIMP.CODSUBUNIT = getsubunitate()
          LEFT  JOIN NARTOBJIMP     OIMP     ON OIMP.CODOBIECT   = OBJC.CODOBIECT  AND OIMP.CODSUBUNIT = GETSUBUNITATE()
          LEFT  JOIN IOART          IOC      ON IOC.CODIOART     = CASE WHEN COALESCE(OIMP.CONTIMPLICIT,0) = 0 THEN CIMP.CONTIMPLICIT ELSE COALESCE(OIMP.CONTIMPLICIT,0) END
          LEFT  JOIN IOART1     IOCLUNA  ON IOCLUNA.CODIOART = IOC.CODIOART AND '||AnLunaLucru::varchar||' BETWEEN IOCLUNA.ALStart and IOCLUNA.ALStop
          LEFT  JOIN NCONT          CONTC    ON CONTC.CODCONT    = IOCLUNA.CONT
          LEFT  JOIN pretm          pm       ON pm.codobiect     = OBJP.codobiect AND pm.implicit = 1 AND pm.subunitatea = ( case when getsubunitate() = 1 then 2 else getsubunitate() end)
          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 NARTOBJ1 P1      ON P1.CodObiect = OBJP.CodObiect AND '||AnLunaLucru::varchar||' BETWEEN P1.ALStart and P1.ALStop
          LEFT  JOIN NARTOBJ1 C1      ON C1.CodObiect = OBJC.CodObiect AND '||AnLunaLucru::varchar||' BETWEEN C1.ALStart and C1.ALStop '
            || coalesce (gSuplJoins ,'') || '
          WHERE 1=1
--            coalesce (P1.AnStart * 12 + P1.LunaStart, 0) = (SELECT coalesce (MAX (AnStart * 12 + LunaStart) , 0)
--              FROM NARTOBJ1 WHERE CodObiect = P1.CodObiect AND AnStart * 12 + LunaStart &lt;= getanlucru() * 12 + getlunalucru())
--            AND coalesce (C1.AnStart * 12 + C1.LunaStart, 0) = (SELECT coalesce (MAX (AnStart * 12 + LunaStart) , 0)
--              FROM NARTOBJ1 WHERE CodObiect = C1.CodObiect AND AnStart * 12 + LunaStart &lt;= getanlucru() * 12 + getlunalucru())
            AND TMP.USERID = ' || coalesce (vUserID::varchar,'');
  PERFORM LIST_EXECUTE_IMMEDIATE (coalesce (sInsert,'')|| coalesce (sSelect0,'') , 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_notacont_setjoinuri</obj_name>
  <obj_hashval>d4a448fdf768e6e1de1f40727c85cadf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacont_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 17 septembrie 2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_NOTACONT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_notacont_setparams</obj_name>
  <obj_hashval>32aac7d668bb2f371d265e9291742ef7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacont_setparams(ptipdoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 17 septembrie 2020
  perform set_config('PKG_LIST_BASE_NOTACONT.vTipDoc',(pTipDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ofeproforma_processlist</obj_name>
  <obj_hashval>83581f2a571b9f5ca9541b6fc8b479f3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ofeproforma_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;
  vCurs           numeric;
  aModulCereale   numeric := 2;
  gSuplCols        VARCHAR :=   'tmp_list_proforma1 p1, oferta o, oferta1 o1, 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 := '';
  vCodDoc          NUMERIC := current_setting('PKG_LIST_BASE_OFEPROFORMA.vCodDoc', true)::numeric;
  wmeRes          boolean;
  vAnLunaLucru    NUMERIC;
  pBancaCursPUV   NUMERIC := CASE WHEN current_setting('PKG_LIST_BASE_OFEPROFORMA.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;
BEGIN
  --Florin 10.04.2024 - fixat 61640
  --Florin 02.03.2023 - fixat 57436
  --Florin 14/16.02.2023 - fixat 57166
  --Adina 16.04.2021 - alstart,alstop
  --Adina 14.10.2020
  vAnLunaLucru := getanlunalucru();
  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_OFEPROFORMA.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');


  IF  current_setting('PKG_LIST_BASE_OFEPROFORMA.pListareLiniiDiscPart', true)::numeric &lt;&gt; 1 THEN
    sCondDiscP := '
    AND NOT p1.tiplinie IN (''G'',''T'')';
  END IF;
  SELECT   COALESCE(o.Moneda, 0), To_Char(o.DataOferta, 'dd.mm.yyyy'),
          CASE
             WHEN  UPPER(SubStr(trim( cf.codfiscal), 1, 2)) = 'RO' AND  fnc_GetValConstantaLucru('ModulCereale') = '1' THEN 1
             ELSE 2
           END
  INTO vMoneda, sDataDoc, aModulCereale
  FROM   oferta o
        LEFT JOIN npartcodfisc cf ON  cf.cod_codfiscal = o.codfiscal
  WHERE o.codoferta = vCodDoc;
  IF  vMoneda = 0 THEN
    sCurs := '1';
  ELSE
    IF sCurs IS NULL OR sCurs = '' THEN
      sCurs := (SELECT PKG_MONEDE_GETCURSMONEDA.WME_RESULT FROM PKG_MONEDE_GETCURSMONEDA(NULL,vMoneda, pBancaCursPUV, sDataDoc))::varchar;  --, 'NLS_NUMERIC_CHARACTERS = ''.,'''
    END IF;
  END IF;
  IF current_setting('PKG_LIST_BASE_OFEPROFORMA.vNrDC', true) IS NOT NULL AND current_setting('PKG_LIST_BASE_OFEPROFORMA.vNrDC', true) &lt;&gt; ''
    AND current_setting('PKG_LIST_BASE_OFEPROFORMA.vNrDC', true)::numeric &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' || coalesce(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
                 ) A_PG
           ) B_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   codoferta1,
            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
            o1.codoferta1, amb.codextern aext, Upper(u1.codextern) uext, u1.paritate upar, amb.greutspecifica gsp,
            Dense_Rank() OVER (PARTITION BY o1.codoferta1, Upper(u1.codextern) ORDER BY CASE WHEN u1.codum1 = o1.umsec THEN 0 ELSE u1.paritate END) idxobj
          FROM   OFERTA1 O1
                INNER JOIN NARTAMB AMB ON AMB.CODOBIECT = O1.CODOBIECT
                INNER JOIN NUM1 U1     ON U1.CODUM1     = AMB.UMSEC
          WHERE O1.CODOFERTA = ' || coalesce(vCodDoc::varchar ,'') || ' AND Upper(U1.codextern) IN (''CUTIE'',''PALET'')
         ) AA_PG
    WHERE idxobj = 1
    GROUP BY codoferta1)
  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,
    p1.pretorig*' || coalesce(sCurs,'') || ', p1.pu*' || coalesce(sCurs,'') || ', p1.pretorig * p1.coefdiscmaj*' || coalesce(sCurs,'') || ',
    p1.valoare*' || coalesce(sCurs,'') || ', (p1.pu - p1.pretorig) * p1.cant*' || coalesce(sCurs,'') || ',
    (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 na.tipserie when 0 then ''fara serie'' when 1 then ''serie pe bucata'' when 2 then ''serie pe lot'' end),
    (case when coalesce(p1.procdisc,0)=0 then '' '' else 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||'' / '' ||o1.d1
      when  2 then um1.den_um||'' = ''||num.den_um||'' / (''||o1.d1||'' x ''||o1.d2||'')''
      when  3 then um1.den_um||'' = ''||num.den_um||'' / (''||o1.d1||'' x ''||o1.d2||'' x ''||o1.d3||'')''
      when  4 then um1.den_um||'' = ''||num.den_um||'' x '' ||o1.d1
      when  5 then um1.den_um||'' = ''||num.den_um||'' x '' ||o1.d1||'' x ''||o1.d2
      when  6 then um1.den_um||'' = ''||num.den_um||'' x '' ||o1.d1||'' x ''||o1.d2||'' x ''||o1.d3
      when  7 then num.den_um||'' = ''||um1.den_um||'' x '' ||o1.d1
      when  8 then num.den_um||'' = ''||um1.den_um||'' x '' ||o1.d1||'' x ''||o1.d2
      when  9 then num.den_um||'' = ''||um1.den_um||'' x '' ||o1.d1||'' x ''||o1.d2||'' x ''||o1.d3
      when 10 then num.den_um||'' = ''||um1.den_um||'' / '' ||o1.d1
      when 11 then num.den_um||'' = ''||um1.den_um||'' / (''||o1.d1||'' x ''||o1.d2||'')''
      when 12 then num.den_um||'' = ''||um1.den_um||'' / (''||o1.d1||'' x ''||o1.d2||'' x ''||o1.d3||'')''
    end),
    o1.d1, o1.d2, o1.d3,
    p1.cant cantumprinc, umcp.cutiepar, umcp.cutieext, umcp.cutiegsp, umcp.paletpar ' || coalesce(sSelectDC,'') || gUserAlias || '
  FROM   tmp_list_proforma1    p1
        LEFT JOIN oferta1     o1    ON o1.codoferta1   = p1.codsursa
        LEFT JOIN oferta      o     ON o.codoferta     = o1.codoferta
        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 nartcli     ac    ON ac.codobiect    = p1.codobiect AND ac.codpart = o.partener
        LEFT JOIN nechiv      e     ON e.codobiect     = p1.codobiect
        LEFT JOIN grechiv     gre   ON gre.codgrechiv  = e.codgrupa
        LEFT JOIN umcp              ON umcp.codoferta1 = p1.codsursa
        LEFT JOIN nagenda     nag   ON nag.codagenda   = o.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 '||vAnLunaLucru::varchar||' BETWEEN nao1.ALStart and nao1.ALStop '
        || coalesce(sJoinDC,'') || gSuplJoins || '
  WHERE 1=1 ' || coalesce(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(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);

  PERFORM pkg_list_Struct_GOLESTE_PARAM();
  WITH
  UMCP AS
  (
    SELECT   codoferta1,
            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  o1.codoferta1, amb.codextern AEXT, Upper(u1.codextern) UEXT, u1.paritate UPAR, amb.greutspecifica GSP,
                  Dense_Rank() OVER (PARTITION BY o1.codoferta1, Upper(u1.codextern) ORDER BY CASE WHEN u1.codum1 = o1.umsec THEN 0 ELSE u1.paritate END) IDXOBJ
          FROM   oferta1 o1
                INNER JOIN NARTAMB AMB ON  AMB.CODOBIECT = o1.CODOBIECT
                INNER JOIN NUM1 U1     ON  U1.CODUM1     = AMB.UMSEC
          WHERE o1.CODoferta = vCodDoc AND Upper(U1.codextern) IN ('CUTIE', 'PALET')
         ) B_PG
    WHERE idxobj = 1
    GROUP BY codoferta1
  )
  SELECT   COALESCE(CEIL(SUM(COALESCE(p1.cant, 0))), 0),
          COALESCE(CEIL(SUM(COALESCE(p1.cant / UMCP.CutiePar, 0))), 0),
          COALESCE(Round((SUM(COALESCE(p1.cant * UMCP.CutieGSp / UMCP.CutiePar, 0)))::numeric), 0),
          COALESCE(CEIL(SUM(COALESCE(p1.cant / UMCP.PaletPar, 0))), 0)
  INTO vCantBuc, vCantCut, vGSpCut, vCantPal
  FROM   oferta1 o1
        LEFT JOIN tmp_list_proforma1 p1 ON  p1.codsursa     = o1.codoferta1
        LEFT JOIN UMCP                  ON  UMCP.codoferta1 = o1.codoferta1
  WHERE o1.codoferta = vCodDoc;

  SELECT   Sum(CASE WHEN tiplinie IN ('G', 'T') THEN 0 ELSE valoare END ),
          Sum(CASE WHEN tiplinie IN ('G', 'T') THEN 0
                   WHEN  aModulCereale = 1 AND Trim( o.codd394) IS NOT NULL  THEN 0
                    ELSE valoare * COALESCE(t.proctva, 0) / 100
               END ),
           Sum(CASE WHEN tiplinie IN ('G', 'T') THEN valoare ELSE valoare * (  1 + COALESCE(t.procdisc / 100, 0)) END )
  INTO vVal, vTva, vValDisc
  FROM  tmp_list_proforma1 t
        LEFT JOIN nartobj o ON  o.codobiect = t.codobiect;
  vTvaDisc := CASE WHEN  vVal = 0 OR  vValDisc = 0 OR  vTva = 0 THEN 0 ELSE vValDisc * vTva / vVal 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;

  FOR v_rec IN
  (
  SELECT   O.TIPDOC, O.NRDOC, O.DATAOFERTA, O.SERIADOC, O.CODLOCATIE, O.NRI, O.AGENT, O.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, O.USERID,
          COALESCE(U.Nume, '...nedefinit...') UNUME, COALESCE(U.Prenume, '...nedefinit...') UPRENUME, COALESCE(U.CNP, '...nedefinit...') UCNP,
          coalesce(U.BISERIA,'') || ' ' || coalesce(U.BINR::varchar ,'') UBI, 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,
          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,
          CASE WHEN  COALESCE(aMonedaV, 0) = 0 OR  COALESCE(aBancaV, 0) = 0 THEN 1
                ELSE PKG_LIST_BASE_UTILS_GETCURSREFERINTA(aMonedaV, aBancaV, to_char(O.dataoferta,'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
  FROM   oferta o
        INNER JOIN NPART        P     ON  P.CODPART          = O.PARTENER
        INNER JOIN NMONEDE      M     ON  M.CODMONEDA        = COALESCE(O.MONEDA, 0)
        LEFT  JOIN NPARTCODFISC CODF  ON  CODF.COD_CODFISCAL = O.CODFISCAL
        LEFT  JOIN NPERS        U     ON  U.LOGONNAME      = O.USERID
        LEFT  JOIN NAGENDA      SLIVR ON  SLIVR.CODAGENDA  = O.CODLOCATIE AND  SLIVR.CODPART = O.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     = O.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       = O.AGENT
        LEFT  JOIN NPERSCONTACT PC     ON  PC.CodPart       = P.CodPart
  WHERE O.codoferta = vCodDoc
  )
  LOOP
    IF  v_rec.codmoneda = 0 THEN
      vCurs := 1;
    ELSIF vCurs IS NULL THEN
      vCurs := COALESCE((SELECT pkg_monede_getcursmoneda.WME_RESULT FROM pkg_monede_getcursmoneda(NULL,v_rec.codmoneda, fnc_GetValConstantaLucru('BancaCursPUV')::numeric, To_Char(v_rec.DataOferta, 'dd.mm.yyyy'))), 1);
    END IF;

    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('DOCUMENT NUMAR',                   v_rec.NrDoc::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT DATA',                   To_Char(v_rec.DataOferta, 'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR INREGISTRARE',     v_rec.NrI);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL',                           TO_CHAR(vVal, 'fm9G999G999G990D00'));
    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(vValDisc + vTvaDisc, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC CU TVA LITERE',     NumarRO(Round((vValDisc + 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 + 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(vVal * vCurs, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL IN LEI SI LITERE',       NumarRO(Round((vVal * vCurs)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL VAL IN LEI SI LITERE ENG',   NumarUK(Round((vVal * vCurs)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU TVA IN LEI',             TO_CHAR((vVal + vTva)  * vCurs, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU TVA IN LEI LITERE',       NumarRO(Round(((vVal + vTva)  * vCurs)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU TVA IN LEI LITERE ENG',   NumarUK(Round(((vVal + vTva)  * vCurs)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA IN LEI',                 TO_CHAR(vTVA * vCurs, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA IN LEI SI LITERE',       NumarRO(Round((vTVA * vCurs)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL TVA IN LEI SI LITERE ENG',   NumarUK(Round((vTVA * vCurs)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC VAL LEI',           TO_CHAR(vValDisc * vCurs, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC VAL LEI LITERE',     NumarRO(Round((vValDisc * vCurs)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC VAL LEI ENG',       NumarUK(Round((vValDisc * vCurs)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC CU TVA LEI',         TO_CHAR((vValDisc + vTvaDisc)  * vCurs, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC CU TVA LEI LITERE', NumarRO(Round(((vValDisc + vTvaDisc)  * vCurs)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC CU TVA LEI ENG',     NumarUK(Round(((vValDisc + vTvaDisc)  * vCurs)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC TVA LEI',           TO_CHAR(vTVADisc * vCurs, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC TVA LEI LITERE',     NumarRO(Round((vTVADisc * vCurs)::numeric, 2), v_rec.Den_Moneda, '', v_rec.SDenumire, ''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL CU DISC TVA LEI ENG',       NumarUK(Round((vTVADisc * vCurs)::numeric, 2), v_rec.SIMBMONEDA, v_rec.SSIMBMONEDA));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL FACT.VALUTA IN LEI',         TO_CHAR(vVal * vCurs, '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 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     );
    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 LOCALITATE',       v_rec.SFactLocalit  );
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE TELEFON',         v_rec.SFactTelefon  );
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU FACTURARE EMAIL',           v_rec.SFactEmail    );
    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 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_GetValConstantaLucru('GetSoldListFact') = '1' THEN
      PERFORM pkg_list_Struct_ADAUGA_PARAM('CLIENT SOLD',                   TO_CHAR(PKG_LIST_BASE_UTILS_GetSoldPart(v_rec.CodPart, v_rec.CodLocatie), 'fm9G999G999G990D00'));
    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('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, 'fm9G999G999G990'));
    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(p1.pu * p1.cant) VALBRUTA,
            SUM(CASE WHEN  p1.cant &gt; 0 THEN p1.cant * COALESCE(o.volum, 0) ELSE 0 END ) VOLUM,
            SUM(CASE WHEN  p1.cant &gt; 0 THEN p1.cant * COALESCE(o.masa, 0)  ELSE 0 END ) MASA,
            SUM(CASE WHEN  p1.cant &gt; 0 THEN p1.cant * COALESCE(o.masa, 0) * COALESCE(u.coef, 1) ELSE 0 END ) MASAM,
            SUM(Ceil(p1.cant) * (SELECT count(1) FROM nartobjcolet oc WHERE oc.codobiect = p1.codobiect )) NRCOL
    FROM   tmp_list_proforma1 p1
          INNER JOIN nartobj o ON  o.codobiect  = p1.codobiect
          INNER JOIN nart    a ON  a.codarticol = o.codarticol
          INNER JOIN num     u ON  u.codum      = a.um
  )
  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   PA.NRINREG,
            (SELECT Max(COALESCE(PA0.KMBORD, 0)) FROM NPARC0 PA0 WHERE PA0.CODNPARCAUT = O.CODNPARCAUT) KMBORD,
            PA.SERIEC, MA.MARCA, MO.MODEL, CA.NRDOC, CA.DATADOC, CA.SERIADOC,
            O.DATAOFERTA + (SELECT Max(COALESCE(O1.ZileL, 0)) FROM OFERTA1 O1 WHERE O1.CODOFERTA = O.CODOFERTA)::integer TERMEN
    FROM   OFERTA O
          LEFT JOIN NPARCAUT    PA  ON  PA.CODNPARCAUT   = O.CODNPARCAUT
          LEFT JOIN NPARCCOM    PCA ON  PCA.CODNPARCAUT  = O.CODNPARCAUT
          LEFT JOIN COMANDA     CA  ON  CA.CODCOMANDA    = PCA.CODCOMANDA AND  CA.DATADOC &lt; O.DATAOFERTA
          LEFT JOIN NMARCIAUTO  MA  ON  MA.CODMARCIAUTO  = PA.MARCA
          LEFT JOIN NMODELEAUTO MO  ON  MO.CODMODELEAUTO = PA.MODEL
    WHERE o.codoferta = vCodDoc AND  COALESCE(O.CODNPARCAUT, 0) &gt; 0
    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'));
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ofertadoc_processlist</obj_name>
  <obj_hashval>d985b35e9bdd09b3edfc2366b14150db</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ofertadoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  sInsert         varchar := '';
  vDataOfe        date := CURRENT_TIMESTAMP;
  vMoneda         numeric := 0;
  vVal            numeric;
  vVCT            numeric;
  sInsAchiz       varchar := '';
  sSelAchiz       varchar := '';
  vAnLuna         numeric;
  gSuplCols       VARCHAR := 'OFERTA1 O1, OFERTA O, NPART PART, NARTOBJ OBJ, NARTCLI ARTCLI, NART NA, NUM1 UM, NUM UM1, NPART PROD, NCLASEA CA, NECHIV E, GRECHIV GRE';
   gUserFields    VARCHAR := '';
  gUserAlias      VARCHAR := '';
  gNullAlias      VARCHAR := '';
  gSuplJoins      VARCHAR := '';
  vCodOferta      NUMERIC := current_setting('PKG_LIST_BASE_OFERTADOC.vCodOferta', true)::NUMERIC;
BEGIN
  --Florin 10.04.2024 - fixat 61640
  --Florin 29.06.2022 - fnc_getprocenttvaart
  --Adina 05.05.2021 - alstart,alstop
  --Adina 30 septembrie 2020
  --Florin 25.01.2021 - fixat 42536
  CALL PRC_AL_CHECK('npers1',0);

  PERFORM pkg_globals_SetSeparator(';');
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'    , 'PD'    , 'PD.CODPART        = PART.CODPART' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT'  , 'OEXT'  , 'O1.CODOBIECT      = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR'  , 'OATR'  , 'O1.CODOBIECT      = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'OFERTAEXT'   , 'OFEXT' , 'OFEXT.CODOFERTA   = O1.CODOFERTA' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'OFERTA1EXT'  , 'OF1EXT', 'OF1EXT.CODOFERTA1 = O1.CODOFERTA1',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'TMP_LST_CURS', 'CURS'  , 'CURS.CODMONEDA    = O.MONEDA'     ,NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_OFERTADOC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF  InStr(gSuplJoins, 'TMP_LST_CURS') &gt; 0 THEN
    BEGIN
      SELECT DATAOFERTA, MONEDA INTO vDataOfe, vMoneda FROM OFERTA WHERE CodOferta = vCodOferta;
    EXCEPTION WHEN OTHERS THEN
      NULL;
    END;
    PERFORM PKG_LIST_BASE_UTILS_UMPLE_TMP_LST_CURS(NULL, vDataOfe, vMoneda);
  END IF;

  sInsAchiz := '';
  sSelAchiz := '';

  IF  aLISTID = 128 THEN
    sInsAchiz := ',PretAchiz,ValAchiz,Marja,ValMarja';
    sSelAchiz := ',O1.PretAchiz,O1.PretAchiz*O1.CantMin,case when Coalesce(O1.PretAchiz,0) &gt; 0 then (O1.Pret - O1.PretAchiz)/O1.Pret*100 else 0 end, case when Coalesce(O1.PretAchiz,0) &gt; 0 then O1.Pret - O1.PretAchiz else 0 end';
  END IF;

  BEGIN
    SELECT AN * 12 + LUNA INTO VANLUNA FROM OFERTA WHERE CODOFERTA = vCodOferta;
  EXCEPTION WHEN OTHERS THEN
    VANLUNA := 0;
  END;

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    ART, UM, CANTMIN, PRET, ADAOS, DISC, OBS, ZileC, ZileL,
    DenLaCli, CodLaCli,
    CodListat,
    UM1, CANT1, D1, D2, D3,
    InCoTerms' || coalesce(sInsAchiz,'') || gUserFields || ')
  SELECT
    OBJ.Denumire, UM.Den_UM1, O1.CantMin/UM.Paritate, O1.Pret*UM.Paritate*(100+Coalesce(O1.ProcAdaos,0))/100, O1.ProcAdaos, O1.ProcDiscount, O1.Obs, O1.ZileC, O1.ZileL,
    (CASE WHEN artcli.denumire IS NULL OR artcli.denumire = '''' THEN obj.denumire ELSE artcli.denumire END),
    (CASE WHEN artcli.codextern IS NULL OR artcli.codextern = '''' THEN obj.codextern ELSE artcli.codextern END),
    CASE WHEN (case artcli.tipcodafisat when 1 then gre.cod when 2 then artcli.codextern when 3 then obj.codextern when 4 then obj.codintern when 5 then obj.codvamal when 6 then obj.codplu::varchar when 7 then o1.codextofe end) IS NULL OR
    (case artcli.tipcodafisat when 1 then gre.cod when 2 then artcli.codextern when 3 then obj.codextern when 4 then obj.codintern when 5 then obj.codvamal when 6 then obj.codplu::varchar when 7 then o1.codextofe end) = '''' THEN obj.codextern
    ELSE (case artcli.tipcodafisat when 1 then gre.cod when 2 then artcli.codextern when 3 then obj.codextern when 4 then obj.codintern when 5 then obj.codvamal when 6 then obj.codplu::varchar when 7 then o1.codextofe end) END,
    um1.den_um, o1.CantMinUM1, o1.d1, o1.d2, o1.d3,
    CASE o.tiplivrare
      WHEN  0 THEN ''...''
      WHEN  1 THEN ''EXW - Ex Works''
      WHEN  2 THEN ''FCA - Free Carrier''
      WHEN  3 THEN ''CPT - Carriage Paid To''
      WHEN  4 THEN ''CIP - Carriage and Insurance Paid to''
      WHEN  5 THEN ''DAT - Delivered at Terminal''
      WHEN  6 THEN ''DAP - Delivered at Place''
      WHEN  7 THEN ''DDP - Delivered Duty Paid''
      WHEN  8 THEN ''FAS - Free alongside ship''
      WHEN  9 THEN ''FOB - Free on Board''
      WHEN 10 THEN ''CFR - Cost and Freight''
      WHEN 11 THEN ''CIF - Cost, Insurance and Freight''
    END InCoTerms' || coalesce(sSelAchiz,'') || gUserAlias || '
  FROM OFERTA1 O1
    INNER JOIN OFERTA  O      ON O1.CodOferta     = O.CodOferta
    LEFT  JOIN NPART   PART   ON PART.CodPart     = O.Partener
    LEFT  JOIN NARTOBJ OBJ    ON OBJ.CodObiect    = O1.CodObiect
    LEFT  JOIN NArtCli ACP    ON ACP.CodObiect    = O1.CodObiect AND ACP.CodPart = O.Partener AND Coalesce(ACP.CodPart,0) &lt;&gt; 0
    LEFT  JOIN NArtCli ARTCLI ON ARTCLI.CodObiect = O1.CodObiect AND ARTCLI.CodArtCli = Coalesce(ACP.CodArtCli, ARTCLI.CodArtCli)
                                 AND Coalesce(ACP.CodArtCli,PART.CodClasa,O.CodClaseP, 0) = COALESCE(ACP.CodArtCli, (case when ARTCLI.CodClaseP is NULL then -1 when ARTCLI.CodClaseP= 0 then -1 else ARTCLI.CodClaseP end))
    LEFT  JOIN NART    NA     ON NA.CodArticol    = OBJ.CodArticol
    LEFT  JOIN NUM1    UM     ON UM.CodUM1        = O1.UMSec
    LEFT  JOIN NUM     UM1    ON UM1.CODUM        = NA.UM1
    LEFT  JOIN NPART   PROD   ON PROD.CodPart     = OBJ.CodProducator
    LEFT  JOIN NCLASEA CA     ON CA.CodClaseA     = NA.Clasa
    LEFT  JOIN NECHIV  E      ON e.codobiect      = o1.codobiect
    LEFT  JOIN GRECHIV GRE    ON gre.codgrechiv   = e.codgrupa' || gSuplJoins || '
  WHERE O.CodOferta = ' || coalesce(vCodOferta::varchar ,'') || '
  ORDER BY O1.CODOFERTA1';

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  SELECT SUM(O1.CANTMIN * O1.PRET * (  1 + Coalesce(O1.PROCADAOS / 100, 0))  * (  1 + Coalesce(O1.PROCDISCOUNT / 100, 0)) ) VAL, SUM(O1.CANTMIN * O1.PRET * (  1 + Coalesce(O1.PROCADAOS / 100, 0))  * (  1 + Coalesce(O1.PROCDISCOUNT / 100, 0))  * (  1 +
  fnc_getprocenttvaart(NO.CodArticol, O.AN, O.LUNA) / 100) ) VALCUTVA
  INTO vVal, vVCT
  FROM OFERTA O
      INNER JOIN OFERTA1 O1 ON  O1.CODOFERTA = O.CODOFERTA
      INNER JOIN NARTOBJ NO ON  NO.CODOBIECT = O1.CODOBIECT
  WHERE O.CodOferta = vCodOferta;

  FOR v_rec IN (WITH FUNCT AS (
                               SELECT P1.CODPERS, F.DENUMIRE FUNCTIE
                               FROM NPERS1 P1 LEFT JOIN FUNCTII F ON  P1.CODFUNCTIE = F.CODFUNCTIE
                               WHERE VANLUNA BETWEEN P1.ALStart AND P1.ALStop
                              )
                SELECT  O.TipDoc, O.NrDoc, O.DataCerere, O.DataOferta, O.DataStart, O.DataEnd, O.Obs, O.Agent, O.CodPersC, 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, AGU.EMAIL, AGU.Telefon UTELEFON1, AGU.TelefonP UTELEFON2,
                        coalesce(AG.NUME,'') || ' ' || coalesce(AG.PRENUME,'') ANUME, AG.CNP ACNP,
                        coalesce(AG.BISERIA,'') || ' ' || coalesce(AG.BINR::varchar ,'') ABI, PCF.CodFiscal AS CIF, P.CodPart, P.Den_Part, P.Autorizatie,
                        P.RegCom, P.Obs PARTOBS, M.Simbol,
                        fnc_GetAdresa(SS.sector, SS.strada, SS.nr1, SS.nr2, SS.bloc, SS.scara, SS.etaj, SS.apart, SS.codpostal) ADRESAS,
                        fnc_GetAdresa(SS.sector, SS.strada, SS.nr1, SS.nr2, SS.bloc, SS.scara, SS.etaj, SS.apart, NULL) ADRESAS_NO_CP,
                        SS.OBS OBSS, LS.Den_Localit LOCALITS, SS.TELEFON TELEFONS, SS.FAX FAXS, JS.DEN_JUDET JUDETS, JS.SimbAuto SIMBAUTOS,
                        TS.Den_Tara TARAS, SS.CODPOSTAL CODPOSTALS, SS.CODFISCAL CODFISCALS, SS.CODCLIENT CODCLIENTS,
                        fnc_GetAdresa(SL.sector, SL.strada, SL.nr1, SL.nr2, SL.bloc, SL.scara, SL.etaj, SL.apart, SL.codpostal) ADRESAL,
                        fnc_GetAdresa(SL.sector, SL.strada, SL.nr1, SL.nr2, SL.bloc, SL.scara, SL.etaj, SL.apart, NULL) ADRESAL_NO_CP,
                        SL.OBS OBSL, LL.Den_Localit LOCALITL, SL.TELEFON TELEFONL, SL.FAX FAXL, JL.DEN_JUDET JUDETL, JL.SimbAuto SIMBAUTOL,
                        TL.Den_Tara TARAL, SL.CODPOSTAL CODPOSTALL, SL.CODFISCAL CODFISCALL, SL.CODCLIENT CODCLIENTL,
                        coalesce(PC.Nume,'') || ' ' || coalesce(PC.Prenume,'') PERSCONTACT, PC.TELEFON PERSCONTACTTEL, PC.EMAIL PERSCONTACTEMAIL,
                        CASE O.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 O.tiplivrare
                           WHEN 0 THEN '...'
                           WHEN 1 THEN 'Ex Works'
                           WHEN 2 THEN 'Free Carrier'
                           WHEN 3 THEN 'Carriage Paid To'
                           WHEN 4 THEN 'Carriage and Insurance Paid to'
                           WHEN 5 THEN 'Delivered at Terminal'
                           WHEN 6 THEN 'Delivered at Place'
                           WHEN 7 THEN 'Delivered Duty Paid'
                           WHEN 8 THEN 'Free alongside ship'
                           WHEN 9 THEN 'Free on Board'
                           WHEN 10 THEN 'Cost and Freight'
                           WHEN 11 THEN 'Cost, Insurance and Freight'
                         END  INCOTERMSDESC,
                         AGA.TELEFON, AGA.TELEFONP, AGF.FUNCTIE AGFUNCTIE, UF.FUNCTIE UFUNCTIE
                FROM  OFERTA O
                      LEFT JOIN NPERS U           ON  U.LOGONNAME   = O.USERID
                      LEFT JOIN TMP_UTILIZATOR UT ON  UT.CODUTILIZATOR = O.USERID
                      LEFT JOIN NMONEDE M         ON  O.Moneda      = M.CodMoneda
                      LEFT JOIN NPARTCODFISC PCF  ON  O.CodFiscal   = PCF.Cod_CodFiscal
                      LEFT JOIN NPART P           ON  O.Partener    = P.CodPart
                      LEFT JOIN NAGENDA SL        ON  SL.CodAgenda  = O.CodLocatie
                      LEFT JOIN NLOCALIT LL       ON  LL.CodLocalit = SL.CodLocalit
                      LEFT JOIN NJUDET JL         ON  JL.CodJudet   = LL.CodJudet
                      LEFT JOIN NTARI TL          ON  TL.CodTara    = Coalesce(LL.CodTara, 0)
                      LEFT JOIN NAGENDA SS        ON  SS.CodPart    = O.Partener AND SS.SEDIUSOCIAL IN (4, 5, 6, 7) AND  Coalesce(SS.INACTIV, 0) = 0
                      LEFT JOIN NLOCALIT LS       ON  LS.CodLocalit = SS.CodLocalit
                      LEFT JOIN NJUDET JS         ON  JS.CodJudet   = LS.CodJudet
                      LEFT JOIN NTARI TS          ON  TS.CodTara    = Coalesce(LS.CodTara, 0)
                      LEFT JOIN NPERS AG          ON  AG.CODPERS    = O.AGENT
                      LEFT JOIN NAGENDA AGA       ON  AGA.CODAGENDA = AG.AGENDA
                      LEFT JOIN NAGENDA AGU       ON  AGU.CODAGENDA = U.AGENDA
                      LEFT JOIN NPERSCONTACT PCx  ON  PCx.CodPart   = P.CodPart
                      LEFT JOIN NPERSCONTACT PC   ON  PC.CodPersC   = CASE WHEN  O.CodPersC IS NULL THEN PCx.CodPersC WHEN  O.CodPersC=0 THEN PCx.CodPersC ELSE  O.CodPersC END
                      LEFT JOIN FUNCT AGF         ON  AGF.CODPERS   = O.AGENT
                      LEFT JOIN FUNCT UF          ON  UF.CODPERS    = U.CODPERS
                WHERE O.CodOferta = vCodOferta 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 MAIL',                 v_rec.EMAIL);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT TELEFON 1',            v_rec.utelefon1);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT TELEFON 2',            v_rec.utelefon2);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('INTOCMIT FUNCTIE',              v_rec.UFUNCTIE);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Numar oferta',                  v_rec.NrDoc::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Perioada de valabilitate',      coalesce(To_Char(v_rec.DataStart, 'dd.mm.yyyy'),'') || ' - ' || coalesce(To_Char(v_rec.DataEnd,'dd.mm.yyyy'),''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Data cerere oferta',            To_Char(v_rec.DataCerere, 'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Data oferta',                   To_Char(v_rec.DataOferta, 'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Data inceput oferta',           To_Char(v_rec.DataStart , 'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Data sfarsit oferta',           To_Char(v_rec.DataEnd   , '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('Partener observatii',           v_rec.PartObs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Moneda',                        v_rec.Simbol);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL DENUMIRE',         v_rec.ObsS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL ADRESA',           v_rec.AdresaS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL ADRESA FARA CP',   v_rec.AdresaS_NO_CP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL LOCALITATE',       v_rec.LocalitS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL TELEFON',          v_rec.TelefonS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL FAX',              v_rec.FaxS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL JUDET',            v_rec.SimbAutoS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL DENUMIRE JUDET',   v_rec.JudetS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL TARA',             v_rec.TaraS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL COD POSTAL',       v_rec.CodPostalS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL COD FISCAL',       v_rec.CodFiscalS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU SOCIAL COD LA CLIENT',    v_rec.CodClientS);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE DENUMIRE',        v_rec.ObsL);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE ADRESA',          v_rec.AdresaL);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE ADRESA FARA CP',  v_rec.AdresaL_NO_CP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE LOCALITATE',      v_rec.LocalitL);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE TELEFON',         v_rec.TelefonL);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE FAX',             v_rec.FaxL);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE JUDET',           v_rec.SimbAutoL);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE TARA',            v_rec.TaraL);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE DENUMIRE JUDET',  v_rec.JudetL);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE COD POSTAL',      v_rec.CodPostalL);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE COD FISCAL',      v_rec.CodFiscalL);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('SEDIU LIVRARE COD LA CLIENT',   v_rec.CodClientL);
    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('AGENT TELEFON 1',               v_rec.TELEFON);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('AGENT TELEFON 2',               v_rec.TELEFONP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('AGENT FUNCTIE',                 v_rec.AGFUNCTIE);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE',                       TO_CHAR(vVal, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE CU TVA',                TO_CHAR(vVCT, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PERSOANA DE CONTACT',           v_rec.PersContact);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PERSOANA DE CONTACT TELEFON',   v_rec.PersContactTel);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('PERSOANA DE CONTACT EMAIL',     v_rec.PersContactEmail);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('InCoTerms',                     v_rec.InCoTerms);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('InCoTermsDesc',                 v_rec.InCoTermsDesc);
    EXIT ;
  END LOOP;

  PERFORM pkg_list_Struct_ADAUGA_PARAM_EXT('OFERTAEXT', 'CODOFERTA', vCodOferta);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_ofertadoc_setparams</obj_name>
  <obj_hashval>239a1aa74990396342e1c2e9d265b6a8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ofertadoc_setparams(pcodoferta numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 30 septembrie 2020
  perform set_config('PKG_LIST_BASE_OFERTADOC.vCodOferta',(pCodOferta)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_parcautoanv_processlist</obj_name>
  <obj_hashval>5db1403b3d020abbd90516eb5281cdd5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_parcautoanv_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  gSuplCols   varchar := 'nparcaut pa, nparc1 p1, nartobj anv, nart nart, num um, npers s, mifix mf, nirstoc ns, ngest g, nartobj o ';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 16.09.2020
  --Florin 14.05.2021 - fixat 41824
  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_PARCAUTOANV.gSuplCols', gSuplCols, FALSE);

  sInsert := 'INSERT INTO ' || tmpName || '(
      NAV_CodDoc, NAV_TipDoc,
      Den, NrInv, Sofer, Gest, Tip,
      NrInreg, DataInreg, Marca, Model, AnFab, SerieC, Culoare, Lung, Lat, Inalt,
      TipMotor, SerieMotor, Combustibil, Cilindree, Putere, Rezervor, CMM, CMU, CME,
      TipIncarc, Greutate, MasaMax, MasaUtil, MasaURDF, MasaURFDF,
      VolumUtil, LocTot, LocFata, LocSpate, LocPic,
      AnvRecF, AnvRecS, AnvOp1F, AnvOp1S, AnvOp2F, AnvOp2S,
      Anvelopa, UM, Cant, Poz, BordInstal, Atentie,
      Montat,Anotimp,Hotel' || gUserFields || ')
    WITH mf1 AS (SELECT codmifix, Max(codnirstoc) codnirstoc FROM mifix1 GROUP BY codmifix)
    SELECT
      pa.codnparcaut, 505,
      o.denumire, pa.nrinv, (s.nume||'' ''||s.prenume) sofer, g.den_gest, (CASE WHEN pa.tip = 0 THEN ''TRACTAT'' ELSE ''MOTORIZAT'' END) tip,
      pa.nrinreg, pa.datainreg, ma.marca, mo.model, pa.anf, pa.seriec, pa.culoarec, pa.lung, pa.lat, pa.inalt,
      pa.tipmotor, pa.seriem, pa.sursae, pa.cilindree, pa.putere, pa.rezervor, pa.cmm, pa.cmu, pa.cme,
      (CASE WHEN tipincarc = 1 THEN ''Marfa'' WHEN tipincarc = 2 THEN ''Persoane'' WHEN tipincarc = 3 THEN ''Mixta'' END) tipincarc, pa.greutate, pa.masam, pa.masau, pa.masaurdf, pa.masaurfdf,
      pa.volumu, pa.loct, pa.locf, pa.locs, pa.locp,
      pa.anvrecomf, pa.anvrecoms, pa.anvopt1f, pa.anvopt1s, pa.anvopt2f, pa.anvopt2s,
      anv.denumire, um.den_um, p1.cant, p1.pozitie, p1.bordinstal, p1.atentie,
      p1.Montat, p1.Anotimp, HT.DEN_PART' || gUserAlias || '
    FROM nparcaut pa
      INNER JOIN nparc1      p1   ON p1.cod           = pa.codnparcaut
      LEFT  JOIN nartobj     anv  on anv.codobiect    = p1.art
      LEFT  JOIN nart        nart on nart.codarticol  = anv.codarticol
      LEFT  JOIN num         um   on um.codum         = nart.um
      LEFT  JOIN npers       s    on s.codpers        = pa.sofer
      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
      LEFT  JOIN NPART       HT   ON HT.CODPART       = P1.CODPART' || gSuplJoins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_parcautocarb_processlist</obj_name>
  <obj_hashval>7ced1203ff54e61bf9fc110c317d0599</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_parcautocarb_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  VREC RECORD;
  sInsert     varchar := '';
  sSelect     varchar := '';
  sInsDC      varchar := '';
  sSelDC      varchar := '';
  sColDc      varchar := '';
  sKMZi       varchar := '';
  pStocComb   varchar := '';
  pServComb   varchar := '';
  gSuplCols   varchar := 'nparcaut pa, npers s, nartobj o, nart a, nclasea ca';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 26.01.2022 - fixat 52780
  --Adina 06.01.2021 tichet 41989 - add  := '' la param.varchar din Declare
  --Adina 22.12.2020 tichet 41800 (care necesita modif.si in exe - Florin) - add liniile 53..55 + 2 aliasuri
  --Florin 16.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_PARCAUTOCARB.gSuplCols', gSuplCols, FALSE);

  PERFORM pkg_globals_SetSeparator(',');
  pStocComb := COALESCE(fnc_getvalconstantalucru('ArtStocCombustibil'), '0');
  pServComb := COALESCE(fnc_getvalconstantalucru('ArtServCombustibil'), '0');

  IF current_setting('PKG_LIST_BASE_PARCAUTOCARB.vDistZile', true)::BOOLEAN OR current_setting('PKG_LIST_BASE_PARCAUTOCARB.vConsZile', true)::BOOLEAN THEN
    FOR i IN 1..31 LOOP
      sKMZi := sKMZi||',SUM((case when zi= '||i||' then km else 0 end)) Z'||i;
    END LOOP;
  END IF;

  FOR vRec IN (SELECT FIELDNAME, COD FROM tmp_dinamic_cols WHERE COD2 = 1 ORDER BY COD)
  LOOP
    sInsDC := coalesce(sInsDC,'') || ', ' || coalesce(vRec.FIELDNAME,'');
    sSelDC := coalesce(sSelDC,'') || ', COALESCE(kml.z' || coalesce(vRec.COD::varchar ,'') || ',0)';
  END LOOP;

  FOR vRec IN (SELECT FIELDNAME, COD FROM tmp_dinamic_cols WHERE COD2 = 2 ORDER BY COD)
  LOOP
    sInsDC := coalesce(sInsDC,'') || ', ' || coalesce(vRec.FIELDNAME,'');
    sSelDC := coalesce(sSelDC,'') || ', COALESCE(pa.cmm*kml.z' || coalesce(vRec.COD::varchar ,'') || ',0)';
  END LOOP;

  sInsert := 'INSERT INTO ' || tmpName || '(
        NRAUTO, SOFER, ART, CLASA, AN, LUNA, KMLUNA, COMBCANT, COMBVAL,
        CONSUMMEDIU,
        PRETMEDIU,
        TOTALROLKM ' || coalesce(sInsDC,'') || gUserFields || ')';

  sSelect := '
      WITH
      AG AS (
        SELECT codauto, an, luna, sum(combcant) combcant, sum(combval) combval' || coalesce(sColDC,'') || '
        FROM (
              SELECT
                CASE WHEN COALESCE(i1.codauto,0) = 0 THEN i.codauto ELSE i1.codauto END codauto, i.an, i.luna,
                i1.cant combcant, (i1.pu * i1.cant - CASE WHEN i.tipdoc IN (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) combval
              FROM intrari i
                INNER JOIN intrari1 i1 ON i1.codintr = i.codintr
              WHERE (COALESCE(i1.codauto,0) &lt;&gt; 0 OR COALESCE(i.codauto,0) &lt;&gt; 0)
                AND i.an*12+i.luna BETWEEN ' || coalesce(current_setting('PKG_LIST_BASE_PARCAUTOCARB.vAnLunaIni', true)::numeric,0) || ' AND ' || coalesce(current_setting('PKG_LIST_BASE_PARCAUTOCARB.vAnLunaFin', true)::numeric,0) || '
                AND I.ANULAT = 0 AND I.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
                AND i1.codobiect IN (' || coalesce(pServComb,'') || ')
              UNION ALL
              SELECT
                i.codauto, i.an, i.luna,
                i1.cant combcant, (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) combval
              FROM iesiri i
                INNER JOIN iesiri1 i1 ON i1.codies = i.codies
              WHERE COALESCE(i.codauto,0) &lt;&gt; 0
                AND i.an*12+i.luna BETWEEN ' || coalesce(current_setting('PKG_LIST_BASE_PARCAUTOCARB.vAnLunaIni', true)::numeric,0) || ' AND ' || coalesce(current_setting('PKG_LIST_BASE_PARCAUTOCARB.vAnLunaFin', true)::numeric,0) || '
                AND I.ANULAT = 0 AND I.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
                AND i1.tiplinie = ''=''
                AND i1.codobiect IN (' || coalesce(pStocComb,'') || ')
             ) A_PG
        GROUP BY codauto, an, luna
      ),
      KMLUN AS (
        SELECT codnparcaut, an, luna, Sum(km) kmluna ' || coalesce(sKMZi,'') || '
        FROM (
              SELECT
                p.codnparcaut, p0.luna, p0.an, EXTRACT (DAY FROM p0.databord) zi,
                p0.kmbord - COALESCE(Lag(p0.kmbord) OVER (PARTITION BY p.codnparcaut ORDER BY p0.databord),p.kmpornire,0) km
              FROM nparc0 p0 INNER JOIN nparcaut p ON p.codnparcaut = p0.codnparcaut
             ) B_PG
        WHERE an*12+luna BETWEEN ' || coalesce(current_setting('PKG_LIST_BASE_PARCAUTOCARB.vAnLunaIni', true)::numeric,0) || ' AND ' || coalesce(current_setting('PKG_LIST_BASE_PARCAUTOCARB.vAnLunaFin', true)::numeric,0) || '
        GROUP BY codnparcaut, an, luna
      )
      SELECT
        PA.NRINREG, S.NUME||'' ''||S.PRENUME, O.DENUMIRE, CA.DEN_CLASEA, AG.AN, AG.LUNA, KML.KMLUNA, AG.COMBCANT, AG.COMBVAL,
        CASE WHEN COALESCE(KML.KMLUNA,0) =0 THEN 0 ELSE (AG.COMBCANT/KML.KMLUNA)*100 END CONSUMMEDIU,
        CASE WHEN COALESCE(AG.COMBCANT,0)=0 THEN 0 ELSE (AG.COMBVAL/AG.COMBCANT)*100 END PRETMEDIU,
        CASE WHEN COALESCE(KML.KMLUNA,0) =0 THEN 0 ELSE (AG.COMBVAL/KML.KMLUNA) *100 END TOTALROLKM ' || coalesce(sSelDC,'') || gUserAlias || '
      FROM AG
        INNER JOIN nparcaut pa  ON pa.codnparcaut  = ag.codauto
        LEFT  JOIN npers    s   ON s.codpers       = COALESCE(pa.sofer,0)
        LEFT  JOIN nartobj  o   ON o.codobiect     = pa.codart
        LEFT  JOIN nart     a   ON a.codarticol    = o.codarticol
        LEFT  JOIN nclasea  ca  ON ca.codclasea    = COALESCE(a.clasa,0)
        LEFT  JOIN kmlun    kml ON kml.codnparcaut = ag.codauto AND kml.an = ag.an AND kml.luna = ag.luna' || 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_pf_setparams</obj_name>
  <obj_hashval>77791b6384e732860d71e10f8ad96bcf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pf_setparams(pcodprogramf numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 11.01.2020
perform set_config('PKG_LIST_BASE_PF.vCodProgramF', pCodProgramF::varchar,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_prodetichete_setparams</obj_name>
  <obj_hashval>704702180df3ccaa75ab030312317248</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_prodetichete_setparams(acoduri character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.10.2020
  perform set_config('PKG_LIST_BASE_PRODETICHETE.vCoduri',(aCoduri)::varchar,false);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_promodoc_add_list_params</obj_name>
  <obj_hashval>deafcd3522b1b6cafb8b652d353499b4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_promodoc_add_list_params()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC     RECORD;
  vCodPromo  NUMERIC := current_setting('PKG_LIST_BASE_PROMODOC.vCodPromo', true)::NUMERIC;
BEGIN
  --Adina 01 octombrie 2020
  FOR v_rec IN (SELECT   D.NrDoc, D.DataStart, D.DataEnd, D.CodLocatie, D.Obs, D.TipClaseP, M.Simbol,
                        CASE D.DeMana
                           WHEN 0 THEN 'Articole individuale'
                           WHEN 1 THEN 'Pachet PROMO'
                           WHEN 2 THEN 'Optional PROMO'
                           WHEN 3 THEN 'Clase de articole'
                           WHEN 4 THEN 'Toate articolele'
                         END  TIP,
                         CASE WHEN  D.ExclAltePromo = 1 THEN 'Da' ELSE 'Nu' END  EXCLALTEPROMO,
                         CASE D.TipConditie
                           WHEN 0 THEN 'neconditionat'
                           WHEN 1 THEN 'cantitate minima de livrare'
                           WHEN 2 THEN 'zile credit'
                           WHEN 3 THEN 'valoare minima de livrare'
                         END  IN_FUNCTIE_DE,
                         CASE D.TipPromotie
                           WHEN 1 THEN 'marime pret'
                           WHEN 2 THEN '% discount'
                           WHEN 3 THEN 'articole promotionale (cadou)'
                           WHEN 4 THEN 'valoare discount'
                         END  INFLUENTEAZA,
                         CASE WHEN  D.Praguri = 1 THEN 'Da' ELSE 'Nu' END  PRAGURI,
                         CASE D.TipServire
                           WHEN 0 THEN 'orice sediu'
                           WHEN 1 THEN 'cu servire indirecta'
                           WHEN 2 THEN 'cu servire directa'
                         END  TIP_SEDIU_CLIENT,
                         CASE WHEN  D.TipClaseP = 1 THEN 'Da' ELSE 'Nu' END  PECLASEPART,
                         Coalesce(PP.Den_Part, P.Den_Part) AS DEN_PART,
                         PP.Den_ClaseP AS DEN_CLASEP,
                         Coalesce(PP.CIF, PCF.CodFiscal) AS CIF,
                         Coalesce(PP.Autorizatie, P.Autorizatie) AS AUTORIZATIE,
                         Coalesce(PP.RegCom, P.RegCom) AS REGCOM,
                         Coalesce(PP.Den_Localit, L.Den_Localit) AS DEN_LOCALIT,
                         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   Promo D
                      LEFT JOIN NMONEDE M         ON  D.Moneda         = M.CodMoneda
                      LEFT JOIN NPARTCODFISC PCF   ON  D.CodFiscal      = PCF.Cod_CodFiscal
                      LEFT JOIN NPART P           ON  D.Partener       = P.CodPart
                      LEFT JOIN NAGENDA AG         ON  D.CodLocatie     = AG.CodAgenda
                      LEFT JOIN NLOCALIT L         ON  AG.CodLocalit    = L.CodLocalit
                      LEFT JOIN NPERS U           ON  U.LOGONNAME      = D.USERID
                      LEFT JOIN NAGENDA US         ON  US.CODAGENDA     = U.AGENDA
                      LEFT JOIN TMP_UTILIZATOR UT ON  UT.CODUTILIZATOR = D.USERID
                      LEFT JOIN (
                                  SELECT D.CodPromo,
                                        fnc_array_to_vc3200(array_agg(P.Den_Part    ORDER BY d.codpromopart)) DEN_PART,
                                        fnc_array_to_vc3200(array_agg(CP.Den_ClaseP ORDER BY d.codpromopart)) DEN_CLASEP,
                                        fnc_array_to_vc3200(array_agg(PCF.CodFiscal ORDER BY d.codpromopart)) CIF,
                                        fnc_array_to_vc3200(array_agg(P.Autorizatie ORDER BY d.codpromopart)) AUTORIZATIE,
                                        fnc_array_to_vc3200(array_agg(P.RegCom      ORDER BY d.codpromopart)) REGCOM,
                                        fnc_array_to_vc3200(array_agg(L.Den_Localit ORDER BY d.codpromopart)) DEN_LOCALIT
                                  FROM   Promopart D
                                        LEFT JOIN NPARTCODFISC PCF   ON  D.CodFiscal   = PCF.Cod_CodFiscal
                                        LEFT JOIN NPART P           ON  D.Partener    = P.CodPart
                                        LEFT JOIN NAGENDA AG         ON  D.CodLocatie  = AG.CodAgenda
                                        LEFT JOIN NLOCALIT L         ON  AG.CodLocalit = L.CodLocalit
                                        LEFT JOIN NCLASEP CP         ON  CP.CodClaseP  = D.CodClaseP
                                  WHERE D.CodPromo = vCodPromo
                                  GROUP BY D.CodPromo
                                ) PP ON  PP.CodPromo = D.CodPromo
                WHERE D.CodPromo = vCodPromo
               )
  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 Promotie',             v_rec.NrDoc::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Perioada de valabilitate',   coalesce(To_Char(v_rec.DataStart, 'dd.mm.yyyy'),'') || ' - ' || coalesce(To_Char(v_rec.DataEnd,'dd.mm.yyyy'),''));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Observatii',                 v_rec.Obs);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Moneda',                     v_rec.Simbol);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Tip',                       v_rec.Tip);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Exclus alte promotii',       v_rec.ExclAltePromo);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('In functie de',             v_rec.In_functie_de);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Influenteaza',               v_rec.Influenteaza);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Praguri',                   v_rec.Praguri);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Pe clase de parteneri',     v_rec.PeClasePart);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Tip sediu client',           v_rec.Tip_sediu_client);
    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('Sediu partener',             v_rec.Den_Localit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('Clasa partener ',           v_rec.Den_ClaseP);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rac_masinilibere_setjoinuri</obj_name>
  <obj_hashval>d0d0059720d1e99acf94d44ad5e1c009</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rac_masinilibere_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.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_rac_masinioc_ce_setjoinuri</obj_name>
  <obj_hashval>042216c0a3d11e05cd3727d708872a53</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rac_masinioc_ce_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.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_raportgestval_processlist</obj_name>
  <obj_hashval>968d09680fbdb5f47a1fa813be450bf1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportgestval_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert   varchar :='';
  sSelect   varchar :='';
  sDataIni  varchar := coalesce(to_char((SELECT WME_RESULT FROM PKG_LIST_SELECTGEST2_ZiuaIni(NULL,NULL)), 'fm00'),'') || '.' || coalesce(to_char(getlunalucru(), 'fm00'),'') || '.' || coalesce(to_char(getanlucru(), 'fm0000'),'');
  sDataFin  varchar := coalesce(to_char((SELECT WME_RESULT FROM PKG_LIST_SELECTGEST2_ZiuaFin(NULL,NULL)), 'fm00'),'') || '.' || coalesce(to_char(getlunalucru(), 'fm00'),'') || '.' || coalesce(to_char(getanlucru(), 'fm0000'),'');
  sCondData varchar :='';
  sDataI      VARCHAR(50);
  sDataT      VARCHAR(50);
  sDataL      VARCHAR(50);
  sDataLT     VARCHAR(50);
BEGIN
  --Florin 08.05.2024 - sinc. Oracle
  -- Adina 07.04.2021 - alstart,alstop
  -- Adina 01.12.2020 tichet 41364
  -- Stef 20.11.2020
   IF current_setting('PKG_LIST_SELECTGEST2.vdata', TRUE)::NUMERIC = 0 then
    sDataI := 'I.DATADOC';
    sDataT := 'T.DATADOC';
    sDataL := 'I.DATADOC';
    sDataLT := 'T.DATADOC';
  else
    sDataI := 'N.DATANIR';
    sDataT := 'N.DATANIR';
    sDataL := 'L.DATALIVR';
    sDataLT := 'L.DATALIVR';
  end if;

  IF (SELECT WME_RESULT FROM PKG_LIST_SELECTGEST2_ZiuaIni(NULL,NULL)) = (SELECT WME_RESULT FROM PKG_LIST_SELECTGEST2_ZiuaFin(NULL,NULL))
  THEN sCondData := ' = to_date(''' || coalesce(sDataIni,'') || ''',''DD.MM.YYYY'') ';
  ELSE sCondData := ' BETWEEN to_date(''' || coalesce(sDataIni,'') || ''',''DD.MM.YYYY'') AND to_date(''' || coalesce(sDataFin,'') || ''',''DD.MM.YYYY'') ';
  END IF;

  sInsert :=
  'INSERT INTO '||tmpName||' (
    NAV_CodDoc, NAV_TipDoc, PrefixDoc, NrDoc, DataDoc, Document, TipDoc, ObsDoc,
    AdDebit, ValDFTVA, ValDCTVA, TVAD,
    AdCredit, ValCFTVA, ValCCTVA, TVAC,
    VDocDCTVA, VDocCCTVA,
    SoldFinFTVA, SoldFinCTVA,
    SursaDest, DenIOART,
    SoldIn, AchizIn, Coef,
    DenGest, DenCONT, SimbCONT, RecLivr, Zi, ZiDoc )';

  sSelect := '
  WITH
  IOA1 AS (
    SELECT IO.CODIOART, IO.DEN_IOART, NCo.DEN_CONT, NCo.SIMBOL SIMB_CONT
    FROM IOART1 IO1
         INNER JOIN IOART IO  on IO.CODIOART = IO1.CODIOART AND '||getAnLunaLucru()::varchar||' BETWEEN IO1.ALStart and IO1.ALStop
         LEFT  JOIN NCONT NCo on NCo.CODCONT = IO1.CONT
    WHERE
      IO1.MG = 5
  ),
  SVM AS (
    SELECT GEST, CODIOART, Coalesce(TVA,0) TVA, SOLD, ADAOS, SOLDINTR, ADAOSINTR
    FROM STOCVALLUNA SVL '||pkg_list_base_rapgesttvaval_jointmp('SVL.GEST')||'
    WHERE (AN*12 + LUNA + 1)= '||getAnLunaLucru()::varchar||'
    UNION ALL -- NIR-URI DIN INTRARI
    SELECT N.GEST, NS.CODIOART, NS.TVA, NS.CANTNIR*NS.PRET SOLD, NS.CANTNIR*NS.ADAOS ADAOS, NS.CANTNIR*NS.PRET SOLDINTR, NS.CANTNIR*NS.ADAOS ADAOSINTR
    FROM NIRSTOC NS
      INNER JOIN NIR     N ON N.CODNIR      = NS.CODNIR '||pkg_list_base_rapgesttvaval_jointmp('N.GEST')||'
      INNER JOIN INTRARI I ON I.CODINTR     = N.CODINTR
      INNER JOIN IOA1      ON IOA1.CODIOART = NS.CODIOART
    WHERE I.TIPDOC IN (1, 2, 3, 4, 5, 6, 7) AND  I.ANULAT = 0 AND I.OPERAT = 1
      AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
      AND '||sDataI||' &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'')
    UNION ALL -- NIR-URI DIN MISCARI INTERNE
    SELECT N.GEST, NS.CODIOART, NS.TVA, NS.CANTNIR*NS.PRET SOLD, NS.CANTNIR*NS.ADAOS ADAOS, NS.CANTNIR*NS.PRET SOLDINTR, NS.CANTNIR*NS.ADAOS ADAOSINTR
    FROM NIRSTOC NS
      INNER JOIN NIR    N ON N.CODNIR      = NS.CODNIR '||pkg_list_base_rapgesttvaval_jointmp('N.GEST')||'
      INNER JOIN TRANSF T ON T.CODTRANSF   = N.CODTRANSF
      INNER JOIN IOA1     ON IOA1.CODIOART = NS.CODIOART
    WHERE T.TIPDOC IN (12, 13) AND  T.ANULAT = 0 AND T.OPERAT = 1 AND N.OPERAT = 1
      AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
      AND '||sDataT||' &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'')
    UNION ALL -- LIVRARI INTRARI
    SELECT LV.GEST, LV.CODIOART, Coalesce(LV.TVANEEX, 0) TVA, - LV.PRETINREG*L1.CANT SOLD, - (LV.PRETINREG - LV.PRETACHIZ)*L1.CANT ADAOS, 0 SOLDINTR, 0 ADAOSINTR
    FROM LIVRVAL LV '||pkg_list_base_rapgesttvaval_jointmp('LV.GEST')||'
      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
    WHERE I.TIPDOC IN (1, 2, 3, 4, 5, 6, 7) AND I.OPERAT = 1 AND I.ANULAT = 0
      AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
      AND '||sDataL||' &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'')
    UNION ALL -- LIVRARI IESIRI
    SELECT LV.GEST, LV.CODIOART, Coalesce(LV.TVANEEX, 0) TVA, - LV.PRETINREG*L1.CANT SOLD, - (LV.PRETINREG - LV.PRETACHIZ)*L1.CANT ADAOS, 0 SOLDINTR, 0 ADAOSINTR
    FROM LIVRVAL LV '||pkg_list_base_rapgesttvaval_jointmp('LV.GEST')||'
      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
    WHERE I.TIPDOC IN (14, 16, 19, 20, 21, 22, 23, 24 ) AND I.OPERAT = 1 AND I.ANULAT = 0
      AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
      AND '||sDataL||' &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'')
    UNION ALL -- LIVRARI MISCARI INTERNE
    SELECT LV.GEST, LV.CODIOART, Coalesce(LV.TVANEEX, 0) TVA, - LV.PRETINREG*L1.CANT SOLD, - (LV.PRETINREG - LV.PRETACHIZ)*L1.CANT ADAOS, 0 SOLDINTR, 0 ADAOSINTR
    FROM LIVRVAL LV '||pkg_list_base_rapgesttvaval_jointmp('LV.GEST')||'
      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
    WHERE T.TIPDOC IN (12, 13) AND T.OPERAT = 1 AND T.ANULAT = 0
      AND '||sDataLT||' &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'')
      AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
    UNION ALL -- LIVRARI MARIRI DE STOC
    SELECT LV.GEST, LV.CODIOART, Coalesce(LV.TVANEEX, 0) TVA, LV.PRETINREG*L1.CANT SOLD, (LV.PRETINREG - LV.PRETACHIZ)*L1.CANT ADAOS, LV.PRETINREG*L1.CANT SOLDINTR, (LV.PRETINREG - LV.PRETACHIZ)*L1.CANT ADAOSINTR
    FROM LIVRVAL LV '||pkg_list_base_rapgesttvaval_jointmp('LV.GEST')||'
      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
    WHERE I.TIPDOC = 15 AND I.OPERAT = 1 AND I.ANULAT = 0
      AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
      AND '||sDataL||' &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'')
  )
  SELECT
    NULL CodDoc, NULL TipDoc, '' '' PrefixDoc, NULL NrDoc, to_date('''||sDataIni||''',''DD.MM.YYYY'') DataDoc, ''Sold initial'' Doc, '' '' TipDoc, '' '' ObsDoc,
    0 AdDebit, 0 ValDFTva, 0 ValDCTva, 0 TVAD,
    0 AdCredit, 0 ValCFTva, 0 ValCCTva, 0 TvaC,
    0 VDocDCTVA, 0 VDocCCTVA,
    SUM(SVM.Sold/(1 + SVM.Tva)) SoldFinFTva, SUM(SVM.Sold) SoldFinCTva,
    NULL SursaDest, IOA1.DEN_IOART,
    SUM(SVM.SOLDINTR) SoldIn, SUM(SVM.SOLDINTR - SVM.ADAOSINTR) AchizIn,
    (case when SUM(SVM.SOLDINTR - SVM.ADAOSINTR)=0 then 0 else SUM(SVM.SOLDINTR)/SUM(SVM.SOLDINTR - SVM.ADAOSINTR) end) Coef,
    NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
    NULL RecLivr, ''0'' Zi, ''0'' ZiDoc
  FROM SVM
    INNER JOIN IOA1     ON IOA1.CODIOART = SVM.CODIOART
    INNER JOIN NGEST NG ON NG.CODGEST    = SVM.GEST '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG','CODSUBUNIT')||'
  GROUP BY NG.DEN_GEST, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT
  UNION ALL -- INTRARI
  SELECT
    I.CODINTR CodDoc, I.TIPDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC,
    coalesce(i.prefixdoc,'''') ||coalesce(i.seriadoc,'''')||coalesce(i.nrdoc::varchar,'''') ||''/''||coalesce(to_char(i.datadoc,''dd.mm.yyyy''),'''') Doc,
    pkg_list_base_utils_decode_tipdoc(I.TIPDOC), I.Obs,
    SUM(NS.CANTNIR*(NS.ADAOS - NS.PRET*NS.TVA/(1+NS.TVA) )) AdDebit, SUM(NS.CANTNIR*NS.PRET/(1+NS.TVA)) ValDFTva, SUM(NS.CANTNIR*NS.PRET) ValDCTva, SUM(NS.CANTNIR*NS.PRET*NS.TVA/(1+NS.TVA)) TVAD,
    0 AdCredit, 0 ValCFTva, 0 ValCCTva, 0 TvaC,
    SUM(NS.CANTNIR*I1.PRETORIG*I1.COEFDISCMAJ*CASE WHEN I1.TVA = 0 THEN 1 WHEN I.TIPDOC = 3 THEN 1 WHEN I1.CANT*I1.PU = 0 THEN 1 ELSE 1+I1.TVA/(I1.CANT*I1.PU) END) VDocDCTVA, 0 VDocCCTVA,
    SUM(NS.CANTNIR*NS.PRET/(1+NS.TVA)) SoldFinFTva, SUM(NS.CANTNIR*NS.PRET) SoldFinCTva,
    (Case  When I.TIPDOC=6 then S.DEN_SUBUNIT When I.TIPDOC=7 then G.DEN_GEST else NP.DEN_PART end) SursaDest, IOA1.DEN_IOART,
    SUM(NS.CANTNIR*NS.PRET) SoldIn, SUM(NS.CANTNIR*(NS.PRET - NS.ADAOS)) AchizIn,
    (case when SUM(NS.CANTNIR*(NS.PRET - NS.ADAOS))=0 then 0 else SUM(NS.CANTNIR*NS.PRET)/SUM(NS.CANTNIR*(NS.PRET - NS.ADAOS)) end) Coef,
    NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
    N.NRNIR||''/''||to_char(N.DATANIR,''dd.mm.yyyy'') RecLivr, TO_CHAR(N.DATANIR,''DD'')::numeric Zi, TO_CHAR(I.DATADOC,''DD'')::numeric ZiDoc
  FROM NIRSTOC NS
    INNER JOIN IOA1        ON IOA1.CODIOART = NS.CODIOART
    INNER JOIN NIR      N  ON N.CODNIR      = NS.CODNIR'||pkg_list_base_rapgesttvaval_jointmp('N.GEST')||'
    INNER JOIN NGEST    NG ON NG.CODGEST    = N.GEST '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG','CODSUBUNIT')||'
    INNER JOIN INTRARI  I  ON I.CODINTR     = N.CODINTR
    LEFT  JOIN INTRARI1 I1 ON I1.CODINTR    = I.CODINTR AND I1.CODINTR1 = NS.CODINTR1
    LEFT  JOIN NPART    NP ON NP.CODPART    = I.PARTENER
    LEFT  JOIN NGEST    G  ON G.CODGEST     = I.CODGESTPROD
    LEFT  JOIN NSUBUNIT S  ON S.CODSUBUNIT = I.CODSUBUNIT
  WHERE I.TIPDOC IN (1, 2, 3, 4, 5, 6, 7) AND I.ANULAT = 0 AND I.OPERAT = 1
    AND '||sDataI||sCondData||'
    AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
  GROUP BY I.CODINTR, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC, I.OBS, N.NRNIR, N.DATANIR, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST, NP.DEN_PART, S.DEN_SUBUNIT, G.DEN_GEST
  UNION ALL -- INTRARI DIN TRANSFERURI
  SELECT
    T.CODTRANSF CodDoc, T.TIPDOC, T.PREFIXDOC, T.NRDOC, T.DATADOC,
    coalesce(t.prefixdoc,'''') ||coalesce(t.seriadoc,'''')||coalesce(t.nrdoc::varchar,'''')||''/''||coalesce(to_char(t.datadoc,''dd.mm.yyyy''),'''') Doc,
    pkg_list_base_utils_decode_tipdoc(T.TIPDOC), T.Obs,
    SUM(NS.CANTNIR*(NS.ADAOS - NS.PRET*NS.TVA/(1+NS.TVA) )) AdDebit, SUM(NS.CANTNIR*NS.PRET/(1+NS.TVA)) ValDFTva, SUM(NS.CANTNIR*NS.PRET) ValDCTva, SUM(NS.CANTNIR*NS.PRET*NS.TVA/(1+NS.TVA)) TVAD,
    0 AdCredit, 0 ValCFTva, 0 ValCCTva, 0 TvaC,
    SUM(NS.CANTNIR*T1.PU*CASE WHEN T1.TVA = 0 THEN 1 WHEN T1.CANT*T1.PU = 0 THEN 1 ELSE 1+T1.TVA/(T1.CANT*T1.PU) END) VDocDCTVA, 0 VDocCCTVA,
    SUM(NS.CANTNIR*NS.PRET/(1+NS.TVA)) SoldFinFTva, SUM(NS.CANTNIR*NS.PRET) SoldFinCTva,
    NG_S.DEN_GEST SursaDest, IOA1.DEN_IOART,
    SUM(NS.CANTNIR*NS.PRET) SoldIn, SUM(NS.CANTNIR*(NS.PRET - NS.ADAOS)) AchizIn,
    (case when SUM(NS.CANTNIR*(NS.PRET - NS.ADAOS))=0 then 0 else SUM(NS.CANTNIR*NS.PRET)/SUM(NS.CANTNIR*(NS.PRET - NS.ADAOS)) end) Coef,
    NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
    N.NRNIR||''/''||to_char(N.DATANIR,''dd.mm.yyyy'') RecLivr, TO_CHAR(N.DATANIR,''DD'')::numeric Zi, TO_CHAR(T.DATADOC,''DD'')::numeric ZiDoc
  FROM TRANSF T
    INNER JOIN NIR     N    ON N.CODTRANSF     = T.CODTRANSF'||pkg_list_base_rapgesttvaval_jointmp('N.GEST')||'
    INNER JOIN NIRSTOC NS   ON NS.CODNIR       = N.CODNIR
    INNER JOIN IOA1         ON IOA1.CODIOART   = NS.CODIOART
    INNER JOIN NGEST   NG   ON NG.CODGEST      = N.GEST '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG','CODSUBUNIT')||'
    LEFT  JOIN TRANSF1 T1   ON T1.CODTRANSF    = T.CODTRANSF AND T1.CODTRANSF1 = NS.CODTRANSF1
    LEFT  JOIN NIRSTOC NS_S ON NS_S.CODNIRSTOC = NS.CODNIRSTOCPARINTE AND (NS.CODNIRSTOCPARINTE IS NOT NULL)
    LEFT  JOIN NIR     N_S  ON N_S.CODNIR      = NS_S.CODNIR
    LEFT  JOIN LIVRVAL LV_S ON LV_S.CODLIVR1   = NS.CODLIVR1
    LEFT  JOIN NGEST   NG_S ON NG_S.CODGEST    = coalesce(N_S.GEST,LV_S.GEST)
  WHERE T.TIPDOC = 12 AND T.ANULAT = 0 AND T.OPERAT = 1 AND N.OPERAT = 1
    AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
    AND '||sDataT||sCondData||'
  GROUP BY T.CODTRANSF, T.TIPDOC, T.PREFIXDOC, T.SERIADOC, T.NRDOC, T.DATADOC, T.OBS, N.NRNIR, N.DATANIR, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST, NG_S.DEN_GEST
  UNION ALL -- IESIRI DIN TRANSFERURI
  SELECT
    T.CODTRANSF CodDoc, T.TIPDOC, T.PREFIXDOC, T.NRDOC, T.DATADOC,
    coalesce(t.prefixdoc,'''') ||coalesce(t.seriadoc,'''')||coalesce(t.nrdoc::varchar,'''')||''/''||coalesce(to_char(t.datadoc,''dd.mm.yyyy''),'''') Doc,
    pkg_list_base_utils_decode_tipdoc(T.TIPDOC), T.Obs,
    0 Addebit, 0 ValDFTva, 0 ValDCTva, 0 TvaD,
    SUM(L1.CANT*(LV.PRETINREG/(1+Coalesce(LV.TVANEEX, 0)) - LV.PRETACHIZ)) AdCredit, SUM(L1.CANT*LV.PRETINREG/(1+Coalesce(LV.TVANEEX, 0))) ValCFTva, SUM(L1.CANT*LV.PRETINREG) ValCCTva, SUM(L1.CANT*LV.PRETINREG*Coalesce(LV.TVANEEX, 0)/(1+Coalesce(LV.TVANEEX, 0))) TvaC,
    0 VDocDCTVA, - SUM(L1.CANT*T1.PU*CASE WHEN T1.TVA = 0 THEN 1 WHEN T1.CANT*T1.PU = 0 THEN 1 ELSE 1+T1.TVA/(T1.CANT*T1.PU) END) VDocCCTVA,
    -SUM(L1.CANT*LV.PRETINREG/(1+Coalesce(LV.TVANEEX, 0))) SoldFinFTva, -SUM(L1.CANT*LV.PRETINREG) SoldFinCTva,
    NG_D.DEN_GEST SursaDest, IOA1.DEN_IOART,
    0 SoldIn, 0 AchizIn,
    0 Coef,
    NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
    L.NRLIVR||''/''||to_char(L.DATALIVR,''dd.mm.yyyy'') RecLivr, TO_CHAR(L.DATALIVR,''DD'')::numeric Zi, TO_CHAR(T.DATADOC,''DD'')::numeric ZiDoc
  FROM TRANSF T
    INNER JOIN LIVR    L    ON L.CODTRANSF   = T.CODTRANSF
    INNER JOIN LIVR1   L1   ON L1.CODLIVR    = L.CODLIVR
    INNER JOIN LIVRVAL LV   ON LV.CODLIVR1   = L1.CODLIVR1'||pkg_list_base_rapgesttvaval_jointmp('LV.GEST')||'
    INNER JOIN IOA1         ON IOA1.CODIOART = LV.CODIOART
    INNER JOIN NGEST   NG   ON NG.CODGEST    = LV.GEST '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG','CODSUBUNIT')||'
    LEFT  JOIN TRANSF1 T1   ON T1.CODTRANSF  = T.CODTRANSF AND T1.CODTRANSF1 = L1.CODIES1
    LEFT  JOIN NIRSTOC NS_D ON NS_D.CODLIVR1 = L1.CODLIVR1
    LEFT  JOIN NIR     N_D  ON N_D.CODNIR    = NS_D.CODNIR
    LEFT  JOIN NGEST   NG_D ON NG_D.CODGEST  = N_D.GEST
  WHERE T.TIPDOC = 12 AND T.ANULAT = 0 AND T.OPERAT = 1
    AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
    AND '||sDataLT||sCondData||'
  GROUP BY T.CODTRANSF, T.TIPDOC, T.PREFIXDOC, T.SERIADOC, T.NRDOC, T.DATADOC, T.OBS, L.NRLIVR, L.DATALIVR, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST, NG_D.DEN_GEST
  UNION ALL -- MODIFICARI DE PRET
  SELECT
    CODTRANSF CodDoc, TIPDOC, PREFIXDOC, NRDOC, DATADOC, PREFIXDOC||SERIADOC||NRDOC::varchar||''/''||To_Char(DATADOC,''dd.mm.yyyy'') Doc, pkg_list_base_utils_decode_tipdoc(TIPDOC) TipDoc, Obs,
    SUM(NS_CantNIR * (NS_ADAOS - NS_PRET * NS_TVA / (1+NS_TVA))) AdDebit, SUM(NS_CantNIR*NS_PRET/(1+NS_TVA)) ValDFTva, SUM(NS_CantNIR*NS_PRET) ValDCTva, SUM(NS_CantNIR*NS_PRET*NS_TVA/(1+NS_TVA)) TVAD,
    SUM(NS_CantNIR*CASE WHEN CODNIRSTOCPARINTE IS NULL THEN (LV_S_PRETINREG/(1+LV_S_TVANEEX) - LV_S_PRETACHIZ) ELSE (NS_S_ADAOS - NS_S_PRET*NS_S_TVA/(1+NS_S_TVA)) END) AdCredit,
    SUM(NS_CantNIR*CASE WHEN CODNIRSTOCPARINTE IS NULL THEN LV_S_PRETINREG/(1+LV_S_TVANEEX)                    ELSE NS_S_PRET/(1+NS_S_TVA)                         END) ValCFTva,
    SUM(NS_CantNIR*CASE WHEN CODNIRSTOCPARINTE IS NULL THEN LV_S_PRETINREG                                     ELSE NS_S_PRET                                      END) ValCCTva,
    SUM(NS_CantNIR*CASE WHEN CODNIRSTOCPARINTE IS NULL THEN LV_S_PRETINREG*LV_S_TVANEEX/(1+LV_S_TVANEEX)       ELSE NS_S_PRET*NS_S_TVA/(1+NS_S_TVA)                END) TvaC,
    SUM(NS_CantNIR*T1_PU*CASE WHEN T1_TVA = 0 THEN 1 WHEN T1_CANT*T1_PU = 0 THEN 1 ELSE 1+T1_TVA/(T1_CANT*T1_PU) END) VDocDCTVA, -SUM(NS_CantNIR*T1_PU*CASE WHEN T1_TVA = 0 THEN 1 WHEN T1_CANT*T1_PU = 0 THEN 1 ELSE 1+T1_TVA/(T1_CANT*T1_PU) END) VDocCCTVA,
    SUM(NS_CantNIR*NS_PRET/(1+NS_TVA)) - SUM(NS_CantNIR*CASE WHEN CODNIRSTOCPARINTE IS NULL THEN LV_S_PRETINREG/(1+LV_S_TVANEEX) ELSE NS_S_PRET/(1+NS_S_TVA) END) SoldFinFTva,
    SUM(NS_CantNIR*NS_PRET)            - SUM(NS_CantNIR*CASE WHEN CODNIRSTOCPARINTE IS NULL THEN LV_S_PRETINREG                  ELSE NS_S_PRET              END) SoldFinCTva,
    DEN_GEST SursaDest, DEN_IOART,
    SUM(NS_CantNIR*NS_PRET) SoldIn, SUM(NS_CantNIR*(NS_PRET - NS_ADAOS)) AchizIn,
    CASE WHEN SUM(NS_CantNIR*(NS_PRET - NS_ADAOS)) = 0 THEN 0 ELSE SUM(NS_CantNIR*NS_PRET)/SUM(NS_CantNIR*(NS_PRET - NS_ADAOS)) END Coef,
    DEN_GEST, DEN_CONT, SIMB_CONT,
    NRNIR||''/''||to_char(DATANIR,''dd.mm.yyyy'') RecLivr, TO_CHAR(DATANIR,''DD'')::numeric Zi, TO_CHAR(DATADOC,''DD'')::numeric ZiDoc
  FROM (
    SELECT
      T.CODTRANSF, T.TIPDOC, Coalesce(T.PREFIXDOC,'''') PREFIXDOC, Coalesce(T.SERIADOC,'''') SERIADOC, T.NRDOC, T.DATADOC, T.OBS,
      N.NRNIR, N.DATANIR, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST,
      NS.CODNIRSTOCPARINTE, NS.CANTNIR NS_CantNIR, Coalesce(NS.ADAOS, 0) NS_ADAOS, Coalesce(NS.PRET, 0) NS_PRET, Coalesce(NS.TVA, 0) NS_TVA,
      Coalesce(T1.CANT, 0) T1_CANT, Coalesce(T1.PU, 0) T1_PU, Coalesce(T1.TVA, 0) T1_TVA,
      Coalesce(NS_S.PRET, 0) NS_S_PRET, Coalesce(NS_S.TVA, 0) NS_S_TVA, Coalesce(NS_S.ADAOS, 0) NS_S_ADAOS,
      Coalesce(LV_S.PRETACHIZ, 0) LV_S_PRETACHIZ, Coalesce(LV_S.PRETINREG, 0) LV_S_PRETINREG, Coalesce(LV_S.TVANEEX, 0) LV_S_TVANEEX
    FROM TRANSF T
      INNER JOIN NIR     N    ON N.CODTRANSF     = T.CODTRANSF'||pkg_list_base_rapgesttvaval_jointmp('N.GEST')||'
      INNER JOIN NIRSTOC NS   ON NS.CODNIR       = N.CODNIR
      INNER JOIN IOA1         ON IOA1.CODIOART   = NS.CODIOART
      INNER JOIN NGEST   NG   ON NG.CODGEST      = N.GEST '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG','CODSUBUNIT')||'
      LEFT  JOIN TRANSF1 T1   ON T1.CODTRANSF    = T.CODTRANSF AND T1.CODTRANSF1 = NS.CODTRANSF1
      LEFT  JOIN NIRSTOC NS_S ON NS_S.CODNIRSTOC = NS.CODNIRSTOCPARINTE AND (NS.CODNIRSTOCPARINTE IS NOT NULL)
      LEFT  JOIN NIR     N_S  ON N_S.CODNIR      = NS_S.CODNIR
      LEFT  JOIN LIVR1   L1_S ON L1_S.CODLIVR1   = NS.CODLIVR1 AND (NS.CODNIRSTOCPARINTE IS NULL)
      LEFT  JOIN LIVRVAL LV_S ON LV_S.CODLIVR1   = L1_S.CODLIVR1
    WHERE T.TIPDOC = 13 AND T.ANULAT = 0 AND T.OPERAT = 1 AND N.OPERAT = 1
      AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
      AND '||sDataT||sCondData||'
  ) AA_PG
  GROUP BY CODTRANSF, TIPDOC, PREFIXDOC, SERIADOC, NRDOC, DATADOC, OBS, NRNIR, DATANIR, DEN_IOART, DEN_CONT, SIMB_CONT, DEN_GEST
  UNION ALL -- RETUR INTRARI VALORIC
  SELECT
    I.CODINTR CodDoc, I.TIPDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC,
    coalesce(i.prefixdoc,'''') ||coalesce(i.seriadoc,'''')||coalesce(i.nrdoc::varchar,'''') ||''/''||coalesce(to_char(i.datadoc,''dd.mm.yyyy''),'''') Doc,
    pkg_list_base_utils_decode_tipdoc(I.TIPDOC), I.Obs,
    - SUM(L1.CANT*(LV.PRETINREG/(1+Coalesce(LV.TVANEEX, 0)) - LV.PRETACHIZ) ) AdDebit, - SUM(L1.CANT*LV.PRETINREG/(1+Coalesce(LV.TVANEEX, 0))) ValDFTva,
    - SUM(L1.CANT*LV.PRETINREG) ValDCTva, - SUM(L1.CANT*LV.PRETINREG*Coalesce(LV.TVANEEX, 0)/(1+Coalesce(LV.TVANEEX, 0))) TvaD,
    0 Adcredit, 0 ValCFTva, 0 ValCCTva, 0 TvaC,
    -SUM(L1.CANT*I1.PRETORIG*I1.COEFDISCMAJ*CASE WHEN I1.TVA = 0 THEN 1 WHEN I.TIPDOC = 3 THEN 1 WHEN I1.CANT*I1.PU = 0 THEN 1 ELSE 1+I1.TVA/(I1.CANT*I1.PU) END) VDocDCTVA, 0 VDocCCTVA,
    -SUM(L1.CANT*LV.PRETINREG/(1+Coalesce(LV.TVANEEX, 0))) SoldFinFTva, -SUM(L1.CANT*LV.PRETINREG) SoldFinCTva,
    (case when I.TIPDOC=6 then S.DEN_SUBUNIT when I.TIPDOC=7 then G.DEN_GEST else NP.DEN_PART end) SursaDest, IOA1.DEN_IOART,
    0 SoldIn, 0 AchizIn,
    0 Coef,
    NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
    L.NRLIVR||''/''||to_char(L.DATALIVR,''dd.mm.yyyy'') RecLivr, TO_CHAR(L.DATALIVR,''DD'')::numeric Zi, TO_CHAR(I.DATADOC,''DD'')::numeric ZiDoc
  FROM INTRARI I
    INNER JOIN LIVR     L  ON L.CODINTR     = I.CODINTR
    INNER JOIN LIVR1    L1 ON L1.CODLIVR    = L.CODLIVR
    INNER JOIN LIVRVAL  LV ON LV.CODLIVR1   = L1.CODLIVR1'||pkg_list_base_rapgesttvaval_jointmp('LV.GEST')||'
    INNER JOIN IOA1        ON IOA1.CODIOART = LV.CODIOART
    INNER JOIN NGEST    NG ON NG.CODGEST    = LV.GEST '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG','CODSUBUNIT')||'
    LEFT  JOIN INTRARI1 I1 ON I1.CODINTR    = I.CODINTR AND I1.CODINTR1 = L1.CODINTR1
    LEFT  JOIN NPART    NP ON NP.CODPART    = I.PARTENER
    LEFT  JOIN NGEST    G  ON G.CODGEST     = I.CODGESTPROD
    LEFT  JOIN NSUBUNIT S  ON S.CODSUBUNIT  = I.CODSUBUNIT
  WHERE I.TIPDOC IN (1, 2, 3, 4, 5, 6, 7) AND I.OPERAT = 1 AND I.ANULAT = 0
    AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
    AND '||sDataL||sCondData||'
  GROUP BY I.CODINTR, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC, I.OBS, L.NRLIVR, L.DATALIVR, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST, NP.DEN_PART, S.DEN_SUBUNIT, G.DEN_GEST
  UNION ALL  -- IESIRI VALORIC
  SELECT
    I.CODIES CodDoc, I.TIPDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC,
    coalesce(i.prefixdoc,'''') ||coalesce(i.seriadoc,'''')||coalesce(i.nrdoc::varchar,'''') ||''/''||coalesce(to_char(i.datadoc,''dd.mm.yyyy''),'''') Doc,
    pkg_list_base_utils_decode_tipdoc(I.TIPDOC), I.Obs,
    0 AdDebit, 0 ValDFTva, 0 ValDCTva, 0 TvaD,
    SUM(L1.CANT*(LV.PRETINREG/(1+Coalesce(LV.TVANEEX, 0)) - LV.PRETACHIZ) ) Adcredit, SUM(L1.CANT*LV.PRETINREG/(1+Coalesce(LV.TVANEEX, 0))) ValCFTva, SUM(L1.CANT*LV.PRETINREG) ValCCTva,
    SUM(L1.CANT*LV.PRETINREG*Coalesce(LV.TVANEEX, 0)/(1+Coalesce(LV.TVANEEX, 0))) TvaC,
    0 VDocDCTVA, SUM(L1.CANT*I1.PRETORIG*I1.COEFDISCMAJ*CASE WHEN I1.TVA = 0 THEN 1 WHEN I.TIPDOC IN (16,21) THEN 1 WHEN I1.CANT*I1.PU = 0 THEN 1 ELSE 1+I1.TVA/(I1.CANT*I1.PU) END) VDocCCTVA,
    -SUM(L1.CANT*LV.PRETINREG/(1+Coalesce(LV.TVANEEX, 0))) SoldFinFTva, -SUM(L1.CANT*LV.PRETINREG) SoldFinCTva,
    (case when I.TIPDOC=14 then ''-'' when I.TIPDOC=16 then ''-'' when I.TIPDOC=23 then S.DEN_SUBUNIT when I.TIPDOC=24 then NG.DEN_GEST else NP.DEN_PART end) SursaDest, IOA1.DEN_IOART,
    0 SoldIn, 0 AchizIn,
    0 Coef,
    NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
    L.NRLIVR||''/''||to_char(L.DATALIVR,''dd.mm.yyyy'') RecLivr, TO_CHAR(L.DATALIVR,''DD'')::numeric Zi, TO_CHAR(I.DATADOC,''DD'')::numeric ZiDoc
  FROM IESIRI I
    INNER JOIN LIVR     L  ON L.CODIES      = I.CODIES
    INNER JOIN LIVR1    L1 ON L1.CODLIVR    = L.CODLIVR
    INNER JOIN LIVRVAL  LV ON LV.CODLIVR1   = L1.CODLIVR1'||pkg_list_base_rapgesttvaval_jointmp('LV.GEST')||'
    INNER JOIN IOA1        ON IOA1.CODIOART = LV.CODIOART
    INNER JOIN NGEST    NG ON NG.CODGEST    = LV.GEST '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG','CODSUBUNIT')||'
    LEFT  JOIN IESIRI1  I1 ON I1.CODIES     = I.CODIES AND I1.CODIES1 = L1.CODIES1
    LEFT  JOIN NPART    NP ON NP.CODPART    = I.PARTENER
    LEFT  JOIN NGEST    G  ON G.CODGEST     = I.CODGESTPROD
    LEFT  JOIN NSUBUNIT S  ON S.CODSUBUNIT  = I.CODSUBUNIT
  WHERE I.TIPDOC IN (14, 16, 19, 20, 21, 22, 23, 24) AND I.OPERAT = 1 AND I.ANULAT = 0
    AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
    AND '||sDataL||sCondData||'
  GROUP BY I.CODIES, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC, I.OBS, L.NRLIVR, L.DATALIVR, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST, NP.DEN_PART, S.DEN_SUBUNIT, G.DEN_GEST
  UNION ALL -- MARIRI DE STOC VALORIC
  SELECT
    I.CODIES CodDoc, I.TIPDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC,
    coalesce(i.prefixdoc,'''') ||coalesce(i.seriadoc,'''')||coalesce(i.nrdoc::varchar,'''') ||''/''||coalesce(to_char(i.datadoc,''dd.mm.yyyy''),'''') Doc,
    pkg_list_base_utils_decode_tipdoc(I.TIPDOC), I.Obs,
    SUM(L1.CANT*(LV.PRETINREG/(1+Coalesce(LV.TVANEEX, 0)) - LV.PRETACHIZ)) AdDebit, SUM(L1.CANT*LV.PRETINREG/(1+Coalesce(LV.TVANEEX, 0))) ValDFTva, SUM(L1.CANT*LV.PRETINREG) ValDCTva, SUM(L1.CANT*LV.PRETINREG*Coalesce(LV.TVANEEX, 0)/(1+Coalesce(LV.TVANEEX, 0))) TvaD,
    0 Adcredit, 0 ValCFTva, 0 ValCCTva, 0 TvaC,
    SUM(L1.CANT*I1.PRETORIG*I1.COEFDISCMAJ*CASE WHEN I1.TVA = 0 THEN 1 WHEN I.TIPDOC IN (16,21) THEN 1 WHEN I1.CANT*I1.PU = 0 THEN 1 ELSE 1+I1.TVA/(I1.CANT*I1.PU) END) VDocDCTVA, 0 VDocCCTVA,
    SUM(L1.CANT*LV.PRETINREG/(1+Coalesce(LV.TVANEEX, 0))) SoldFinFTva, SUM(L1.CANT*LV.PRETINREG) SoldFinCTva,
    NG.DEN_GEST SursaDest, IOA1.DEN_IOART,
    SUM(L1.CANT*LV.PRETINREG) SoldIn, SUM(L1.CANT*LV.PRETINREG) AchizIn,
    (case when SUM(L1.CANT*LV.PRETINREG)=0 then 0 else SUM(L1.CANT*LV.PRETINREG)/SUM(L1.CANT*LV.PRETINREG) end) Coef,
    NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
    L.NRLIVR||''/''||to_char(L.DATALIVR,''dd.mm.yyyy'') RecLivr, TO_CHAR(L.DATALIVR,''DD'')::numeric Zi, TO_CHAR(I.DATADOC,''DD'')::numeric ZiDoc
  FROM IESIRI I
    INNER JOIN LIVR    L  ON L.CODIES      = I.CODIES
    INNER JOIN LIVR1   L1 ON L1.CODLIVR    = L.CODLIVR
    INNER JOIN LIVRVAL LV ON LV.CODLIVR1   = L1.CODLIVR1'||pkg_list_base_rapgesttvaval_jointmp('LV.GEST')||'
    INNER JOIN IOA1       ON IOA1.CODIOART = LV.CODIOART
    INNER JOIN NGEST   NG ON NG.CODGEST    = LV.GEST '||PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG','CODSUBUNIT')||'
    LEFT  JOIN IESIRI1 I1 ON I1.CODIES     = I.CODIES AND I1.CODIES1 = L1.CODIES1
  WHERE I.TIPDOC = 15 AND I.OPERAT = 1 AND I.ANULAT = 0
    AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
    AND '||sDataL||sCondData||'
  GROUP BY I.CODIES, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC, I.OBS, L.NRLIVR, L.DATALIVR, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST';

  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
  -- din versiunea veche: EXECUTE 'UPDATE ' || coalesce(tmpName,'') || ' SET SoldAd=AdDebit-AdCredit WHERE SoldAd=0';
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_raportp_m_processlist</obj_name>
  <obj_hashval>8e4ef18352d0e5dad6882c27965845ac</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportp_m_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR :=   'RaportP P, RaportP1 P1, RaportP2 P2, NGEST G, FORMATII F, NSUBUNIT S, NPERS A, NartObj Ob, ProdMan PM, NOper Op, Comanda1 C1, Comanda C,'||
                               'utilaje2c ut2c,utilaje ut,utilaje2 ut2,ninterventiiauto interv,nartobj intervserv,nartobj utilajobj,NCLASEINT CLSINT,prodcomp pc';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 11.05.2021 - alstart, alstop
  --Adina 22.12.2020 tichet 41810
  --Adina 16 septembrie 2020
  CALL PRC_AL_CHECK('tarifeman1', 0);

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'RAPORTPDET', 'PDET', 'PDET.CODRAPORTP = P.CODRAPORTP',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = OB.CODOBIECT' ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = OB.CODOBIECT' ,NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_RAPORTP_M.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
    NAV_CodDoc, NAV_TipDoc, NrDoc, DataI, DataS, PeForm, Sectie, Form, Sub,
    Ang, Ord,
    Com, Art, Oper,
    Realizat, TNorma, TValoare, Rebut, Interventie, Utilaj ' || gUserFields || ')
  SELECT
    P.CodRaportP, 63, P.NrDoc, coalesce(P2.DataStart,P.DATAI), coalesce(P2.DataStop,P.DATAS), (case when P.Pe_Formatie=1 then ''Da'' else ''Nu'' end), G.Den_Gest, F.Den_Formatie, S.Den_Subunit,
    (case when P1.Angajat=0 then A.NUME else A.NUME||'' ''||A.PRENUME end), ROW_NUMBER() OVER (PARTITION BY P2.CodRaportP1 ORDER BY P2.CODRAPORTP2 ASC),
    coalesce(C.PREFIXDOC,'''')||coalesce(C.NRDOC::varchar,'''')||''/''||to_char(C.DATADOC,''dd.mm.yyyy''), OB.DENUMIRE,
    coalesce(PM.NROP::varchar,'''')||''/''|| coalesce(OP.DENUMIRE,''''),
    P2.REALIZAT, PM.TU * P2.REALIZAT, T1.Tarif * PM.TU * P2.REALIZAT / 60, P2.REBUT,
    intervserv.denumire,
    utilajobj.denumire ' || gUserAlias || '
  FROM RaportP P
    INNER JOIN RaportP0         P0          ON P0.CodRaportP             = P.CodRaportP
    INNER JOIN RaportP1         P1          ON P1.CodRaportP0            = P0.CodRaportP0
    INNER JOIN RaportP2         P2          ON P2.CodRaportP1            = P1.CodRaportP1
    INNER JOIN ProdMan          PM          ON PM.CodMan                 = P2.CodMan
    INNER JOIN Tarifeman1       T1          ON T1.CodTarif               = PM.CodTarif AND (P.AN*12+P.LUNA) BETWEEN T1.ALSTART and T1.ALSTOP
    INNER JOIN Comanda1         C1          ON C1.CodComanda1            = P2.CodComanda1
    INNER JOIN Comanda          C           ON C.CodComanda              = C1.CodComanda
    INNER JOIN ProdComp         PC          ON PC.CodProdComp            = PM.CodProdComp
    LEFT  JOIN NGEST            G           ON G.CodGest                 = P.Sectie
    LEFT  JOIN FORMATII         F           ON F.CodFormatie             = P.Formatie
    LEFT  JOIN NSUBUNIT         S           ON S.CodSubunit              = P.Subunitatea
    LEFT  JOIN NPERS            A           ON A.CodPers                 = P1.Angajat
    LEFT  JOIN NartObj          Ob          ON Ob.CodObiect              = P2.CodObiect
    LEFT  JOIN NOper            Op          ON Op.CodOp                  = PM.CodOp
    left  join utilaje2c        ut2c        on ut2c.codcomanda1           = c1.codcomanda1
    left  join utilaje          ut          on ut2c.codutilaj             = ut.codutilaj
    left  join utilaje2         ut2        on ut2.codutilaj2             = ut2c.codutilaj2
    left  join ninterventiiauto interv      on interv.CODINTERVENTIIAUTO = ut2.interventie
    LEFT  JOIN NCLASEINT        CLSINT      ON INTERV.CLASA               = CLSINT.CODCLASEINT
    left  join nartobj          intervserv on intervserv.codobiect       = interv.serviciu
    left  join nartobj          utilajobj  on utilajobj.codobiect       = ut.codobiect' || gSuplJoins || '
  WHERE C.ANULAT = 0 AND C.OPERAT = 1 AND C.TIPTRANZACTIE = 1 AND
        P.An*12 + p.Luna BETWEEN current_setting(''PKG_LIST_SELECTLUNAAN.vLunaStart'', true)::numeric AND current_setting(''PKG_LIST_SELECTLUNAAN.vLunaStop'', true)::numeric '
        || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('P',NULL,NULL,NULL),'') || '
  UNION ALL
  SELECT
    P.CodRaportP, 63, P.NrDoc, coalesce(P2.DataStart,P.DATAI), coalesce(P2.DataStop,P.DATAS), (case when P.Pe_Formatie=1 then ''Da'' else ''Nu'' end), G.Den_Gest, F.Den_Formatie, S.Den_Subunit,
    (case when P1.Angajat=0 then A.NUME else A.NUME||'' ''||A.PRENUME end), ROW_NUMBER() OVER (PARTITION BY P2.CodRaportP1 ORDER BY P2.CODRAPORTP2 ASC),
    coalesce(C.PREFIXDOC,'''')||coalesce(C.NRDOC::varchar,'''')||''/''||to_char(C.DATADOC,''dd.mm.yyyy''), OB.DENUMIRE,
    coalesce(PM.NROP::varchar,'''')||''/''|| coalesce(OP.DENUMIRE,''''),
    P2.REALIZAT, P2.TU * P2.REALIZAT, T1.Tarif * P2.TU * P2.REALIZAT / 60, P2.REBUT,
    intervserv.denumire,
    utilajobj.denumire ' || gUserAlias || '
  FROM RaportP P
    INNER JOIN RaportP0         P0          ON P0.CodRaportP              = P.CodRaportP
    INNER JOIN RaportP1         P1          ON P1.CodRaportP0             = P0.CodRaportP0
    INNER JOIN RaportP2         P2          ON P2.CodRaportP1             = P1.CodRaportP1
    INNER JOIN Comanda1         C1          ON C1.CodComanda1             = P2.CodComanda1
    INNER JOIN Comanda          C           ON C.CodComanda               = C1.CodComanda
    INNER JOIN Tarifeman1       T1          ON T1.CodTarif                = P2.CodTarif AND (P.AN*12+P.LUNA) BETWEEN T1.ALSTART and T1.ALSTOP
    LEFT  JOIN ProdMan          PM          ON PM.CodMan                  = P2.CodMan
    LEFT  JOIN ProdComp         PC          ON PC.CodProdComp             = PM.CodProdComp
    LEFT  JOIN NGEST            G           ON G.CodGest                  = P.Sectie
    LEFT  JOIN FORMATII         F           ON F.CodFormatie              = P.Formatie
    LEFT  JOIN NSUBUNIT         S           ON S.CodSubunit               = P.Subunitatea
    LEFT  JOIN NPERS            A           ON A.CodPers                  = P1.Angajat
    LEFT  JOIN NartObj          Ob          ON Ob.CodObiect               = P2.CodObiect
    LEFT  JOIN NOper            Op          ON Op.CodOp                   = P2.CodOp
    left  join utilaje2c        ut2c        on ut2c.codcomanda1           = c1.codcomanda1
    left  join utilaje          ut          on ut2c.codutilaj             = ut.codutilaj
    left  join utilaje2         ut2        on ut2.codutilaj2             = ut2c.codutilaj2
    left  join ninterventiiauto interv     on interv.CODINTERVENTIIAUTO = ut2.interventie
    LEFT  JOIN NCLASEINT        CLSINT      ON INTERV.CLASA               = CLSINT.CODCLASEINT
    left  join nartobj          intervserv on intervserv.codobiect       = interv.serviciu
    left  join nartobj          utilajobj  on utilajobj.codobiect       = ut.codobiect' || gSuplJoins || '
  WHERE C.ANULAT = 0 AND C.OPERAT = 1 AND C.TIPTRANZACTIE = 1 AND coalesce(PM.CODMAN,0) = 0 AND
        P.An*12 + p.Luna BETWEEN current_setting(''PKG_LIST_SELECTLUNAAN.vLunaStart'', true)::numeric AND current_setting(''PKG_LIST_SELECTLUNAAN.vLunaStop'', true)::numeric '
        || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('P',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_raportp_processlist</obj_name>
  <obj_hashval>246f3d77e865b3e23adf867210e75610</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportp_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR :=   'RaportP P, RaportP1 P1, RaportP2 P2, NGEST G, FORMATII F, NSUBUNIT S, NPERS A, NartObj Ob, ProdMan PM, NOper Op, Comanda1 C1, Comanda C,PRODCOMP PC';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  sAnLunaLucru    varchar := coalesce(getAnLunalucru()::varchar,'0');
BEGIN
  --Florin 28.12.2022 - coloane suplimentare
  --Adina 11.05.2021 - alstart, alstop, sAnLunaLucru
  --Adina 06.01.2021
  CALL PRC_AL_CHECK('tarifeman1', 0);

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'RAPORTPDET', 'PDET', 'PDET.CODRAPORTP = P.CODRAPORTP',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT  = OB.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT  = OB.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_RAPORTP.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert := 'INSERT INTO ' || coalesce(TMPNAME,'') || '(
        NAV_CodDoc, NAV_TipDoc, NrDoc, DataI, DataS, PeForm, Sectie, Form, Sub,
        Ang, Ord,
        Com, Art, Oper,
        Realizat, TNorma, TValoare, Rebut' || coalesce(gUserFields,'') || ')
      SELECT
        P.CodRaportP, 63, P.NrDoc, P.DataI, P.DataS, (case when P.Pe_Formatie=1 then ''Da'' else ''Nu'' end), G.Den_Gest, F.Den_Formatie, S.Den_Subunit,
        (case when P1.Angajat=0 then A.NUME else A.NUME||'' ''||A.PRENUME end) , ROW_NUMBER() OVER (PARTITION BY P2.CodRaportP1 ORDER BY P2.CODRAPORTP2 ASC),
        coalesce(C.PREFIXDOC,'''')||coalesce(C.NRDOC::varchar,'''')||''/''||to_char(C.DATADOC,''dd.mm.yyyy''), OB.DENUMIRE,
        coalesce(PM.NROP::varchar,'''')||''/''|| coalesce(OP.DENUMIRE,''''),
        P2.REALIZAT, PM.TU * P2.REALIZAT, T1.Tarif * PM.TU * P2.REALIZAT / 60, P2.REBUT ' || gUserAlias || '
      FROM RaportP P
        INNER JOIN RaportP0   P0 ON P0.CodRaportP  = P.CodRaportP
        INNER JOIN RaportP1   P1 ON P1.CodRaportP0 = P0.CodRaportP0
        INNER JOIN RaportP2   P2 ON P2.CodRaportP1 = P1.CodRaportP1
        INNER JOIN ProdMan    PM ON PM.CodMan      = P2.CodMan
        INNER JOIN Tarifeman1 T1 ON T1.CodTarif    = PM.CodTarif AND '||sAnLunaLucru||' BETWEEN T1.ALSTART and T1.ALSTOP
        INNER JOIN PRODCOMP   PC ON PM.CODPRODCOMP = PC.CODPRODCOMP
        LEFT  JOIN NGEST      G  ON G.CodGest      = P.Sectie
        LEFT  JOIN FORMATII   F  ON F.CodFormatie  = P.Formatie
        LEFT  JOIN NSUBUNIT   S  ON S.CodSubunit   = P.Subunitatea
        LEFT  JOIN NPERS      A  ON A.CodPers      = P1.Angajat
        LEFT  JOIN NOper      Op ON Op.CodOp       = PM.CodOp
        LEFT  JOIN Comanda1   C1 ON C1.CodComanda1 = P2.CodComanda1
        LEFT  JOIN NartObj    Ob ON Ob.CodObiect   = C1.CodObiect
        LEFT  JOIN Comanda    C  ON C.CodComanda   = C1.CodComanda' || gSuplJoins || '
      WHERE P.An*12 + p.Luna BETWEEN PKG_LIST_SELECTLUNAAN_LunaStart() AND PKG_LIST_SELECTLUNAAN_LunaStop() ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('P',NULL,NULL,NULL),'') || '
      UNION ALL
      SELECT
        P.CodRaportP, 63, P.NrDoc, P.DataI, P.DataS, (case when P.Pe_Formatie=1 then ''Da'' else ''Nu'' end), G.Den_Gest, F.Den_Formatie, S.Den_Subunit,
        (case when P1.Angajat=0 then  A.NUME else A.NUME||'' ''||A.PRENUME end), ROW_NUMBER() OVER (PARTITION BY P2.CodRaportP1 ORDER BY P2.CODRAPORTP2 ASC),
        coalesce(C.PREFIXDOC,'''')||coalesce(C.NRDOC::varchar,'''')||''/''||to_char(C.DATADOC,''dd.mm.yyyy''), OB.DENUMIRE,
        coalesce(PM.NROP::varchar,'''')||''/''|| coalesce(OP.DENUMIRE,''''),
        P2.REALIZAT, P2.TU * P2.REALIZAT, T1.Tarif * P2.TU * P2.REALIZAT / 60, P2.REBUT ' || gUserAlias || '
      FROM RaportP P
        INNER JOIN RaportP0   P0 ON P0.CodRaportP  = P.CodRaportP
        INNER JOIN RaportP1   P1 ON P1.CodRaportP0 = P0.CodRaportP0
        INNER JOIN RaportP2   P2 ON P2.CodRaportP1 = P1.CodRaportP1
        INNER JOIN Tarifeman1 T1 ON T1.CodTarif    = P2.CodTarif AND '||sAnLunaLucru||' BETWEEN T1.ALSTART and T1.ALSTOP
        LEFT  JOIN ProdMan    PM ON PM.CodMan      = P2.CodMan
        LEFT  JOIN PRODCOMP   PC ON PM.CODPRODCOMP = PC.CODPRODCOMP
        LEFT  JOIN NGEST      G  ON G.CodGest      = P.Sectie
        LEFT  JOIN FORMATII   F  ON F.CodFormatie  = P.Formatie
        LEFT  JOIN NSUBUNIT   S  ON S.CodSubunit   = P.Subunitatea
        LEFT  JOIN NPERS      A  ON A.CodPers      = P1.Angajat
        LEFT  JOIN NOper      Op ON Op.CodOp       = P2.CodOp
        LEFT  JOIN Comanda1   C1 ON C1.CodComanda1 = P2.CodComanda1
        LEFT  JOIN NartObj    Ob ON Ob.CodObiect   = c1.CodObiect
        LEFT  JOIN Comanda    C  ON C.CodComanda   = C1.CodComanda' || gSuplJoins || '
      WHERE coalesce(PM.CODMAN,0) = 0 AND P.An*12 + p.Luna BETWEEN PKG_LIST_SELECTLUNAAN_LunaStart() AND PKG_LIST_SELECTLUNAAN_LunaStop() ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('P',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_realgest_processlist</obj_name>
  <obj_hashval>88ce0e67f6905cedce7ff3b115372922</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest_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 := '';
  sInsertDC   varchar := '';
  sSelectDC   varchar := '';
  sJoinDC     varchar := '';
  i           numeric;
  sConditie   VARCHAR(1000);
  sIn         VARCHAR(20);
BEGIN
  --Florin 06.06.2024 - sinc. Oracle
  --Florin 10.05.2023 - fixat 57923
  --Florin 11.01.2023 - fixat 56763
  --Florin 29.12.2022 - sinc. Oracle
  --Florin 06.12.2022 - sinc. Oracle
  --Adina 17.02.2021 - tichet 43389
  --BogdanL 28.07.2020
  PERFORM pkg_list_base_realgest_ver_col_analiza(tmpName, COALESCE(current_setting('PKG_LIST_BASE_REALGEST.NiveleANod', true)::numeric, 0));

  gSuplCols := 'NGEST NG, NSUBUNIT NSUBUNIT, JURNAL J, NCONT CONTD, NCONT CONTC, CENTRECOST CC, NCLASEG CLSG, NCONTS CS, NCONTT CT, ANALIZANOD ANOD, ANALIZA ANALIZ, DESCRIPTORI1 ADESC1, DESCRIPTORI ADESC';

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

  sConditie := ' AND (contd.clasa = 6 OR contd.clasa = 7 OR contc.clasa = 6 OR contc.clasa = 7) ';
  sIn := '(6,7)';
  if current_setting('PKG_LIST_BASE_REALGEST.vExtra', TRUE)::NUMERIC = 1 THEN
    sConditie := ' AND (contd.clasa = 6 OR contd.clasa = 7 OR contc.clasa = 6 OR contc.clasa = 7 OR contd.clasa = 9 or contc.clasa = 9) ';
    sIn := '(6,7,9)';
  END IF;
  IF current_setting('PKG_LIST_BASE_REALGEST.vAllCC', true)::numeric = 1 THEN
    DELETE FROM tmp_manevra_liste where  filtru = 'CODCENTRU';
    INSERT INTO TMP_MANEVRA_LISTE(FILTRU, VALOARE)
    SELECT 'CODCENTRU', CODCENTRU FROM CENTRECOST WHERE COALESCE(INACTIV, 0) = 0;
  END IF;

  IF  COALESCE(current_setting('PKG_LIST_BASE_REALGEST.NiveleANod', true)::numeric, 0) &gt; 0 THEN
    sJoinDC := ' LEFT JOIN (
                SELECT CodAnalizaNod';

    FOR i IN 1..COALESCE(current_setting('PKG_LIST_BASE_REALGEST.NiveleANod', true)::numeric, 0) LOOP
      sInsertDC := sInsertDC||', NA'||to_char(i)||',COR'||to_char(i);
      sSelectDC := sSelectDC||', DC.NA'||to_char(i)||',DC.COR'||to_char(i);
      sJoinDC := sJoinDC ||',
                Max(CASE WHEN nivel = '||to_char(i)||' THEN valoare ELSE NULL end) NA'||to_char(i);
      sJoinDC   := sJoinDC ||',
                Max(CASE WHEN nivel = '||to_char(i)||' THEN (select wme_result from PKG_DESCRIPTORI_GetDenAsociat(null, TIP,CODASOCIAT)) ELSE NULL end) COR'||to_char(i);
    END LOOP;

    sJoinDC := coalesce(sJoinDC,'') || ' FROM TMP_TREE_ANALIZANOD
                      GROUP BY CodAnalizaNod
                    ) DC ON DC.CodAnalizaNod = j.CodAnalizaNod ';
  END IF;
  sInsert := 'INSERT INTO ' || tmpName || ' (
              NAV_CodDoc, NAV_CodDoc1, NAV_TipDoc,
              Doc, DataDoc,
              SimbCont,
              ValChelt,
              ValVenit,
              ValReal,
              CheltVal,
              VenitVal,
              RealVal,
              DenGest, DenAct, Obs, SimbCont_psec, NameCont_psec, An, Luna, CentruCost,
              DENCONT, TipAloc, TipChelt,
              ObsDoc,
              IFRS,IFRSV' || coalesce(sInsertDC,'') || gUserFields || ')
          SELECT
            CASE WHEN j.tipdoc = 35 AND PKG_GLOBALS_GET_DREPT_SALARIZARE() = 0 AND NC.JurnalTVA = 5 THEN 0 WHEN j.tipdoc = 36 THEN (SELECT MF1.CODNIRSTOC FROM MIFIX1 MF1 WHERE MF1.CODMIFIX = J.CODDOC AND MF1.ANSTART*12+MF1.LUNASTART=J.AN*12+J.LUNA) ELSE j.coddoc END,
            CASE WHEN j.tipdoc = 35 AND PKG_GLOBALS_GET_DREPT_SALARIZARE() = 0 AND NC.JurnalTVA = 5 THEN 0 WHEN j.tipdoc = 36 THEN (SELECT MF1.CODNIRSTOC FROM MIFIX1 MF1 WHERE MF1.CODMIFIX = J.CODDOC AND MF1.ANSTART*12+MF1.LUNASTART=J.AN*12+J.LUNA) WHEN j.TipDoc IN (29,30,31,33) THEN j.indexlocal ELSE 0 END,
            CASE WHEN j.tipdoc = 35 AND PKG_GLOBALS_GET_DREPT_SALARIZARE() = 0 AND NC.JurnalTVA = 5 THEN 0 ELSE j.tipdoc END,
            j.Document, j.DataDoc,
            CASE when contd.clasa in '||sIn||' then contd.simbol else contc.simbol END,
            CASE when contd.clasa in '||sIn||' then j.valoare else 0 END,
            CASE when contc.clasa in '||sIn||' then j.valoare else 0 END,
            CASE when contc.clasa in '||sIn||' then j.valoare else 0 END - CASE when contd.clasa in '||sIn||' then j.valoare else 0 END,
            CASE when contd.clasa in '||sIn||' then j.valoareV else 0 END as cheltval,
            CASE when contc.clasa in '||sIn||' then j.valoareV else 0 END as venitval,
            CASE when contc.clasa in '||sIn||' then j.valoareV else 0 END - CASE when contd.clasa in '||sIn||' then j.valoareV else 0 END as cheltval,
            NG.den_gest DenGest, ACT.Den_Activit, J.Obs, cs.simbol, cs.name, J.An, J.Luna, CC.Denumire,
            CASE WHEN contd.clasa IN '||sIn||' THEN contd.den_cont ELSE contc.den_cont END,
            CASE WHEN coalesce(CC.CodCentru,0) &lt;&gt; 0 THEN
              (Case  When coalesce(CC.TipAloc,0)=0 then ''Alocabil in calcul pret''
                  When coalesce(CC.TipAloc,0)=1 then ''Nealocabil in calcul pret''
                  When coalesce(CC.TipAloc,0)=2 then ''Fara inregistrari clasa 9'' end)
            END,
            CASE
                WHEN CC.TipChelt =  1 then ''Activitate de baza''
                WHEN CC.TipChelt =  2 then ''Cheltuieli indirecte - regie fixa''
                WHEN CC.TipChelt =  3 then ''Cheltuieli indirecte - regie variabila''
                WHEN CC.TipChelt = 11 then ''Cheltuieli auxiliare''
                WHEN CC.TipChelt = 12 then ''Cheltuieli generale de administratie''
                WHEN CC.TipChelt = 13 then ''Cheltuieli de desfacere''
                WHEN CC.TipChelt = 14 then ''Cheltuieli indirecte comune''
            END,' || coalesce(CASE  WHEN PKG_LIST_BASE_REALGEST_FaraMiscari() THEN
                'CASE WHEN j.TipDoc IN (29,30,31,33) then pkg_list_base_utils_getobsdoc(j.indexlocal, j.tipdoc)
                      ELSE pkg_list_base_utils_getobsdoc(j.coddoc, j.tipdoc)
                 END '
                   ELSE 'NULL '
                   END ::varchar ,'') ||
          ' ObsDoc,
          CASE WHEN contd.clasa in '||sIn||' THEN 1 ELSE -1 END * coalesce(j.valoare_ifrs,0), CASE WHEN contd.clasa in '||sIn||' THEN 1 ELSE -1 END * coalesce(j.valoarev_ifrs,0)'
          || coalesce(sSelectDC,'') || gUserAlias || '
        FROM JURNAL J
          INNER JOIN NCONT        CONTC   ON j.contc                = contc.codcont
          INNER JOIN NCONT        CONTD   ON j.contd                = contd.codcont
          LEFT  JOIN NC                   ON NC.CODNC               = J.CODDOC AND J.TIPDOC = 35
          LEFT  JOIN NGEST        NG      ON coalesce(j.gest, 0)    = ng.codgest
          LEFT  JOIN NACTIVIT     ACT     ON ng.codactivit          = act.codactivit
          LEFT  JOIN CENTRECOST   CC      ON j.codcentru            = cc.codcentru
          LEFT  JOIN NSUBUNIT             ON j.subunitatea          = nsubunit.codsubunit
          LEFT  JOIN NCLASEG      CLSG    ON NG.codclasa            = clsg.codclaseg
          LEFT  JOIN NCONTS CS ON cs.codconts = pkg_list_base_utils_get_codconts(CASE when contd.clasa in '||sIn||' then contd.codcont else contc.codcont END, j.an, j.luna)
          LEFT  JOIN NCONTT CT ON ct.codcontt = (select wme_result from pkg_list_base_utils_get_codcontt(null, CASE when contd.clasa in '||sIn||' then contd.codcont else contc.codcont END, j.an, j.luna))
          LEFT  JOIN ANALIZANOD   ANOD    ON anod.codanalizanod     = j.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
          LEFT  JOIN ANALIZANOD   ANODP   ON anodp.codanalizanod    = anod.nodparinte
          LEFT  JOIN ANALIZA      ANALIZP ON analizp.codanaliza     = anodp.codanaliza
          LEFT  JOIN DESCRIPTORI1 ADESC1P ON adesc1p.coddescriptor1 = anodp.coddescriptor1
          LEFT  JOIN DESCRIPTORI  ADESCP  ON adescp.coddescriptor   = adesc1p.coddescriptor' || coalesce(sJoinDC,'') || gSuplJoins || '
         WHERE J.AN*12 + J.LUNA BETWEEN '
            || coalesce(current_setting('PKG_LIST_BASE_REALGEST.AnLunaIni', true),'') ||
            ' AND ' || coalesce(current_setting('PKG_LIST_BASE_REALGEST.AnLunaFin', true),'') || sConditie || '
         AND (J.TipDoc &lt;&gt; 32 OR (J.TipDoc = 32 AND J.CodDoc = 1))';
  IF  current_setting('PKG_LIST_BASE_REALGEST.vAllCC', true)::numeric &lt;&gt; 1 THEN
      sInsert := coalesce(sInsert,'') || ' and
      EXISTS (SELECT T.VALOARE FROM TMP_MANEVRA_LISTE T WHERE CC.CODCENTRU = T.VALOARE::numeric AND T.FILTRU = ''CODCENTRU'') ';
  END IF;

  sInsert := coalesce(sInsert,'')
        || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT
                     FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,
                                    'J',
                                    null,
                                    null,
                                    current_setting('PKG_LIST_BASE_REALGEST.Subunit', true)::numeric )),'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_realgest3_setjoinuri</obj_name>
  <obj_hashval>496c644c115a5a0863fb41e490bb1af2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_realgest3_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --BogdanL 28.07.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_REALGEST3.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regcasabanca_processlist_faratuning</obj_name>
  <obj_hashval>de2ab8eb1e0a130076f4c3e7673c476c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regcasabanca_processlist_faratuning(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert      varchar;
  sSelect      varchar;
  sSelReg      varchar;
  sDocument    varchar;
  sCursRef     varchar := '1 curs_ref';
  vCodMOneda   NUMERIC;
  dataIni      date := fnc_current_setting_date('PKG_LIST_CASABANKA.p_DataIni');
  dataFin      date := fnc_current_setting_date('PKG_LIST_CASABANKA.p_DataFin');
  sdataIni     varchar := 'To_DATE(''' || To_Char(dataIni, 'dd.mm.yyyy') || ''',''dd.mm.yyyy'')';
  sdataIniSP   varchar := 'To_DATE(''' || To_Char(dataIni + 1,'dd.mm.yyyy') || ''',''dd.mm.yyyy'')';
  sdataFin     varchar := 'To_DATE(''' || To_Char(dataFin, 'dd.mm.yyyy') || ''',''dd.mm.yyyy'')';
  vTipDoc      varchar := current_setting('PKG_LIST_CASABANKA.p_tipDoc', true);
  vAnIni       numeric := To_Char(dataIni, 'yyyy')::numeric;
  vLunaIni     numeric := To_Char(dataIni, 'mm')::numeric;
  vAnLunaIni   numeric := vAnIni * 12 + vLunaIni;
  vAnFin       numeric := To_Char(dataFin, 'yyyy')::numeric;
  vLunaFin     numeric := To_Char(dataFin, 'mm')::numeric;
  vAnLunaFin   numeric := vAnFin * 12 + vLunaFin;
  vAmReg       NUMERIC;
  vAnLunaLucru numeric := getanlunalucru();
  aSitV        numeric;
  aBancaV      numeric;
  aMonedaV     numeric;
  sColSold     varchar := 'soldlei';
  sIniOrd      varchar := CASE WHEN Extract(DAY FROM dataIni) = 1 THEN '1' ELSE '0' END ;
  vDenSubunit  varchar;
  vCount       numeric;
  vValI        numeric;
  vValP        numeric;
  vSold_Col    numeric;
  vSoldLei_Col numeric;
  gSuplCols    varchar := 'tmp_lst_rb rb, nbankcont nbc, nbank nb, npers ag, ncont nc, ncont1 nc1, nconts cs, npart part, npers pers, ngest ng';
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplJoins   VARCHAR := '';
BEGIN
  --Florin 01.10.2025 - sinc. Oracle
  --Florin 06.08.2020
  --Florin 20.08.2020 - adaugat filtrare pe subunitate
  --Florin 25.08.2020 - fixat tichete
  --Florin 19.11.2020 - sters PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG cu 3 parametri
  --Adina 24.11.2020 tichet 41227
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET', 'PD', 'PD.CODPART = PART.CODPART', NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPERS', 'OPER', 'OPER.LOGONNAME = RB.USERID', 1);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('PKG_LIST_BASE_regcasabanca.gSuplCols', gSuplCols, false);

  IF (SELECT pkg_list_base_utils_GetInfoSitValuta.WME_RESULT FROM pkg_list_base_utils_GetInfoSitValuta(NULL,aSitV, aBancaV, aMonedaV))
  THEN
    sCursRef := 'PKG_LIST_BASE_UTILS.GETCURSREFERINTA(' || coalesce(aMonedaV, 0) || ',' || coalesce(aBancaV, 0) || ', rb.datadoc ) curs_ref ';
  END IF;

  SELECT DISTINCT nbc.codmoneda
  INTO vCodMoneda
  FROM TMP_MANEVRA_LISTE tmp
  INNER JOIN nbankcont nbc ON  tmp.VALOARE = nbc.codbankcont::varchar
  WHERE
     FILTRU = 'CODBANKCONT';

  IF vCodMoneda &lt;&gt; 0 THEN
    SELECT Count(1)
    INTO vAmReg
    FROM reg
    WHERE
      tipreg = 45 AND (an * 12 + luna)  BETWEEN vAnLunaIni AND vAnLunaFin AND datadoc BETWEEN dataini AND datafin AND codmoneda = vCodMoneda;
    sColSold := 'soldvaluta';
  END IF;

  IF  vAmReg &gt; 0 THEN
    sSelReg := '
      UNION ALL
      SELECT
        r.codreg coddoc, NULL coddoc1, r.tipreg tipdoc, r.datadoc datareg, NULL doccumul, NULL prefixdoc, NULL seriedoc, NULL nri, r.nrdoc, r.datadoc, NULL AGENT,
        ''Regularizare valuta'' explicatii, NULL den_part, 0 cont, NULL obs,
        -1 tiptranz, 0 val, 0 valdoc, r.curs, x.CodBankCont codbanca, 0 sold_col,
        CASE bc.credit WHEN 1 THEN -1 ELSE 1 END * ((x.SoldValuta * r.Curs - x.SoldLei) - Coalesce( lag (x.SoldValuta * r.Curs - x.SoldLei,1) OVER (PARTITION BY X.CODBANKCONT ORDER BY r.datadoc),0)) soldlei_col,
        9 ordine, bc.subunitatea, 0 idxloc, r.an * 12 + r.luna anluna, NULL codpart, NULL codpers, NULL codgest, NULL userid
      FROM
        ( SELECT CODBANKCONT, CODREG, SUM(SOLDLEI) SOLDLEI, SUM(SOLDVALUTA) SOLDVALUTA
          FROM (
            SELECT T.CODBANCA CODBANKCONT, R.CODREG,
              SUM((CASE t1.tiptranz WHEN 1 THEN 1 ELSE -1 END * T1.VALDOC - Coalesce(T1.COMISION,0)) * T1.CURS * CASE bc.credit WHEN 1 THEN -1 ELSE 1 END) SOLDLEI,
              SUM((CASE t1.tiptranz WHEN 1 THEN 1 ELSE -1 END * T1.VALDOC - Coalesce(T1.COMISION,0)) * CASE bc.credit WHEN 1 THEN -1 ELSE 1 END) SOLDVALUTA
            FROM  TREZOR T
              INNER JOIN trezor1   t1 ON t1.codtrezor   = t.codtrezor
              INNER JOIN nbankcont bc ON bc.codbankcont = t.codbanca
              INNER JOIN reg       r  ON r.codmoneda    = bc.codmoneda
            WHERE R.TipReg = 45
              AND r.datadoc BETWEEN ' || coalesce(sdataini, '') || ' AND ' || coalesce(sdatafin, '') || '
              AND r.an * 12 + r.luna between ' || coalesce(vAnLunaIni, 0) || ' AND ' || coalesce(vAnLunaFin, 0) || '
              AND t.tipdoc = ' || coalesce(vTipDoc,'') || ' AND t.operat = 1 AND Coalesce(t1.anulat, 0) = 0
              AND t.an * 12 + t.luna &gt;= ' || coalesce(vAnLunaIni, 0) || '
              AND t.an * 12 + t.luna &lt;= r.an * 12 + r.luna
              AND t.datadoc &lt;= r.datadoc
              AND Coalesce(t1.tiptranz,-1) IN (0,1)
              AND bc.codmoneda &lt;&gt; 0
              AND t.codbanca::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'')
            GROUP BY T.CODBANCA, R.CODREG
            UNION ALL
            SELECT BCS.CODBANKCONT, R.CODREG, Coalesce(bcs.SOLDLEI,0) SOLDLEI,  Coalesce(bcs.SOLDVALUTA,0) SOLDVALUTA
            FROM NBANKSOLDLUNA BCS
              INNER JOIN nbankcont bc ON bc.codbankcont = bcs.codbankcont
              INNER JOIN reg       r  ON r.codmoneda    = bc.codmoneda
            WHERE bc.codmoneda &lt;&gt; 0
              AND R.TipReg = 45
              AND r.datadoc BETWEEN ' || coalesce(sdataini, '') || ' AND ' || coalesce(sdatafin, '') || '
              AND r.an * 12 + r.luna between ' || coalesce(vAnLunaIni, 0) || ' AND ' || coalesce(vAnLunaFin, 0) || '
              AND bcs.an * 12 + bcs.luna = ' || coalesce((vAnLunaIni - 1)::varchar,'') || '
              AND bcs.codbankcont::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'')
          ) a_pg
          GROUP BY CODBANKCONT, CODREG
        ) X
        INNER JOIN REG R ON R.CODREG = X.CODREG
        INNER JOIN NBANKCONT BC ON BC.CODBANKCONT = X.CODBANKCONT
      WHERE SOLDLEI &lt;&gt; SOLDVALUTA * R.CURS';
  END IF;
  sInsert := 'INSERT INTO ' || tmpName || '(
      NAV_CodDoc, NAV_CodDoc1, NAV_TipDoc, DATAREG, DOCCUMUL, PREFIXDOC, SERIEDOC, NRI, NRDOC, DATADOC, AGENT,
      EXPLICATII, DEN_PART, SEMNIFICATIE, CONTSEC, OBS,
      INCASARE, PLATA,
      VALDOC, VALDOCLEI, SOLD_COL, SOLDLEI_COL,
      ORDINE, IDXLOC, SIMB_BANCA, DEN_CONT, NRCONT, SUBUNITATEA, CONTREPR, TIPTRANZ,
      CURS, CURS_REF' || gUserFields || ') ';
  sDocument := '
                 CASE
                   WHEN o.semnificatie IN (310,410) THEN ''in avans ''
                   WHEN int.codintr IS NOT NULL THEN int.prefixdoc|| ''/''||int.nrdoc||''/''|| To_char(int.datadoc,''dd.mm.yyyy'')
                   WHEN ies.codies  IS NOT NULL THEN ies.prefixdoc|| ''/''||ies.nrdoc||''/''|| To_char(ies.datadoc,''dd.mm.yyyy'')
                 END ';
  sSelect := '
    WITH
      NBC1 AS (
        SELECT CODBANKCONT, CODIOBANCA, (ANSTART * 12 + LUNASTART) ANLUNASTART,
          Coalesce(LEAD(ANSTART*12+LUNASTART) OVER (PARTITION BY CODBANKCONT ORDER BY ANSTART, LUNASTART) - 1,36000) ANLUNASTOP
        FROM NBANKCONT1 WHERE (ANSTART * 12 + LUNASTART) &lt;= ' || coalesce(vAnLunaFin, 0) || '),
      IOB1 AS (
        SELECT CODIOBANK, CONT, COMISION, (ANSTART * 12 + LUNASTART) ANLUNASTART,
          Coalesce(LEAD(ANSTART*12+LUNASTART) OVER (PARTITION BY CODIOBANK ORDER BY ANSTART, LUNASTART) - 1,36000) ANLUNASTOP
        FROM IOBANK1 WHERE (ANSTART * 12 + LUNASTART) &lt;= ' || coalesce(vAnLunaFin, 0) || '),
      NC1 AS (
        SELECT C1.*, (ANSTART * 12 + LUNASTART) ANLUNASTART,
          Coalesce(LEAD(ANSTART*12+LUNASTART) OVER (PARTITION BY CODCONT ORDER BY ANSTART, LUNASTART) - 1,36000) ANLUNASTOP
        FROM NCONT1 C1 WHERE (ANSTART * 12 + LUNASTART) &lt;= ' || coalesce(vAnLunaFin, 0) || '),
      CC AS (
        SELECT
          LAST_VALUE(T1.CODCONTDED)  OVER (ORDER BY T1.ANSTART, T1.LUNASTART range between unbounded preceding and unbounded following) as CODCONTDED,
          LAST_VALUE(T1.CODCONTCOLE) OVER (ORDER BY T1.ANSTART, T1.LUNASTART range between unbounded preceding and unbounded following) as CODCONTCOLE,
          C.ANLUNASTART, C.ANLUNASTOP, T1.CODTVA
        FROM (
          SELECT CV.VALOARE, (CL.ANSTART * 12 + CL.LUNASTART) ANLUNASTART, Coalesce(LEAD(CL.ANSTART * 12 + CL.LUNASTART) OVER (PARTITION BY C1.SIMBOL ORDER BY CL.ANSTART, CL.LUNASTART) - 1,36000) ANLUNASTOP
          FROM CONST1 C1
            LEFT JOIN CATEGCONST CT ON CT.CODCATEG = C1.CODCATEG
            LEFT JOIN CONSTLUNA CL on CL.codconst1 = C1.codConst1
            LEFT JOIN CONSTVAL  CV on cv.codconstluna = cL.codconstluna
          WHERE Upper(C1.simbol) = Upper(''TIPTVAImplicit'')
        ) C INNER JOIN NTVA1 T1 ON T1.CODTVA::varchar = C.VALOARE AND (T1.ANSTART * 12 + T1.LUNASTART) &lt;= (C.ANLUNASTART)
      ),
      RB AS (
        SELECT coddoc, coddoc1, tipdoc, datareg, doccumul, prefixdoc, seriedoc, nri, nrdoc, datadoc, agent, explicatii, den_part, cont, obs,
               tiptranz, val, valdoc, curs, codbanca, sold_col, soldlei_col, 2 ordine, subunitatea, idxloc, anluna, codpart, codpers, codgest, userid
        FROM (
          SELECT
            coddoc, coddoc1, tipdoc, datareg, doccumul, prefixdoc, seriedoc, nri, nrdoc, datadoc, agent, obs,
            CASE
              WHEN tiptranz = 0 AND obiecttranz = 0 THEN ''Plata furnizor ''
              WHEN tiptranz = 0 AND obiecttranz = 1 THEN ''Plata retur ''
              WHEN tiptranz = 0 AND obiecttranz = 2 THEN ''Plata angajat ''
              WHEN tiptranz = 0 AND obiecttranz = 3 THEN ''Plata viramente interne ''
              WHEN tiptranz = 0 AND obiecttranz = 4 THEN ''Plata direct pe cheltuieli ''
              WHEN tiptranz = 0 AND obiecttranz = 5 THEN ''Plata datorii / taxe / impozite ''
              WHEN tiptranz = 1 AND obiecttranz = 0 THEN ''Incasare client ''
              WHEN tiptranz = 1 AND obiecttranz = 1 THEN ''Incasare retur ''
              WHEN tiptranz = 1 AND obiecttranz = 2 THEN ''Incasare angajat ''
              WHEN tiptranz = 1 AND obiecttranz = 3 THEN ''Incasare viramente interne ''
              WHEN tiptranz = 1 AND obiecttranz = 4 THEN ''Incasare direct pe venituri ''
              WHEN tiptranz = 1 AND obiecttranz = 5 THEN ''Incasare imprumuturi / subventii ''
              WHEN tiptranz = 1 AND obiecttranz = 6 THEN ''Incasare dobanda ''
              WHEN tiptranz = 2                     THEN ''Plata SPLIT TVA ''
            END || coalesce(den_part, '''')|| '' '' || coalesce(string_agg(DISTINCT DOC, ''''), '''') explicatii,
            Coalesce(cont,0) cont, tiptranz, sum(val) val, Coalesce(valdoc,0) valdoc, den_part, codbanca, curs,
            sum(sold_col) sold_col, sum(soldlei_col) soldlei_col, subunitatea, idxloc, anluna, codpart, codpers, codgest, userid
          FROM (
            SELECT
              t.codtrezor coddoc, t1.codtrezor1 coddoc1, t.tipdoc, t.datadoc datareg, t.numedoc doccumul, t1.doc prefixdoc, t1.seriedoc, t1.nri, t1.nrdoc, t1.datadoc, Coalesce(NullIF(t1.agent,0),t.agent) agent, t1.obs, t1.obiecttranz,
              CAST(' || coalesce(sDocument,'') || ' AS VARCHAR(100)) doc, nc.codcont cont, CASE WHEN t1.platatva = 1 THEN 2 ELSE t1.tiptranz END tiptranz,
              CASE
                -- cica in cazul t1.obiecttranz = 3 am o singura obligatie asociata, nu are TVA si am gasit bube date de diferente de curs
                -- stef 05.03.2014 am gasit si mai multe linii din preluare pt cazul de mai sus si atunci imi bag picioarele ca iese nasol suma
                WHEN t1.obiecttranz = 3 AND COUNT(1) OVER (PARTITION BY t1.codtrezor1) = 1 THEN t1.valdoc
                WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.dincaretva,0)
                ELSE (Coalesce(o.valoare,0) - Coalesce(g.tva,0)) * CASE WHEN g.moneda = ' || coalesce(vCodMoneda, 0) || ' THEN 1 ELSE Coalesce(NullIF(g.curs,0),1) / Coalesce(NullIF(t1.curs,0),1) END
              END val,
              t1.valdoc, CASE t1.obiecttranz WHEN 3 THEN nb.denumire||'' ''||nbc.nrcont WHEN 2 THEN pers.nume||'' ''||pers.prenume WHEN 1 THEN part.den_part WHEN 0 THEN part.den_part ELSE nc.simbol END den_part,
              t.codbanca, Coalesce(NullIF(t1.curs,0),1) curs,
              CASE
                WHEN t1.obiecttranz = 3 AND COUNT(1) OVER (PARTITION BY t1.codtrezor1) = 1 THEN t1.valdoc
                WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.dincaretva,0)
                ELSE (Coalesce(o.valoare,0) - Coalesce(g.tva,0)) * CASE WHEN g.moneda = ' || coalesce(vCodMoneda , 0) || ' THEN 1 ELSE Coalesce(NullIF(g.curs,0),1) / Coalesce(NullIF(t1.curs,0),1) END
              END * CASE t1.tiptranz WHEN 1 THEN 1 ELSE -1 END sold_col,
              CASE
                WHEN t1.obiecttranz = 3 AND COUNT(1) OVER (PARTITION BY t1.codtrezor1) = 1 THEN t1.valdoc * Coalesce(NullIF(t1.curs,0),1)
                WHEN Coalesce(t1.platatva,0) = 1 THEN Coalesce(o.dincaretva,0)
                ELSE (Coalesce(o.valoare,0) - Coalesce(g.tva,0)) * CASE WHEN g.moneda = ' || coalesce(vCodMoneda, 0) || ' THEN Coalesce(NullIF(t1.curs,0),1) ELSE Coalesce(NullIF(g.curs,0),1) END
              END * CASE t1.tiptranz WHEN 1 THEN 1 ELSE -1 END soldlei_col,
              t.subunitatea, t1.indexlocal * 10 + 1 idxloc, t.an*12+t.luna anluna, part.codpart, pers.codpers, o.codgest, t.userid
            FROM trezor t
              LEFT JOIN trezor1 t1 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 npart part ON part.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 nbc ON nbc.codbankcont = t1.codpart AND t1.obiecttranz = 3
              LEFT JOIN nbank nb ON nb.codbank = nbc.codbank
              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 intrari int on int.codintr = gs.coddoc and int.tipdoc = gs.tipdoc
              LEFT JOIN iesiri ies on ies.codies = gs.coddoc and ies.tipdoc = gs.tipdoc
              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 ncont nc ON nc.codcont =
                CASE
                  WHEN o.semnificatie IN (300,320) AND Coalesce(os.semnificatie, 0) = 500 THEN (SELECT PKG_TREZOR_CODCONTCEC.wme_result FROM PKG_TREZOR_CODCONTCEC(NULL, TS.CodBanca, OS.Semnificatie, TS1.Tipdecont, T.an, T.luna))
                  WHEN o.semnificatie IN (400,420) AND Coalesce(os.semnificatie, 0) = 600 THEN (SELECT PKG_TREZOR_CODCONTCEC.wme_result FROM PKG_TREZOR_CODCONTCEC(NULL, TS.CodBanca, OS.Semnificatie, TS1.Tipdecont, 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 (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, o.semnificatie, o.icont, PKG_CONTURIBANCI_GET_BANKCONT_COD_CARACT_LUNA(t.codbanca,t.an,t.luna)))
                  WHEN o.semnificatie IN (1100,1101) THEN (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, o.semnificatie, o.icont, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(t1.codpart,t.an,t.luna)))
                  ELSE (SELECT WME_RESULT FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, o.semnificatie, o.icont, PKG_NOMPART_GET_PART_COD_CARACT_LUNA(t1.codpart,t.an,t.luna)))
                END
            WHERE t.tipdoc = ' || coalesce(vTipDoc,'') || ' AND t.operat = 1 AND Coalesce(t1.anulat, 0) = 0
              AND t.an * 12 + t.luna  between ' || coalesce(vAnLunaIni, 0) || ' AND ' || coalesce(vAnLunaFin, 0) || '
              AND t.datadoc BETWEEN ' || coalesce(sdataini, '') || ' AND ' || coalesce(sdatafin, '') || '
              AND Coalesce(t1.tiptranz,-1) IN (0,1)
              AND t.codbanca::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'')
            ) a_pg
          GROUP BY
            coddoc, coddoc1, tipdoc, datareg, prefixdoc, seriedoc, nri, nrdoc, datadoc, agent, obs, Coalesce(cont,0), tiptranz, obiecttranz, valdoc, den_part, codbanca, curs, subunitatea, idxloc, anluna, doccumul,
            codpart, codpers, codgest, userid
          UNION ALL
          SELECT
            coddoc, coddoc1, tipdoc, datareg, doccumul, prefixdoc, seriedoc, nri, nrdoc, datadoc, agent, obs,
            CASE
              WHEN tiptranz = 0 AND obiecttranz = 0 THEN ''Plata(TVA) furnizor ''
              WHEN tiptranz = 0 AND obiecttranz = 1 THEN ''Plata(TVA) retur ''
              WHEN tiptranz = 0 AND obiecttranz = 2 THEN ''Plata(TVA) angajat ''
              WHEN tiptranz = 0 AND obiecttranz = 3 THEN ''Plata(TVA) viramente interne ''
              WHEN tiptranz = 0 AND obiecttranz = 4 THEN ''Plata(TVA) direct pe cheltuieli ''
              WHEN tiptranz = 0 AND obiecttranz = 5 THEN ''Plata(TVA) datorii / taxe / impozite ''
              WHEN tiptranz = 1 AND obiecttranz = 0 THEN ''Incasare(TVA) client ''
              WHEN tiptranz = 1 AND obiecttranz = 1 THEN ''Incasare(TVA) retur ''
              WHEN tiptranz = 1 AND obiecttranz = 2 THEN ''Incasare(TVA) angajat ''
              WHEN tiptranz = 1 AND obiecttranz = 3 THEN ''Incasare(TVA) viramente interne ''
              WHEN tiptranz = 1 AND obiecttranz = 4 THEN ''Incasare(TVA) direct pe venituri ''
              WHEN tiptranz = 1 AND obiecttranz = 5 THEN ''Incasare(TVA) imprumuturi / subventii ''
              WHEN tiptranz = 1 AND obiecttranz = 6 THEN ''Incasare(TVA) dobanda ''
            END || coalesce(den_part, '''') || '' '' || coalesce(string_agg(DISTINCT DOC, ''''), '''') explicatii,
            Coalesce(cont, 0) cont, tiptranz, sum(val) val , Coalesce(valdoc,0) valdoc, den_part, codbanca, curs,
            sum(sold_col) sold_col, sum(soldlei_col) soldlei_col, subunitatea, idxloc, anluna, codpart, codpers, codgest, userid
          FROM (
            SELECT
              t.codtrezor coddoc, t1.codtrezor1 coddoc1, t.tipdoc, t.datadoc datareg, t.numedoc doccumul, t1.doc prefixdoc, t1.seriedoc, t1.nri, t1.nrdoc, t1.datadoc, Coalesce(NullIF(t1.agent,0),t.agent) agent, t1.obs, t1.obiecttranz,
              CAST(' || coalesce(sDocument,'') || ' AS VARCHAR(100)) doc, nc.codcont cont, t1.tiptranz,
              g.tva * CASE WHEN g.moneda = ' || coalesce(vCodMoneda , 0) || ' THEN 1 ELSE Coalesce(NullIF(g.curs,0),1) / Coalesce(NullIF(t1.curs,0),1) END val,
              t1.valdoc, CASE t1.obiecttranz WHEN 3 THEN nb.denumire||'' ''||nbc.nrcont WHEN 2 THEN pers.nume||'' ''||pers.prenume WHEN 1 THEN part.den_part WHEN 0 THEN part.den_part ELSE nc.simbol END den_part,
              t.codbanca, Coalesce(NullIF(t1.curs,0),1) curs,
              CASE t1.tiptranz WHEN 1 THEN 1 ELSE -1 END * g.tva * CASE WHEN g.moneda = ' || coalesce(vCodMoneda, 0) || ' THEN 1 ELSE Coalesce(NullIF(g.curs,0),1) / Coalesce(NullIF(t1.curs,0),1) END sold_col,
              CASE t1.tiptranz WHEN 1 THEN 1 ELSE -1 END * g.tva * CASE WHEN g.moneda = ' || coalesce(vCodMoneda, 0) || ' THEN Coalesce(NullIF(t1.curs,0),1) ELSE Coalesce(NullIF(g.curs,0),1) END soldlei_col,
              t.subunitatea, t1.indexlocal * 10 + 2 idxloc, t.an*12+t.luna anluna, part.codpart, pers.codpers, o.codgest, t.userid
            FROM trezor t
              LEFT JOIN trezor1 t1 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 npart part ON part.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 nbc ON nbc.codbankcont = t1.codpart AND t1.obiecttranz = 3
              LEFT JOIN nbank nb ON nb.codbank = nbc.codbank
              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 intrari int on int.codintr = gs.coddoc and int.tipdoc = gs.tipdoc
              LEFT JOIN iesiri ies on ies.codies = gs.coddoc and ies.tipdoc = gs.tipdoc
              LEFT JOIN cc ON (t.an * 12 + t.luna) between cc.anlunastart AND cc.anlunastop
              LEFT JOIN ncont nc ON nc.codcont = CASE WHEN t1.tiptranz = 0 AND t1.obiecttranz =1 THEN cc.codcontcole WHEN t1.tiptranz = 0 OR t1.obiecttranz =1 THEN cc.codcontded ELSE cc.codcontcole END
            WHERE t.tipdoc = ' || coalesce(vTipDoc, '') || ' AND t.operat = 1 AND Coalesce(t1.anulat, 0) = 0
              AND (t.an * 12 + t.luna)  between ' || coalesce(vAnLunaIni, 0) || ' AND ' || coalesce(vAnLunaFin, 0) || '
              AND t.datadoc BETWEEN ' || coalesce(sdataini, '') || ' AND ' || coalesce(sdatafin, '') || '
              AND Coalesce(t1.tiptranz,-1) IN (0,1)
              AND (Coalesce (g.tva, 0) &lt;&gt; 0)
              AND t.codbanca::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'')
            ) b_pg
          GROUP BY
            coddoc, coddoc1, tipdoc, datareg, prefixdoc, seriedoc, nri, nrdoc, datadoc, agent, obs, Coalesce(cont,0), tiptranz, obiecttranz, valdoc, den_part, codbanca, curs, subunitatea, idxloc, anluna, doccumul,
            codpart, codpers, codgest, userid';
  IF  vTipDoc::numeric = 30 THEN
    sSelect := coalesce(sSelect,'') || '
          UNION ALL
          SELECT
            t.codtrezor coddoc, t1.codtrezor1 coddoc1, t.tipdoc, t.datadoc datareg, t.numedoc doccumul, t1.doc prefixdoc, t1.seriedoc, t1.nri, t1.nrdoc, t1.datadoc, t.agent, t1.obs,
            ''Comision Bancar '' explicatii, iob1.comision cont,
            0 tiptranz, t1.comision val, 0 valdoc, Coalesce(part.den_part,pers.nume|| '' '' || pers.prenume) den_part, t.codbanca, Coalesce(NullIF(t1.curs,0),1) curs,
            - t1.comision sold_col, - t1.comision * Coalesce(NullIF(t1.curs,0),1) soldlei_col,
            t.subunitatea, t1.indexlocal * 10 + 3 idxloc, t.an*12+t.luna anluna, part.codpart, pers.codpers, NULL codgest, NULL userid
          FROM trezor t
            LEFT JOIN trezor1 t1 ON t.codtrezor = t1.codtrezor
            LEFT JOIN npart part ON part.codpart = t1.codpart AND t1.obiecttranz IN (0,1)
            LEFT JOIN npers pers ON pers.codpers = t1.codpart AND t1.obiecttranz = 2
            LEFT JOIN nbc1 ON nbc1.codbankcont = t.codbanca AND nbc1.anlunastart &lt;= t.an * 12 + t.luna AND nbc1.anlunastop &gt;= t.an * 12 + t.luna
            LEFT JOIN iob1 ON iob1.codiobank = nbc1.codiobanca AND iob1.anlunastart &lt;= t.an * 12 + t.luna AND iob1.anlunastop &gt;= t.an * 12 + t.luna
          WHERE t.tipdoc = ' || coalesce(vTipDoc,'') || ' AND t.operat = 1 AND Coalesce(t1.anulat, 0) = 0
            AND t.an * 12 + t.luna between ' || coalesce(vAnLunaIni, 0) || ' AND ' || coalesce(vAnLunaFin, 0) || '
            AND Coalesce(t1.tiptranz,-1) IN (0,1)
            AND Coalesce(t1.comision,0) &lt;&gt; 0
            AND t.datadoc BETWEEN ' || coalesce(sdataini, '') || ' AND ' || coalesce(sdatafin, '') || '
            AND t.codbanca::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'') ';
  END IF;
  sSelect := coalesce(sSelect,'') || '
          ) c_pg';
  IF vTipDoc::numeric = 29 THEN
    sSelect := coalesce(sSelect,'') || '
        UNION ALL
        SELECT
          i.codies coddoc, NULL coddoc1, i.tipdoc, i.datadoc datareg, Coalesce(i.prefixdoc,''M'') doccumul, i.prefixdoc, i.seriadoc seriedoc, i.nri, i.nrdoc, i.datadoc, i.agent,
          ''Incasare Monetar '' explicatii, null den_part, x.cont, i.obs,
          1 tiptranz,
          Round(CASE WHEN i.tvadoc = 0 OR i.valdoc = 0 THEN SUM(mp.valoare) ELSE SUM(mp.valoare) * (i.valdoc - i.tvadoc) / i.valdoc END * x.coef,7) val,
          i.valdoc, Coalesce(NullIF(i.curs,0),1) curs, mp.codbankcont codbanca,
          Round(CASE WHEN i.tvadoc = 0 OR i.valdoc = 0 THEN SUM(mp.valoare) ELSE SUM(mp.valoare) * (i.valdoc - i.tvadoc) / i.valdoc END * x.coef,7) sold_col,
          Round(CASE WHEN i.tvadoc = 0 OR i.valdoc = 0 THEN SUM(mp.valoare) ELSE SUM(mp.valoare) * (i.valdoc - i.tvadoc) / i.valdoc END * x.coef * Coalesce(NullIF(i.curs,0),1),7) soldlei_col,
          2 ORDINE, i.subunitatea, i.codies * 10 idxloc, i.an*12+i.luna anluna, NULL codpart, NULL codpers, NULL codgest, i.userid
        FROM (
          SELECT
            i.codies, Coalesce(ioa1.venituri,i1.contserv,0) cont,
            Sum (
              CASE
                WHEN coalesce(i1.tva, 0) = 0 THEN Coalesce(l1.cant, i1.cant) * i1.pu
                WHEN l1.codlivr1 IS NULL THEN (i1.pu * i1.cant - coalesce(i1.tva, 0))
                WHEN i1.pu * i1.cant = 0 THEN 0
                ELSE (i1.pu * i1.cant - coalesce(i1.tva, 0)) * l1.cant / i1.cant
              END) / (i.valdoc - i.tvadoc - Coalesce(i.valdiscount,0) + Coalesce(i.tvadiscount,0)) coef
          FROM iesiri i
            LEFT JOIN iesiri1 i1 ON i1.codies = i.codies AND (i.valdoc - i.tvadoc &lt;&gt; 0) AND (i1.pu * i1.cant - coalesce(i1.tva, 0) &lt;&gt; 0)
            LEFT JOIN livr l ON l.codies = i.codies
            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 (
              SELECT CODIOART, MAX(VENITURI) VENITURI
              FROM(
                SELECT io1.CODIOART, io1.VENITURI,
                  DENSE_RANK() OVER (PARTITION BY io1.CODIOART order by ANSTART desc, LUNASTART desc) io2
                FROM IOART1 io1
                WHERE (ANSTART * 12 + LUNASTART) &lt;= ' || coalesce(vAnLunaLucru, 0) || ') io3 WHERE io3.io2 = 1
              GROUP BY CODIOART
            ) ioa1 ON ioa1.codioart = CASE WHEN COALESCE(l1.contintermed, 0) &lt;&gt; 0 THEN l1.contintermed ELSE COALESCE(ns.codioart, lv.codioart,-1) END
          WHERE i.tipdoc = 16 AND i.anulat = 0 AND i.operat = 1
            AND NOT (i1.tiplinie = ''='' AND l1.codlivr1 IS NULL)
            AND i.an * 12 + i.luna between ' || coalesce(vAnLunaIni, 0) || ' AND ' || coalesce(vAnLunaFin, 0) || '
            AND i.datadoc BETWEEN ' || coalesce(sdataini, '') || ' AND ' || coalesce(sdatafin, '') || '
            AND EXISTS (SELECT mp.codies
                        FROM moduriplati mp INNER JOIN tmp_manevra_liste tmp ON mp.codbankcont::varchar = tmp.valoare
                        WHERE mp.codies = i.codies AND tmp.filtru = ''CODBANKCONT'')
          GROUP BY i.codies, i.valdoc, i.tvadoc, i.valdiscount, i.tvadiscount, Coalesce(ioa1.venituri,i1.contserv,0) ) x
          INNER JOIN iesiri i ON i.codies = x.codies
          INNER JOIN moduriplati mp ON mp.codies = i.codies
        WHERE mp.codbankcont::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'')
        GROUP BY i.codies, i.tipdoc, i.prefixdoc, i.seriadoc, i.nri, i.nrdoc, i.datadoc, i.agent, i.obs, i.valdoc, i.tvadoc, i.subunitatea, i.curs, i.an, i.luna, mp.codbankcont, x.cont, x.coef, i.userid
        UNION ALL
        SELECT
          i.codies coddoc, NULL coddoc1, i.tipdoc, i.datadoc datareg, Coalesce(i.prefixdoc,''M'') doccumul, i.prefixdoc, i.seriadoc seriedoc, i.nri, i.nrdoc, i.datadoc, i.agent,
          ''Incasare(TVA) Monetar '' explicatii, null den_part, cc.codcontcole cont, i.obs,
          1 tiptranz,
          Round(CASE WHEN i.tvadoc = 0 OR i.valdoc = 0 THEN 0 ELSE SUM(mp.valoare) * i.tvadoc / i.valdoc END,7) val,
          i.valdoc, Coalesce(NullIF(i.curs,0),1) curs, mp.codbankcont codbanca,
          Round(CASE WHEN i.tvadoc = 0 OR i.valdoc = 0 THEN 0 ELSE SUM(mp.valoare) * i.tvadoc / i.valdoc END,7) sold_col,
          Round(CASE WHEN i.tvadoc = 0 OR i.valdoc = 0 THEN 0 ELSE SUM(mp.valoare) * i.tvadoc / i.valdoc END * Coalesce(NullIF(i.curs,0),1),7) soldlei_col,
          2 ORDINE, i.subunitatea, i.codies * 10 +1 idxloc, i.an*12+i.luna anluna, NULL codpart, NULL codpers, NULL codgest, i.userid
        FROM iesiri i
          LEFT JOIN moduriplati mp ON mp.codies = i.codies
          LEFT JOIN cc ON i.an * 12 + i.luna between cc.anlunastart AND cc.anlunastop
        WHERE i.tipdoc = 16 AND i.anulat = 0 AND i.operat = 1
          AND i.an * 12 + i.luna between ' || coalesce(vAnLunaIni, 0) || ' AND ' || coalesce(vAnLunaFin, 0) || '
          AND i.datadoc BETWEEN ' || coalesce(sdataini, '') || ' AND ' || coalesce(sdatafin, '') || '
          AND mp.codbankcont::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'')
        GROUP BY i.codies, i.tipdoc, i.prefixdoc, i.seriadoc, i.nri, i.nrdoc, i.datadoc, i.agent, i.obs, i.valdoc, i.tvadoc, i.subunitatea, i.curs, i.an, i.luna, mp.codbankcont, cc.codcontcole, i.userid';
  END IF;
  sSelect := coalesce(sSelect,'') || '
        UNION ALL
        SELECT
          NULL coddoc, NULL coddoc1, NULL tipdoc, ' || coalesce(sdataini, '''') || ' datareg, NULL doccumul, NULL prefixdoc, NULL seriedoc, NULL nri, NULL nrdoc, NULL DATADOC, NULL AGENT,
          (CASE ordine WHEN 1 THEN ''Documente cu data &lt; ' ||  To_Char(dataIni, 'dd.mm.yyyy') || ''' ELSE ''Sold initial'' END) explicatii, NULL den_part, NULL semnificatie, NULL obs,
          -1 tiptranz, 0 val, 0 valdoc, NULL curs, NULL codbanca, SUM (sold) sold_col, SUM (soldlei) soldlei_col, ordine,
          getsubunitate() subunitatea, 0 idxloc, 0 anluna, NULL codpart, NULL codpers, NULL codgest, NULL userid
        FROM (
          SELECT 0 ordine, 0 sold, 0 soldlei
          UNION ALL
          SELECT 0 ordine, Coalesce(' || coalesce(sColSold,'') || ',0) sold, Coalesce(soldlei,0) soldlei
          FROM nbanksoldluna
          WHERE (an * 12 + luna) = ' || coalesce((vAnLunaIni - 1)::varchar,'') || '
            AND codbankcont::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'')
          UNION ALL
          SELECT ' || coalesce(sIniOrd,'') || ' ordine,
            (t1.valdoc * CASE t1.tiptranz WHEN 1 THEN 1 ELSE -1 END - Coalesce(t1.comision,0)) * CASE bc.credit WHEN 1 THEN -1 ELSE 1 END sold,
            (t1.valdoc * CASE t1.tiptranz WHEN 1 THEN 1 ELSE -1 END - Coalesce(t1.comision,0)) * Coalesce(NullIF(t1.curs,0),1) * CASE bc.credit WHEN 1 THEN -1 ELSE 1 END soldlei
          FROM trezor t
            LEFT JOIN trezor1 t1 ON t1.codtrezor = t.codtrezor
            LEFT JOIN nbankcont bc ON bc.codbankcont = t.codbanca
          WHERE t.tipdoc = ' || coalesce(vTipDoc,'') || ' AND t.operat = 1 AND Coalesce(t1.anulat, 0) = 0 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'t',NULL,NULL,NULL)),'') || '
            AND t.codbanca::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'')
            AND t.datadoc &lt; ' || coalesce(sdataini, '') || '
            AND (t.an * 12 + t.luna) = ' || coalesce(vAnLunaIni, 0);
  IF  vTipDoc::numeric = 29 THEN
    sSelect := coalesce(sSelect,'') || '
          UNION ALL
          SELECT ' || coalesce(sIniOrd,'') || ' ordine, SUM(mp.valoare) sold , SUM(mp.valoare) * Coalesce(NullIF(i.curs,0),1) soldlei
          FROM iesiri i LEFT JOIN moduriplati mp ON mp.codies = i.codies
          WHERE i.tipdoc = 16 AND i.anulat = 0 AND i.operat = 1 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'i',NULL,NULL,NULL)),'') || '
            AND i.an * 12 + i.luna = ' || coalesce(vAnLunaIni, 0) || '
            AND i.datadoc &lt; ' || coalesce(sdataini, '') || '
            AND mp.codbankcont::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'')
          GROUP BY i.codies, i.tipdoc, i.prefixdoc, i.seriadoc, i.nri, i.nrdoc, i.datadoc, i.agent, i.obs, i.valdoc, i.tvadoc, i.subunitatea, i.curs, mp.codbankcont';
  END IF;
  sSelect := coalesce(sSelect,'') || '
        ) d_pg
        GROUP BY ordine
        UNION ALL
        SELECT NULL coddoc, NULL coddoc1, NULL tipdoc, datadoc datareg, NULL doccumul, NULL prefixdoc, NULL seriedoc, NULL nri, NULL nrdoc, NULL datadoc, NULL AGENT,
          ''Sold ziua precedenta'' explicatii, NULL den_part, NULL semnificatie, NULL obs,
          -1 tiptranz, 0 val, 0 valdoc, NULL curs, NULL codbanca, 0 sold_col, 0 soldlei_col, 1 ordine,
          getsubunitate() subunitatea, 0 idxloc, 0 anluna, NULL codpart, NULL codpers, NULL codgest, NULL userid
        FROM (
          SELECT datadoc
          FROM  trezor t
          WHERE tipdoc = ' || coalesce(vTipDoc,'') || ' AND t.operat = 1 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,NULL,NULL,NULL,NULL)),'') || '
            AND datadoc between ' || coalesce(sdatainiSP, '') || ' AND ' || coalesce(sdatafin, '') || '
            AND t.codbanca::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'')';
  IF  vTipDoc::numeric = 29 THEN
    sSelect := coalesce(sSelect,'') || '
          UNION
          SELECT i.datadoc
          FROM iesiri i LEFT JOIN moduriplati mp ON mp.codies = i.codies
          WHERE i.tipdoc = 16 AND i.anulat = 0 AND i.operat = 1 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'i',NULL,NULL,NULL)),'') || '
            AND i.an * 12 + i.luna between ' || coalesce(vAnLunaIni, 0) || ' AND ' || coalesce(vAnLunaFin, 0) || '
            AND i.datadoc BETWEEN ' || coalesce(sdatainiSP,'') || ' AND ' || coalesce(sdatafin, '') || '
            AND mp.codbankcont::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODBANKCONT'') ';
  END IF;
  sSelect := coalesce(sSelect,'') || '
          ) e_pg' || coalesce(sSelreg,'') || '),
      R AS (
        SELECT CODBANK, LAST_VALUE(CURS) OVER (PARTITION  BY CODBANK  ORDER BY datadoc desc  range between unbounded preceding and unbounded following) CURS
          FROM reg WHERE tipreg = 45
          AND datadoc BETWEEN ' || coalesce(sdataini, '') || ' AND ' || coalesce(sdatafin, '') || '
          AND an * 12 + luna between ' || coalesce(vAnLunaIni, 0) || ' AND ' || coalesce(vAnLunaFin, 0) || '
          AND codmoneda = ' || coalesce(vCodMoneda, 0) || ')
    SELECT distinct
      rb.coddoc, rb.coddoc1, rb.tipdoc, rb.datareg, rb.doccumul, rb.prefixdoc, rb.seriedoc, rb.nri, rb.nrdoc, rb.datadoc, ag.nume||'' ''||ag.prenume agent,
      CAST(rb.explicatii As VARCHAR(300)) explicatii, rb.den_part, nc.simbol semnificatie, cs.simbol contsec, rb.obs,
      Coalesce(CASE WHEN rb.tiptranz  = 1      THEN rb.val END,0) * Coalesce(CASE nbc.codmoneda WHEN 0 THEN rb.curs ELSE 1 END,0) incasare,
      Coalesce(CASE WHEN rb.tiptranz IN (0, 2) THEN rb.val END,0) * Coalesce(CASE nbc.codmoneda WHEN 0 THEN rb.curs ELSE 1 END,0) plata,
      rb.valdoc, rb.valdoc * Coalesce(r.curs,rb.curs) valdoclei,
      CASE nbc.credit WHEN 1 THEN -1 ELSE 1 END * rb.sold_col, CASE nbc.credit WHEN 1 THEN -1 ELSE 1 END * rb.soldlei_col,
      rb.ordine, rb.idxloc, nb.simbol simb_banca, nbc.den_cont, nbc.nrcont, sub.den_subunit, ncb.simbol contrepr, CASE rb.tiptranz WHEN 1 THEN ''Incasare'' ELSE ''Plata'' END tiptranz,
      CASE
        WHEN Coalesce(rb.curs,0) &lt;&gt; 0 THEN rb.curs
        WHEN Coalesce(rb.sold_col,0) &lt;&gt; 0 AND Coalesce(rb.soldlei_col,0) &lt;&gt; 0 THEN rb.soldlei_col/rb.sold_col
        ELSE 1
      END curs, ' || coalesce(sCursRef,'') || gUserAlias || '
    FROM rb
      LEFT JOIN nbankcont nbc ON nbc.codbankcont = rb.codbanca
      LEFT JOIN nbank nb ON nb.codbank = nbc.codbank
      LEFT JOIN npers ag ON ag.codpers = rb.agent
      LEFT JOIN npart part ON part.codpart = rb.codpart
      LEFT JOIN npers pers ON pers.codpers = rb.codpers
      LEFT JOIN ngest ng ON ng.codgest = rb.codgest
      LEFT JOIN nsubunit sub ON sub.codsubunit = rb.subunitatea
      LEFT JOIN nbc1 ON nbc1.codbankcont = rb.codbanca AND nbc1.anlunastart &lt;= rb.anluna AND nbc1.anlunastop &gt;= rb.anluna
      LEFT JOIN iob1 ON iob1.codiobank = nbc1.codiobanca AND iob1.anlunastart &lt;= rb.anluna AND iob1.anlunastop &gt;= rb.anluna
      LEFT JOIN ncont nc ON nc.codcont = rb.cont
      LEFT JOIN nc1 ON nc1.codcont = rb.cont AND nc1.anlunastart &lt;= rb.anluna AND nc1.anlunastop &gt;= rb.anluna
      LEFT JOIN nconts cs ON cs.codconts = nc1.contsecundar
      LEFT JOIN ncont ncb ON ncb.codcont = iob1.cont
      LEFT JOIN r ON r.codbank = nbc.codbank' || gSuplJoins || '
    ORDER BY rb.datareg, rb.ordine, rb.idxloc';
  PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
  IF getsubunitate() &lt;&gt; 1 AND fnc_getvalconstantalucru('Holding')::NUMERIC &lt;&gt; 1
  THEN
    SELECT DEN_SUBUNIT
    INTO vDenSubunit
    FROM NSUBUNIT
    WHERE
       CodSubunit = current_setting('PKG_GLOBALS.SUBUNITATE', true)::NUMERIC;
    EXECUTE 'SELECT Count(1), Sum(INCASARE), SUM(PLATA), Sum(sold_col), Sum(soldlei_col) FROM ' || tmpName || ' WHERE SUBUNITATEA &lt;&gt; $1'
    INTO vCount, vValI, vValP, vSold_Col, vSoldLei_Col USING vDenSubunit;

    IF vCount &gt; 0 THEN
      EXECUTE 'DELETE FROM ' || tmpName || ' WHERE SUBUNITATEA &lt;&gt; $1' USING vDenSubunit;
      IF vValI &lt;&gt; 0 OR  vValP &lt;&gt; 0 OR vSold_Col &lt;&gt; 0 OR vSoldLei_Col &lt;&gt; 0 THEN
        EXECUTE 'INSERT INTO ' || tmpName || ' (
          DATAREG, AGENT, EXPLICATII, INCASARE, PLATA, VALDOC, VALDOCLEI, SOLD_COL, SOLDLEI_COL, ORDINE, IDXLOC, SUBUNITATEA)
          SELECT to_date(''' || coalesce(To_Char(dataFin, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy''), '' '', ''Tranzactii alte subunitati'', $1, $2, 0, 0, $3, $4, 9, 0, ''Altele'' '
          USING vValI, vValP, vSold_Col, vSoldLei_Col;
      END IF;
    END IF;
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regjurnal_guseralias</obj_name>
  <obj_hashval>f5864f3c957f22878fff5a34029b44b6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_guseralias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_REGJURNAL.gUserAlias'));
  RETURN ;
  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_regjurnal_lunafin</obj_name>
  <obj_hashval>124e8f80cb1f96dbc5de2b7dffe9f914</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_lunafin(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result :=  current_setting('PKG_LIST_BASE_REGJURNAL.p_LunaFin')::numeric;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_restlistgest_setparams</obj_name>
  <obj_hashval>4248cd40352d49f8377c935770984d20</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_restlistgest_setparams(acodgest numeric, acodrestcmd numeric, aid numeric, aver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  perform set_config('PKG_LIST_BASE_RESTLISTGEST.CODGEST'   ,(aCodGest)::varchar   ,false);
  perform set_config('PKG_LIST_BASE_RESTLISTGEST.CODRESTCMD',(aCodRestCmd)::varchar,false);
  perform set_config('PKG_LIST_BASE_RESTLISTGEST.ID'        ,(aID)::varchar        ,false);
  perform set_config('PKG_LIST_BASE_RESTLISTGEST.VER'       ,(aVer)::varchar       ,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rezmf_setjoinuri</obj_name>
  <obj_hashval>19738ea606d86b9fdc07997402cf37ca</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rezmf_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 29.12.2021
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_REZMF.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rezmf_setparams</obj_name>
  <obj_hashval>1cc529c23db9d4844b496f2d73b7aaef</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rezmf_setparams(pcod numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 29.12.2021
  perform set_config('PKG_LIST_BASE_REZMF.vCod',pCod::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sediipart_setjoinuri</obj_name>
  <obj_hashval>40ba7b3bb3a680bab0c5f31ecb174611</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sediipart_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Adina iulie 2020
PERFORM Pkg_List_Struct_SetTableSpec( current_setting('PKG_LIST_BASE_SEDIIPART.gSuplCols', true));
PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sinttrez_processlist</obj_name>
  <obj_hashval>09d9932117ea2dcdfa1adb71ce86e057</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sinttrez_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     text;
  i           numeric;
  oData       date;
  oDataFin    date;
  gSuplCols   varchar := '';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Stef 07.06.2023 - Optimizare
  --PERFORM PKG_GLOBALS_SetDebugMode(TRUE);
  CALL create_wm_temps_flag('TMP_SINTTREZ');
  gSuplCols :='nmonede m, nbankcont bc, nbank b, ncont nc, nsubunit sub'  ;
  CALL pkg_list_struct_StartSuplCols();
  CALL pkg_list_struct_GetSuplCols(aLISTID,alistver,gUserFields,gUserAlias,gNullAlias,gSuplJoins,gSuplCols);
  perform set_config('PKG_LIST_BASE_SINTTREZ.gSuplCols',gSuplCols,false);

  PERFORM PKG_LIST_BASE_SINTTREZ_TMPPrepare(0,0);
  CALL PRC_AL_CHECK('nbankcont1',0);
  CALL PRC_AL_CHECK('iobank1',0);

  sInsert :=
  'INSERT INTO '||tmpName||'(
    AnLuna, An, Luna,
    Banca, Cont, NrCont, Moneda,
    SoldInit, Incasari, Plati, SoldFin,
    SoldInitLEI, IncasariLEI, PlatiLEI, DifRegLEI, SoldFinalLEI,
    ContReprez, UltData, Subunitate, CodBankCont'||gUserFields||' )
  SELECT
    stt.an*12+stt.luna anluna, stt.an,
    CASE stt.luna
      WHEN  1 THEN ''01 - Ianuarie''
      WHEN  2 THEN ''02 - Februarie''
      WHEN  3 THEN ''03 - Martie''
      WHEN  4 THEN ''04 - Aprilie''
      WHEN  5 THEN ''05 - Mai''
      WHEN  6 THEN ''06 - Iunie''
      WHEN  7 THEN ''07 - Iulie''
      WHEN  8 THEN ''08 - August''
      WHEN  9 THEN ''09 - Septembrie''
      WHEN 10 THEN ''10 - Octombrie''
      WHEN 11 THEN ''11 - Noiembrie''
      WHEN 12 THEN ''12 - Decembrie''
    END luna,
    b.simbol banca, bc.den_cont cont, bc.nrcont, m.simbol moneda,
    stt.soldin, stt.incasari, stt.plati, stt.soldin + (stt.incasari - stt.plati) * CASE WHEN Coalesce(bc.credit,0) = 0 THEN 1 ELSE -1 END soldfin,
    stt.soldinlei, stt.incasarilei, stt.platilei,
    CASE
      WHEN cr.curs IS NULL then 0
      ELSE (stt.soldin    + (stt.incasari    - stt.plati   ) * CASE WHEN Coalesce(bc.credit,0) = 0 THEN 1 ELSE -1 END) * cr.curs -
           (stt.soldinlei + (stt.incasarilei - stt.platilei) * CASE WHEN Coalesce(bc.credit,0) = 0 THEN 1 ELSE -1 END)
    END DifRegLei,
    CASE
      WHEN cr.curs IS NULL
      THEN  stt.soldinlei + (stt.incasarilei - stt.platilei) * CASE WHEN Coalesce(bc.credit,0) = 0 THEN 1 ELSE -1 END
      ELSE (stt.soldin    + (stt.incasari    - stt.plati   ) * CASE WHEN Coalesce(bc.credit,0) = 0 THEN 1 ELSE -1 END) * cr.curs
    END soldfinlei,
    nc.simbol, stt.ultdata, sub.den_subunit, bc.codbankcont '||gUserAlias||'
  FROM (
    SELECT
      an, luna, codbankcont, Max(datadoc) ultdata,
      sum(incasari)    incasari,    sum(plati)    plati,    sum(soldin)    soldin,
      sum(incasarilei) incasarilei, sum(platilei) platilei, sum(soldinlei) soldinlei
    FROM tmp_stt
    GROUP BY an, luna, codbankcont
  ) STT
    LEFT JOIN nbankcont  bc   ON bc.codbankcont  = stt.codbankcont
    LEFT JOIN nmonede    m    ON m.codmoneda     = bc.codmoneda
    LEFT JOIN nbank      b    ON b.codbank       = bc.codbank
    LEFT JOIN nbankcont1 bc1  ON bc1.codbankcont = bc.codbankcont and stt.an*12+stt.luna between  bc1.Alstart and  bc1.Alstop
    LEFT JOIN iobank1    iob1 ON iob1.codiobank  = bc1.codiobanca and stt.an*12+stt.luna between iob1.Alstart and iob1.Alstop
    LEFT JOIN ncont      nc   ON nc.codcont      = iob1.cont
    LEFT JOIN tmp_sttreg cr   ON cr.codmoneda    = bc.codmoneda AND cr.luna = stt.luna AND cr.an = stt.an AND COALESCE(BC.FARAREG, 0) = 0
    LEFT JOIN nsubunit   sub  ON sub.codsubunit  = bc.subunitatea'||
    gSuplJoins|| '
  WHERE b.codbank &lt;&gt; 0
  ORDER BY stt.luna, bc.codbank, bc.codmoneda';

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  IF current_setting('PKG_LIST_SELECTPERIOADA.vOpt1', true)::numeric = 1 THEN
    oData    := to_date(current_setting('PKG_LIST_SELECTPERIOADA.vdataini', true),'dd.mm.yyyy');
    oDataFin := to_date(current_setting('PKG_LIST_SELECTPERIOADA.vdatafin', true),'dd.mm.yyyy');
    i := 0;
    WHILE oData &lt;= oDataFin LOOP
      i := i + 1;
      sInsert :=
      'UPDATE '||tmpName||' TMP SET
       (W'||i::varchar||', WLEI'||i::varchar||')  =
       (
         SELECT
           Coalesce(SUM(stt.soldin   +stt.incasari   -stt.plati   *CASE WHEN Coalesce(bc.credit,0) = 0 THEN 1 ELSE -1 END), 0),
           Coalesce(SUM(stt.soldinlei+stt.incasarilei-stt.platilei*CASE WHEN Coalesce(bc.credit,0) = 0 THEN 1 ELSE -1 END), 0)
         FROM TMP_STT STT LEFT JOIN NBANKCONT BC ON BC.CODBANKCONT = STT.CODBANKCONT
         WHERE STT.DATADOC &lt;= TO_DATE('''||TO_CHAR(oData,'dd.mm.yyyy')||''',''dd.mm.yyyy'')
           AND TMP.CODBANKCONT = STT.CODBANKCONT AND STT.AN = '||To_Char(oData,'yyyy')||' AND STT.LUNA = '||To_Char(oData,'mm')||'
       )';
      PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

      oData := oData + 1;
    END LOOP;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sinttrez_tmpprepare</obj_name>
  <obj_hashval>5916b2edf5436cddc17c260f740f063b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sinttrez_tmpprepare(alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sUpdate     varchar;
  sExtraSold  varchar;
  sDataIni    varchar := '';
  sDataFin    varchar := '';
  sFiltruData varchar := '';
  vAnLunaIni  numeric;
  vAnLunaFin  numeric;
  dDataIni    date;
  dDataFin    date;
  sAnLunaIni  varchar;
  sAnLunaFin  varchar;
BEGIN
  --Florin 24.04.2025 - sinc. Oracle
  --Florin 15.06.2023 - fixat 58575
  --Stef 07.06.2023 - Optimizare
  IF (current_setting('PKG_LIST_SELECTPERIOADA.vDupaData', true)::NUMERIC = 1) THEN
    dDataIni    := to_date(current_setting('PKG_LIST_SELECTPERIOADA.vdataini', true),'dd.mm.yyyy')::date;
    dDataFin    := to_date(current_setting('PKG_LIST_SELECTPERIOADA.vdatafin', true),'dd.mm.yyyy')::date;
    vAnLunaIni  := Extract( YEAR FROM dDataIni) * 12 + Extract( MONTH FROM dDataIni);
    vAnLunaFin  := Extract( YEAR FROM dDataIni) * 12 + Extract( MONTH FROM dDataIni);
    sDataIni    := 'To_Date(''' || coalesce(To_Char(dDataIni, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
    sDataFin    := 'To_Date(''' || coalesce(To_Char(dDataFin, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
    sFiltruData := '
    AND d.datadoc &lt;= ' || coalesce(sDataFin,'');
  ELSE
    vAnLunaIni := current_setting('PKG_LIST_SELECTPERIOADA.vAnLunaIni', true)::numeric;
    vAnLunaFin := current_setting('PKG_LIST_SELECTPERIOADA.vAnLunaFin', true)::numeric;
  END IF;
  sAnLunaIni := To_Char(vAnLunaIni, 'fm99999');
  sAnLunaFin := To_Char(vAnLunaFin, 'fm99999');

  DELETE FROM tmp_stt;

  sInsert := 'INSERT INTO tmp_stt(
    An, Luna, CodBankCont, TipDoc, CodDoc, CodDoc1, IndexLocal, CarnetDoc, SerieDoc, DataDoc,
    Document, CursDoc,
    Soldin, SoldInLei,
    Incasari, Plati, Explicatii )
  SELECT
    t.an, t.luna, t.codbanca CodBankCont, t.tipdoc, t.codtrezor CodDoc, d.codtrezor1 CodDoc1, d.IndexLocal, d.CarnetDoc, d.SerieDoc, d.datadoc,
    d.doc||d.nrdoc||''/''||to_char(d.datadoc,''dd.mm.yyyy'') as Document, Coalesce(NULLIF(d.curs,0),1) CursDoc,
    0 Soldin, 0 SoldInLei,
   CASE
     WHEN d.tiptranz = 1 THEN
       coalesce(o.valoare/case when b.codmoneda &lt;&gt; g.moneda then case when Coalesce(d.curs,1) = 0 then 1 else Coalesce(d.curs,1) end/
       case when coalesce(g.curs,1) = 0 then 1 else coalesce(g.curs,1) end else 1 end,d.valdoc)
     ELSE 0
   END Incasari,
   CASE
     WHEN d.tiptranz = 1 THEN 0
     ELSE coalesce(o.valoare/case when b.codmoneda &lt;&gt; g.moneda then case when Coalesce(d.curs,1) = 0 then 1 else Coalesce(d.curs,1) end/
       case when coalesce(g.curs,1) = 0 then 1 else coalesce(g.curs,1) end else 1 end,d.valdoc)
   END + Coalesce(d.comision,0)*coalesce(o.valoare/
     case when coalesce(b.codmoneda,0) &gt; 0 and b.codmoneda &lt;&gt; g.moneda then case when Coalesce(d.curs,1) = 0 then 1 else Coalesce(d.curs,1) end else 1 end,d.valdoc)/d.valdoc Plati,
      CASE
      WHEN CASE WHEN d.platatva = 1 THEN 2 ELSE d.tiptranz END = 0 AND d.obiecttranz = 0 THEN ''Plata furnizor ''
      WHEN CASE WHEN d.platatva = 1 THEN 2 ELSE d.tiptranz END = 0 AND d.obiecttranz = 1 THEN ''Plata retur ''
      WHEN CASE WHEN d.platatva = 1 THEN 2 ELSE d.tiptranz END = 0 AND d.obiecttranz = 2 THEN ''Plata angajat ''
      WHEN CASE WHEN d.platatva = 1 THEN 2 ELSE d.tiptranz END = 0 AND d.obiecttranz = 3 THEN ''Plata viramente interne ''
      WHEN CASE WHEN d.platatva = 1 THEN 2 ELSE d.tiptranz END = 0 AND d.obiecttranz = 4 THEN ''Plata direct pe cheltuieli ''
      WHEN CASE WHEN d.platatva = 1 THEN 2 ELSE d.tiptranz END = 0 AND d.obiecttranz = 5 THEN ''Plata datorii / taxe / impozite ''
      WHEN CASE WHEN d.platatva = 1 THEN 2 ELSE d.tiptranz END = 1 AND d.obiecttranz = 0 THEN ''Incasare client ''
      WHEN CASE WHEN d.platatva = 1 THEN 2 ELSE d.tiptranz END = 1 AND d.obiecttranz = 1 THEN ''Incasare retur ''
      WHEN CASE WHEN d.platatva = 1 THEN 2 ELSE d.tiptranz END = 1 AND d.obiecttranz = 2 THEN ''Incasare angajat ''
      WHEN CASE WHEN d.platatva = 1 THEN 2 ELSE d.tiptranz END = 1 AND d.obiecttranz = 3 THEN ''Incasare viramente interne ''
      WHEN CASE WHEN d.platatva = 1 THEN 2 ELSE d.tiptranz END = 1 AND d.obiecttranz = 4 THEN ''Incasare direct pe venituri ''
      WHEN CASE WHEN d.platatva = 1 THEN 2 ELSE d.tiptranz END = 1 AND d.obiecttranz = 5 THEN ''Incasare imprumuturi / subventii ''
      WHEN CASE WHEN d.platatva = 1 THEN 2 ELSE d.tiptranz END = 1 AND d.obiecttranz = 6 THEN ''Incasare dobanda ''
      WHEN CASE WHEN d.platatva = 1 THEN 2 ELSE d.tiptranz END = 2                       THEN ''Plata SPLIT TVA ''
    END ||
    CASE d.obiecttranz
      WHEN 3 THEN nb.denumire||'' ''||nbc.nrcont
      WHEN 2 THEN pers.nume||'' ''||pers.prenume
      WHEN 1 THEN part.den_part
      WHEN 0 THEN part.den_part
      ELSE (
        SELECT nc.simbol
        FROM ncont nc
        WHERE nc.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 (select wme_result from PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(null, o.semnificatie, o.icont, PKG_CONTURIBANCI_GET_BANKCONT_COD_CARACT_LUNA(t.codbanca,t.an,t.luna)))
            WHEN o.semnificatie IN (1100,1101)         THEN (select wme_result from PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(null, o.semnificatie, o.icont, PKG_NOMPERS_GET_PERS_COD_CARACT_LUNA(d.codpart,t.an,t.luna)))
            ELSE                                            (SELECT wme_result FROM PKG_GLOBALS_GET_CONT_CONTABIL_OBLIG(NULL, o.semnificatie, o.icont, PKG_NOMPART_GET_PART_COD_CARACT_LUNA(d.codpart,t.an,t.luna)))
          END
      )
    END ||'' ''||
    CASE
      WHEN o.semnificatie IN (310,410) THEN ''in avans ''
      WHEN int.codintr IS NOT NULL THEN int.prefixdoc|| ''/''||int.nrdoc||''/''||int.datadoc
      WHEN ies.codies  IS NOT NULL THEN ies.prefixdoc|| ''/''||ies.nrdoc||''/''||ies.datadoc
    END
  FROM trezor t
    INNER JOIN trezor1 d ON d.codtrezor = t.codtrezor
    LEFT JOIN NBANKCONT B ON B.CODBANKCONT = T.CODBANCA
    LEFT JOIN general g ON g.tipdoc = t.tipdoc AND g.coddoc = d.codtrezor1
    LEFT JOIN obligpif o ON o.codgeneral = g.codgeneral
    LEFT JOIN npart part ON part.codpart = d.codpart AND d.obiecttranz IN (0,1)
    LEFT JOIN npers pers ON pers.codpers = d.codpart AND d.obiecttranz = 2
    LEFT JOIN nbankcont nbc ON nbc.codbankcont = d.codpart AND d.obiecttranz = 3
    LEFT JOIN nbank nb ON nb.codbank = nbc.codbank
    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 intrari int on int.codintr = gs.coddoc and int.tipdoc = gs.tipdoc
    LEFT JOIN iesiri ies on ies.codies = gs.coddoc and ies.tipdoc = gs.tipdoc
    LEFT JOIN trezor1 ts1 ON ts1.codtrezor1 = gs.coddoc AND gs.tipdoc IN (29,31)
    LEFT JOIN trezor ts ON ts.codtrezor = ts1.codtrezor
  WHERE t.tipdoc IN (29,30)
    AND t.operat = 1 AND Coalesce(d.anulat,0) = 0 and coalesce(d.valdoc,0) &lt;&gt; 0';
  IF current_setting('PKG_LIST_SELECTPERIOADA.vOpt2', TRUE)::NUMERIC = 1 THEN
    sInsert := sInsert||'  AND T.SUBUNITATEA = GETSUBUNITATE()';
  END IF;
  sInsert := sInsert||'
    AND t.an * 12 + t.luna BETWEEN '||sAnLunaIni||' AND '||sAnLunaFin||
    sFiltruData;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  sInsert := 'INSERT INTO tmp_stt(
    An, Luna, CodBankCont, TipDoc, CodDoc, CodDoc1, IndexLocal, CarnetDoc, SerieDoc, DataDoc,
    Document, CursDoc,
    Soldin, SoldInLei,
    Incasari, Plati)
  SELECT
    d.an, d.luna, m.codbankcont, d.tipdoc, d.codies CodDoc, 0 CodDoc1, 0 IndexLocal, d.CarnetDoc, d.SeriaDoc, d.datadoc,
    d.prefixdoc||d.nrdoc||''/''||TO_CHAR(d.Datadoc,''dd.mm.yyyy'') as Document, Coalesce(NULLIF(d.curs,0),1) CursDoc,
    0 Soldin, 0 SoldInLei,
    m.valoare Incasari, 0 Plati
    FROM IESIRI d inner JOIN moduriplati m ON m.codies = d.codies
  WHERE d.tipdoc = 16 and M.CODBANKCONT &gt; 0
    AND operat = 1 AND d.anulat = 0';
  if current_setting('PKG_LIST_SELECTPERIOADA.vOpt2', TRUE)::NUMERIC = 1 THEN
    sInsert := sInsert||'  AND D.SUBUNITATEA = GETSUBUNITATE()';
  END IF;
  sInsert := sInsert||'
    AND d.an * 12 + d.luna BETWEEN '||sAnLunaIni||' AND '||sAnLunaFin||
    sFiltruData;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  sUpdate := 'UPDATE tmp_stt SET IncasariLei = Incasari*CursDoc, PlatiLei = Plati*CursDoc';
  PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate, aListID, aListVer);

  DELETE FROM tmp_sttsolddoc;
  sInsert := 'INSERT INTO tmp_sttsolddoc ( An, Luna, CodBankCont, DataDoc, SoldIn, SoldInLei)
  SELECT An, Luna, CodBankCont, Max(DataDoc) DataDoc, SUM(Incasari - Plati) SoldIn, Sum(IncasariLei - PlatiLei) SoldInLei
  FROM tmp_stt
  WHERE DataDoc &lt; '||sDataIni||'
  GROUP BY An, Luna, CodBankCont';

  IF (current_setting('PKG_LIST_SELECTPERIOADA.vDupaData', true)::NUMERIC = 1) THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
    PERFORM LIST_EXECUTE_IMMEDIATE('DELETE FROM tmp_stt WHERE DataDoc &lt; ' || sDataIni, aListID, aListVer);
  END IF;

  sInsert := 'INSERT INTO tmp_stt(
    An, Luna, CodBankCont, TipDoc, CodDoc, CodDoc1, IndexLocal, DataDoc,
    Document, CursDoc,
    SoldIn, SoldInLei,
    Incasari, IncasariLei, Plati, PlatiLei)
  SELECT
    An, Luna, CodBankCont, 0 TipDoc, 0 CodDoc, 0 CodDoc1, 0 IndexLocal, Max(DataDoc),
    ''Sold initial'' as Document, 1 CursDoc,
    Sum(SoldIn), Sum(SoldInLei),
    0 Incasari, 0 IncasariLei, 0 Plati, 0 PlatiLei
  FROM (
    SELECT
      s.an + CASE s.luna WHEN 12 THEN 1 ELSE 0 END an, CASE s.luna WHEN 12 THEN 1 ELSE s.luna+1 END luna, s.codbankcont,
      last_day(to_date(To_Char(s.an,''fm0000'')||To_Char(s.luna,''fm0000''),''yyyymm'')) datadoc,
      CASE WHEN Coalesce(bc.codmoneda,0) = 0 THEN s.soldlei ELSE s.soldvaluta END soldin, s.soldlei soldinlei
    FROM nbanksoldluna s LEFT JOIN nbankcont bc ON bc.codbankcont = s.codbankcont
    WHERE (s.an*12+s.luna+1) BETWEEN '||sAnLunaIni||' AND '||sAnLunaFin;
  if current_setting('PKG_LIST_SELECTPERIOADA.vOpt2', TRUE)::NUMERIC = 1 THEN
    sInsert := sInsert||'  AND BC.SUBUNITATEA = GETSUBUNITATE()';
  END IF;
  sInsert := sInsert||'
    UNION ALL
    SELECT
      An, Luna, CodBankCont,
      DataDoc,
      SoldIn, SoldInLei
    FROM  tmp_sttsolddoc
  ) subs
  GROUP BY An, Luna, CodBankCont';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  DELETE FROM tmp_sttreg;
  sInsert := 'INSERT INTO tmp_sttreg( An, Luna, CodMoneda, Curs)
  SELECT An, Luna, CodMoneda, Curs
  FROM (
    SELECT An, Luna, CodMoneda, Curs, Row_Number() OVER (PARTITION BY An, Luna, CodMoneda ORDER BY DataDoc DESC) IDXCurs
    FROM reg
    WHERE tipreg = 45 AND an *12 + luna BETWEEN '||sAnLunaIni||' AND '||sAnLunaFin;
--  if current_setting('PKG_LIST_SELECTPERIOADA.vOpt2', TRUE)::NUMERIC = 1 THEN
--    sInsert := sInsert||'  AND CODSUBUNIT = GETSUBUNITATE()';
--  END IF;
  sInsert := sInsert||'
  ) subs
  WHERE IDXCurs = 1';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitconsum_processlist</obj_name>
  <obj_hashval>4d94770bc9f6bf2113fd30e0072e847f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitconsum_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sColSerii   varchar := ', NULL serii, NULL serobs, NULL sercant';
  sColNP      VARCHAR := ', NULL SERIIPROD, NULL NRNP ';
  sColTmpNP   VARCHAR := ', NULL SERIIPROD, NULL NRNP ';
  sJoinNP     VARCHAR := '';
  sJoinSerii  varchar;
  sFiltru     varchar;
  gSuplCols   VARCHAR:= 'ioart io, iesiri i, iesiri1 i1, livr l, livr1 l1, num1 u, nartobj o, nart a, nartamb aa, comanda1 ci1, comanda ci, comanda1 cc1, comanda cc, npart cli, nirstoc nirstoc, nclasea ca, nirser nse, nserii ser,' || 'centrecost cco,LANSARE LANS,PRODCOMP PC,TMP_LST_SITCONSUM TMP, cmdprodmat mat, cmdprodmat prod';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 06.12.2022 - sinc. Oracle
  --Florin 24.02.2022 - sinc. Oracle (23.02.2022)
  --Florin 09.08.2021 - sinc. Oracle (51005)
  --Adina 12.04.2021 - alstart,alstop
  --Adina 12.04.2021 - sinc.Oracle din 10.04.2021 - infonp
  --Florin 07.08.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_SITCONSUM.gSuplCols',gSuplCols,false);

  CALL PRC_AL_CHECK('ioart1',0);

  IF current_setting('PKG_LIST_SELECTPER.bAduSerii' , TRUE)::NUMERIC = 1 THEN
    sColSerii := ',
          CASE WHEN COALESCE(ns.tipserie,0) &lt;&gt; 0 THEN string_agg(s.serie, '''') END serii,
          CASE WHEN COALESCE(ns.tipserie,0) &lt;&gt; 0 THEN string_agg(nser.obs, '''') END serobs,
          CASE WHEN COALESCE(ns.tipserie,0) &lt;&gt; 0 THEN string_agg(s.serie||''(''||trunc(l1.cant)||'')'', '''') END sercant';
    sJoinSerii := '
             LEFT JOIN nirser nser ON nser.codnirser = l1.codnirser
             LEFT JOIN nserii s    on s.codserie     = nser.codserie';
  END IF;

  IF COALESCE(NULLIF(current_setting('PKG_LIST_SELECTPER.bInfoNP' , TRUE),'')::NUMERIC,0) = 1 THEN
    sColNP    := ', TMP.SERIIPROD, TMP.NRNP ';
    sColTmpNP := ', ser_np.serii, nr_np.nrdocs ';
    sJoinNP   := '
                 LEFT JOIN (
                   select
                     CASE
                       WHEN coalesce(ns.tipserie,0) &lt;&gt; 0 THEN fnc_array_to_string_sum(array_agg(s.serie||''(~#''||nse.cantnir||''#~)'' order by s.serie) )
                     END serii,
                     i1.codcmdint1,
                     i1.codobiect
                   from intrari1 i1
                        inner join intrari i   on i1.codintr     = i.codintr
                        inner join nirstoc ns  on ns.codintr1    = i1.codintr1
                        inner join nirser  nse on nse.codnirstoc = ns.codnirstoc
                        inner join nserii  s   on nse.codserie   = s.codserie
                   where coalesce(i.anulat,0) = 0 and i.operat = 1 and i.tipdoc = 7
                   group by i1.codcmdint1, i1.codobiect, ns.tipserie
                ) SER_NP on ser_np.codcmdint1 = lg.codcmdint1 and ser_np.codobiect = oc.codobiect
                LEFT JOIN (
                  select
                    fnc_array_to_vc3200(array_agg(i.nrdoc::varchar order by i.nrdoc))  nrdocs,
                    i1.codcmdint1,
                    i1.codobiect
                  from intrari1 i1
                       inner join intrari i on i1.codintr = i.codintr
                  where coalesce(i.anulat,0) = 0 and i.operat = 1 and i.tipdoc = 7
                  group by i1.codcmdint1, i1.codobiect
                ) NR_NP on nr_np.codcmdint1 = lg.codcmdint1 and nr_np.codobiect = oc.codobiect
                ';
  END IF;

  IF current_setting('PKG_LIST_SELECTPER.vToateArt' , TRUE)::NUMERIC = 0 THEN
    sFiltru := COALESCE(sFiltru,'') || '
          AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' AND VALOARE = i1.CODOBIECT::varchar) ';
  END IF;

  IF current_setting('PKG_LIST_SELECTPER.vToateGest' , TRUE)::NUMERIC = 0 THEN
    sFiltru := COALESCE(sFiltru,'') || '
          AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = i.CODGESTPROD::VARCHAR) ';
  END IF;

  DELETE FROM TMP_LST_SITCONSUM;
  sInsert := 'INSERT INTO TMP_LST_SITCONSUM (
      codlivr1, codies,codlivr,codies1,codioart1,gest,umsec,codcmdint1,codnirstoc,codnirser,
      NAV_CodDoc,NAV_TipDoc,PREFIXDOC,NRDOC,DATADOC,DOCIESIRE,
      GEST_PROD,GEST_SURSA, DENUMIRE,PRODUS,CONT,CHELTUIELI,
      PU,CANT,UM,VALOARE, CANTUM1, CANTUM2, UM1, UM2,
      PERS, MASINA, SERII, SEROBS, SERCANT, TIPRETETA,
      NRCI, DATACI, NRCC, DATACC, CLIENT,
      PMP, PMPVALUTA, PMPPREC, PMPPRECVAL, PRETACHIZ, VALACHIZ, SERIIPROD, NRNP)
    WITH lg As (
      SELECT
        l1.codlivr1, i.codies, i1.codies1, l.codlivr, l1.umsec, COALESCE(COALESCE(lv.gest, n.gest),0) gest, COALESCE(ns.codlocatie,0) codlocatie,
        (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) codioart1,
        ns.furn, ns.codgestprod gestfurn, sum(l1.cant) cant, sum(l1.cantum1) cantum1, sum(l1.cantum2) cantum2, ns.d1, ns.d2, ns.d3, ns.codnirstoc, COALESCE(l1.codnirser,0) codnirser,
        COALESCE(lv.pretachiz, COALESCE(ns.pret,0) - COALESCE(ns.adaos,0)) pretachiz, sum(l1.cant * COALESCE(lv.pretachiz, COALESCE(ns.pret,0) - COALESCE(ns.adaos,0))) valachiz, I1.CODCMDINT1 ' || coalesce(sColSerii,'') || '
      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';
  IF current_setting('PKG_LIST_SELECTPER.vTipPer', TRUE)::NUMERIC = 1 THEN
    sInsert := COALESCE(sInsert,'') || '
      INNER JOIN COMANDA1 C1 ON C1.CODCOMANDA1 = I1.CODCMDINT1
      INNER JOIN COMANDA  C  ON C.CODCOMANDA   = C1.CODCOMANDA';
  END IF;
  sInsert := coalesce(sInsert,'') || '
        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' || COALESCE(sJoinSerii,'') || '
      WHERE i.tipdoc = 24 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)),'');
  IF current_setting('PKG_LIST_SELECTPER.vTipPer', TRUE)::NUMERIC = 1 THEN
    sInsert := COALESCE(sInsert,'') || '
        AND C.DATADOC BETWEEN TO_DATE(''' || COALESCE(current_setting('PKG_LIST_SELECTPER.vDataIni', TRUE), '') || ''', ''DD/MM/YYYY'') AND TO_DATE(''' || COALESCE(current_setting('PKG_LIST_SELECTPER.vDataFin', TRUE),'') || ''',''DD/MM/YYYY'')';
  ELSE
    sInsert := COALESCE(sInsert,'') || '
        AND l.datalivr BETWEEN TO_DATE(''' || coalesce(current_setting('PKG_LIST_SELECTPER.vDataIni', TRUE), '') || ''',''DD/MM/YYYY'') AND TO_DATE(''' || COALESCE(current_setting('PKG_LIST_SELECTPER.vDataFin', TRUE),'') || ''',''DD/MM/YYYY'')';
  END IF;
  sInsert := COALESCE(sInsert,'') || COALESCE(sFiltru,'') || '
      GROUP BY
        l1.codlivr1, i.codies, i.an, i.luna, i1.codies1, l.codlivr, l1.umsec, SIGN(l1.cant), ns.codnirstoc,l1.codnirser, ns.pret, ns.adaos, lv.pretachiz,
        lv.codioart, lv.gest, n.gest, ns.codlocatie, ns.codioart, ns.furn, ns.codgestprod, ns.tipserie, ns.d1, ns.d2, ns.d3, i1.codcmdint1),
    VALORICE AS (
      SELECT VALLINK.CODIES, VALLINK.CODLIVR1, OBJVAL.DENUMIRE
      FROM IESVALLINK VALLINK
           LEFT JOIN LIVR1   L1VAL  ON L1VAL.CODLIVR1   = VALLINK.CODLIVR1
           LEFT JOIN LIVR    LVAL   ON LVAL.CODLIVR     = L1VAL.CODLIVR
           LEFT JOIN IESIRI  IVAL   ON LVAL.CODIES      = IVAL.CODIES
           LEFT JOIN IESIRI1 I1VAL  ON I1VAL.CODIES     = IVAL.CODIES AND I1VAL.CODIES1 = L1VAL.CODIES1
           LEFT JOIN NARTOBJ OBJVAL ON OBJVAL.CODOBIECT = I1VAL.CODOBIECT
      WHERE VALLINK.CODIES1 IS NULL
    )
    SELECT
      lg.codlivr1, lg.codies,lg.codlivr,lg.codies1,lg.codioart1,lg.gest,lg.umsec,lg.codcmdint1,lg.codnirstoc,lg.codnirser,
      i.codies, i.tipdoc, i.prefixdoc, i.nrdoc, i.datadoc, i.prefixdoc||''/''||i.nrdoc||''/''||to_char(i.datadoc, ''dd.mm.yyyy'') dociesire,
      gp.den_gest, gs.den_gest, o.denumire, COALESCE(VALORICE.DENUMIRE,oc.denumire), c.simbol,cch.simbol,
      i1.pu, lg.cant, u.den_um1, i1.pu*lg.cant, lg.cantum1, lg.cantum2, u1.den_um, u2.den_um,
      pers.nume||'' ''||pers.prenume, auto.nrinreg, lg.serii, lg.serobs, lg.sercant, (Case When pc.tipreteta=1 then ''Agregare'' When pc.tipreteta=2 THEN ''Dezagregare'' END),
      ci.nrdoc, ci.datadoc, cc.nrdoc, cc.datadoc, cli.den_part,
      case when io1.mg = 3 then pkg_PMP_GET_PMP_LEI(i1.codobiect,i.subunitatea,i.an,i.luna) end,
      case when io1.mg = 3 then (SELECT pkg_PMP_GET_PMP_VALUTA_FROM_VAR.WME_RESULT FROM pkg_PMP_GET_PMP_VALUTA_FROM_VAR(NULL, NULL)) end,
      case when io1.mg = 3 then (SELECT pkg_PMP_GET_PMP_PREC_FROM_VAR.WME_RESULT FROM pkg_PMP_GET_PMP_PREC_FROM_VAR(NULL, NULL)) end,
      case when io1.mg = 3 then (SELECT pkg_PMP_GET_PMP_PREC_VALUTA_FROM_VAR.WME_RESULT FROM pkg_PMP_GET_PMP_PREC_VALUTA_FROM_VAR(NULL, NULL)) end,
      lg.PretAchiz, lg.ValAchiz'||sColTmpNP||'
    FROM lg
      LEFT JOIN iesiri      i    ON i.codies          = lg.codies
      LEFT JOIN livr        l    ON l.codlivr         = lg.codlivr
      LEFT JOIN iesiri1     i1   ON i1.codies1        = lg.codies1
      LEFT JOIN ioart1      io1  ON io1.codioart1     = lg.codioart1
      LEFT JOIN ioart       io   ON io1.codioart      = io.codioart
      LEFT JOIN ncont       c    ON c.codcont         = io1.cont
      LEFT JOIN ncont       cch  ON cch.codcont       = io1.cheltuieli
      LEFT JOIN ngest       gp   ON gp.codgest        = i.codgestprod
      LEFT JOIN ngest       gs   ON gs.codgest        = lg.gest
      LEFT JOIN nartobj     o    ON o.codobiect       = i1.codobiect
      LEFT JOIN nart        a    ON a.codarticol      = o.codarticol
      LEFT JOIN num1        u    ON u.codum1          = lg.umsec
      LEFT JOIN num         u1   ON u1.codum          = a.um1
      LEFT JOIN num         u2   ON u2.codum          = a.um2
      LEFT JOIN npers       pers ON pers.codpers      = i.codpers
      LEFT JOIN nparcaut    auto ON auto.codnparcaut  = i.codauto
      LEFT JOIN nartamb     aa   ON aa.codobiect      = i1.codobiect AND aa.umsec = i1.umsec
      LEFT JOIN iesprodlink ipl  ON ipl.codies1       = lg.codies1
      LEFT JOIN cmdprodmat  mat  ON mat.codcmdprodmat = ipl.codcmdprodmat
      LEFT JOIN cmdprodmat  prod ON prod.codcomanda1  = i1.codcmdint1 AND prod.tip = 0
      LEFT JOIN comanda1    c1   ON c1.codcomanda1    = mat.codcomanda1
      LEFT JOIN prodcomp    pc   ON pc.codprodcomp    = c1.codreteta
      LEFT JOIN nartobj     oc   ON oc.codobiect      = prod.codobiect
      LEFT JOIN VALORICE         ON VALORICE.CODIES   = I1.CODIES AND VALORICE.CODLIVR1 = I1.CODLIVR1PRODVAL '
      ||sJoinNP||'
--      LEFT JOIN (select
--                   CASE
--                     WHEN COALESCE(ns.tipserie,0) &lt;&gt; 0 THEN STRING_AGG(s.serie||''(''||trunc(nse.cantnir)||'')'', '''')
--                   END serii,
--                   i1.codcmdint1,
--                   i1.codobiect
--                 from intrari1 i1
--                      inner join intrari i   on i1.codintr     = i.codintr
--                      inner join nirstoc ns  on ns.codintr1    = i1.codintr1
--                      inner join nirser  nse on nse.codnirstoc = ns.codnirstoc
--                      inner join nserii  s   on nse.codserie   = s.codserie
--                 where COALESCE(i.anulat,0) = 0 and i.operat = 1 and i.tipdoc = 7
--                 group by i1.codcmdint1, i1.codobiect, ns.tipserie
--                ) SER_NP on ser_np.codcmdint1 = lg.codcmdint1 and ser_np.codobiect = oc.codobiect
--      LEFT JOIN (select
--                   STRING_AGG(i.nrdoc::VARCHAR, '''') nrdocs,
--                   i1.codcmdint1,
--                   i1.codobiect
--                 from intrari1 i1
--                      inner join intrari i on i1.codintr = i.codintr
--                 where COALESCE(i.anulat,0) = 0 and i.operat = 1 and i.tipdoc = 7
--                 group by i1.codcmdint1, i1.codobiect
--                ) NR_NP on nr_np.codcmdint1 = lg.codcmdint1 and nr_np.codobiect = oc.codobiect
      LEFT JOIN comanda1   ci1   ON ci1.codcomanda1  = i1.codcmdint1
      LEFT JOIN comanda    ci    ON ci.codcomanda    = ci1.codcomanda
      LEFT JOIN cmdlink    cl    ON cl.codcomanda1   = ci1.codcomanda1
      LEFT JOIN comanda1   cc1   ON cc1.codcomanda1  = cl.codliniecomanda
      LEFT JOIN comanda    cc    ON cc.codcomanda    = cc1.codcomanda
      LEFT JOIN npart      cli   ON cli.codpart      = cc.partener
      LEFT JOIN nirstoc          ON lg.codnirstoc    = nirstoc.codnirstoc
      LEFT JOIN nclasea    ca    ON ca.codclasea     = a.clasa
      LEFT JOIN nirser     nse   ON nse.codnirser    = lg.codnirser
      LEFT JOIN nserii     ser   ON nse.codserie     = ser.codserie
      LEFT JOIN centrecost cco   on i1.codcentru     = cco.codcentru
      LEFT JOIN LANSARE1   LANS1 ON LANS1.CODCMD1    = CI1.CODCOMANDA1
      LEFT JOIN LANSARE    LANS  ON LANS1.CODLANSARE = LANS.CODLANSARE
    where lg.cant &lt;&gt; 0';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  sInsert := 'INSERT INTO ' || TMPNAME || ' (
      NAV_CodDoc,NAV_TipDoc,PREFIXDOC,NRDOC,DATADOC,DOCIESIRE,
      GEST_PROD,GEST_SURSA, DENUMIRE,PRODUS,CONT,CHELTUIELI,
      PU,CANT,UM,VALOARE, CANTUM1, CANTUM2, UM1, UM2,
      PERS, MASINA, SERII, SEROBS, SERCANT, TIPRETETA,
      NRCI, DATACI, NRCC, DATACC, CLIENT,
      PMP, PMPVALUTA, PMPPREC, PMPPRECVAL, PRETACHIZ, VALACHIZ, SERIIPROD, NRNP ' || gUserFields || ' )
    WITH
    VALORICE AS (
      SELECT VALLINK.CODIES, VALLINK.CODLIVR1, OBJVAL.DENUMIRE
      FROM IESVALLINK VALLINK
           LEFT JOIN LIVR1   L1VAL  ON L1VAL.CODLIVR1   = VALLINK.CODLIVR1
           LEFT JOIN LIVR    LVAL   ON LVAL.CODLIVR     = L1VAL.CODLIVR
           LEFT JOIN IESIRI  IVAL   ON LVAL.CODIES      = IVAL.CODIES
           LEFT JOIN IESIRI1 I1VAL  ON I1VAL.CODIES     = IVAL.CODIES AND I1VAL.CODIES1 = L1VAL.CODIES1
           LEFT JOIN NARTOBJ OBJVAL ON OBJVAL.CODOBIECT = I1VAL.CODOBIECT
      WHERE VALLINK.CODIES1 IS NULL
    )
    SELECT
      i.codies, i.tipdoc, i.prefixdoc, i.nrdoc, i.datadoc, i.prefixdoc||''/''||i.nrdoc||''/''||to_char(i.datadoc, ''dd.mm.yyyy'') dociesire,
      gp.den_gest, gs.den_gest, o.denumire, COALESCE(VALORICE.DENUMIRE,oc.denumire), c.simbol,cch.simbol,
      i1.pu*u.paritate, TMP.cant/u.paritate, u.den_um1, i1.pu*TMP.cant, TMP.cantum1, TMP.cantum2, u1.den_um, u2.den_um,
      pers.nume||'' ''||pers.prenume, auto.nrinreg, TMP.serii, TMP.serobs, TMP.sercant, (Case When pc.tipreteta=1 then ''Agregare'' When pc.tipreteta=2 THEN ''Dezagregare'' END),
      ci.nrdoc, ci.datadoc, cc.nrdoc, cc.datadoc, cli.den_part,
      case when io1.mg = 3 then pkg_PMP_GET_PMP_LEI(i1.codobiect,i.subunitatea,i.an,i.luna) end,
      case when io1.mg = 3 then (SELECT pkg_PMP_GET_PMP_VALUTA_FROM_VAR.WME_RESULT FROM pkg_PMP_GET_PMP_VALUTA_FROM_VAR(NULL, NULL)) end,
      case when io1.mg = 3 then (SELECT pkg_PMP_GET_PMP_PREC_FROM_VAR.WME_RESULT FROM pkg_PMP_GET_PMP_PREC_FROM_VAR(NULL, NULL)) end,
      case when io1.mg = 3 then (SELECT pkg_PMP_GET_PMP_PREC_VALUTA_FROM_VAR.WME_RESULT FROM pkg_PMP_GET_PMP_PREC_VALUTA_FROM_VAR(NULL, NULL)) end,
      TMP.PretAchiz, TMP.ValAchiz '||sColNP || gUserAlias || '
    FROM TMP_LST_SITCONSUM TMP
      LEFT JOIN iesiri      i    ON i.codies          = TMP.codies
      LEFT JOIN livr        l    ON l.codlivr         = TMP.codlivr
      LEFT JOIN livr1       l1   ON l1.codlivr1       = TMP.codlivr1
      LEFT JOIN iesiri1     i1   ON i1.codies1        = TMP.codies1
      LEFT JOIN ioart1      io1  ON io1.codioart1     = TMP.codioart1
      LEFT JOIN ioart       io   ON io1.codioart      = io.codioart
      LEFT JOIN ncont       c    ON c.codcont         = io1.cont
      LEFT JOIN ncont       cch  ON cch.codcont       = io1.cheltuieli
      LEFT JOIN ngest       gp   ON gp.codgest        = i.codgestprod
      LEFT JOIN ngest       gs   ON gs.codgest        = TMP.gest
      LEFT JOIN nartobj     o    ON o.codobiect       = i1.codobiect
      LEFT JOIN nart        a    ON a.codarticol      = o.codarticol
      LEFT JOIN num1        u    ON u.codum1          = TMP.umsec
      LEFT JOIN num         u1   ON u1.codum          = a.um1
      LEFT JOIN num         u2   ON u2.codum          = a.um2
      LEFT JOIN npers       pers ON pers.codpers      = i.codpers
      LEFT JOIN nparcaut    auto ON auto.codnparcaut  = i.codauto
      LEFT JOIN nartamb     aa   ON aa.codobiect      = i1.codobiect AND aa.umsec = i1.umsec
      LEFT JOIN iesprodlink ipl  ON ipl.codies1       = TMP.codies1
      LEFT JOIN cmdprodmat  mat  ON mat.codcmdprodmat = ipl.codcmdprodmat
      LEFT JOIN cmdprodmat  prod ON prod.codcomanda1  = i1.codcmdint1 AND prod.tip = 0
      LEFT JOIN comanda1    c1   ON c1.codcomanda1    = mat.codcomanda1
      LEFT JOIN prodcomp    pc   ON pc.codprodcomp    = c1.codreteta
      LEFT JOIN nartobj     oc   ON oc.codobiect      = prod.codobiect
      LEFT JOIN VALORICE         ON VALORICE.CODIES   = I1.CODIES AND VALORICE.CODLIVR1 = I1.CODLIVR1PRODVAL
--      LEFT JOIN (select
--                   CASE
--                     WHEN COALESCE(ns.tipserie,0) &lt;&gt; 0 THEN STRING_AGG(s.serie||''(''||trunc(nse.cantnir)||'')'', '''')
--                   END serii,
--                   i1.codcmdint1,
--                   i1.codobiect
--                 from intrari1 i1
--                      inner join intrari i   on i1.codintr     = i.codintr
--                      inner join nirstoc ns  on ns.codintr1    = i1.codintr1
--                      inner join nirser  nse on nse.codnirstoc = ns.codnirstoc
--                      inner join nserii  s   on nse.codserie   = s.codserie
--                 where COALESCE(i.anulat,0) = 0 and i.operat = 1 and i.tipdoc = 7
--                 group by i1.codcmdint1, i1.codobiect, ns.tipserie
--                ) SER_NP on ser_np.codcmdint1 = lg.codcmdint1 and ser_np.codobiect = oc.codobiect
--      LEFT JOIN (select
--                   STRING_AGG(i.nrdoc::VARCHAR, '''') nrdocs,
--                   i1.codcmdint1,
--                   i1.codobiect
--                 from intrari1 i1
--                      inner join intrari i on i1.codintr = i.codintr
--                 where COALESCE(i.anulat,0) = 0 and i.operat = 1 and i.tipdoc = 7
--                 group by i1.codcmdint1, i1.codobiect
--                ) NR_NP on nr_np.codcmdint1 = lg.codcmdint1 and nr_np.codobiect = oc.codobiect
      LEFT JOIN comanda1   ci1   ON ci1.codcomanda1  = i1.codcmdint1
      LEFT JOIN comanda    ci    ON ci.codcomanda    = ci1.codcomanda
      LEFT JOIN cmdlink    cl    ON cl.codcomanda1   = ci1.codcomanda1
      LEFT JOIN comanda1   cc1   ON cc1.codcomanda1  = cl.codliniecomanda
      LEFT JOIN comanda    cc    ON cc.codcomanda    = cc1.codcomanda
      LEFT JOIN npart      cli   ON cli.codpart      = cc.partener
      LEFT JOIN nirstoc          ON TMP.codnirstoc   = nirstoc.codnirstoc
      LEFT JOIN nclasea    ca    ON ca.codclasea     = a.clasa
      LEFT JOIN nirser     nse   ON nse.codnirser    = TMP.codnirser
      LEFT JOIN nserii     ser   ON nse.codserie     = ser.codserie
      LEFT JOIN centrecost cco   on i1.codcentru     = cco.codcentru
      LEFT JOIN LANSARE1   LANS1 ON LANS1.CODCMD1    = CI1.CODCOMANDA1
      LEFT JOIN LANSARE    LANS  ON LANS1.CODLANSARE = LANS.CODLANSARE' || gSuplJoins || '
    where TMP.cant &lt;&gt; 0';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  IF current_setting('PKG_LIST_SELECTPER.vTipPer', TRUE)::NUMERIC = 1 THEN
    DELETE FROM TMP_LST_SITCONSUM;
    sInsert := 'INSERT INTO TMP_LST_SITCONSUM (
      codcmdint1,
      NAV_CodDoc,NAV_TipDoc,
      GEST_PROD,DENUMIRE,PRODUS,
      TIPRETETA,
      NRCI, DATACI, NRCC, DATACC, CLIENT,
      SERIIPROD, NRNP)
    SELECT
      ci1.codcomanda1,
      ci.codcomanda, ci.tipdoc,
      gp.den_gest, o.denumire, oc.denumire,
     (Case When pc.tipreteta=1 then ''Agregare'' When pc.tipreteta=2 THEN ''Dezagregare'' END),
      ci.nrdoc, ci.datadoc, cc.nrdoc, cc.datadoc, cli.den_part'||sColTmpNP||'
    FROM comanda ci
      INNER JOIN comanda1   ci1  ON ci.codcomanda    = ci1.codcomanda
      inner join cmdprodmat mat  on mat.codcomanda1  = ci1.codcomanda1 and mat.tip = 1
      inner join cmdprodmat prod on prod.codcomanda1 = ci1.codcomanda1 and prod.tip = 0
      inner JOIN nartobj    o    ON o.codobiect      = mat.codobiect
      inner JOIN nartobj    oc   ON oc.codobiect     = prod.codobiect
      inner JOIN nart       a    ON a.codarticol     = o.codarticol
      inner JOIN num1       u    ON u.codum1         = a.um and coalesce(u.secundara,0) = 0
      inner JOIN prodcomp   pc   ON pc.codprodcomp   = ci1.codreteta
      LEFT  JOIN iesiri1    i1   ON i1.codcmdint1    = ci1.codcomanda1
      LEFT  JOIN ngest      gp   ON gp.codgest       = ci.codgest
      LEFT  JOIN num        u1   ON u1.codum         = a.um1
      LEFT  JOIN num        u2   ON u2.codum         = a.um2
      LEFT  JOIN nartamb    aa   ON aa.codobiect     = o.codobiect AND aa.umsec = u.codum1 ';
    IF COALESCE(NULLIF(current_setting('PKG_LIST_SELECTPER.bInfoNP' , TRUE),'')::NUMERIC,0) = 1 THEN
      sInsert := sInsert || '
      LEFT JOIN (select
                   CASE
                     WHEN COALESCE(ns.tipserie,0) &lt;&gt; 0 THEN fnc_array_to_string_sum(array_agg(s.serie||''(~#''||nse.cantnir||''#~)'' order by s.serie) )  --STRING_AGG(s.serie||''(''||trunc(nse.cantnir)||'')'', '''')
                   END serii,
                   i1.codcmdint1,
                   i1.codobiect
                 from intrari1 i1
                      inner join intrari i   on i1.codintr     = i.codintr
                      inner join nirstoc ns  on ns.codintr1    = i1.codintr1
                      inner join nirser  nse on nse.codnirstoc = ns.codnirstoc
                      inner join nserii  s   on nse.codserie   = s.codserie
                 where COALESCE(i.anulat,0) = 0 and i.operat = 1 and i.tipdoc = 7
                 group by i1.codcmdint1, i1.codobiect, ns.tipserie
                ) SER_NP on ser_np.codcmdint1 = ci1.codcomanda1 and ser_np.codobiect = prod.codobiect
      LEFT JOIN (select
                   fnc_array_to_vc3200(array_agg(i.nrdoc::varchar order by i.nrdoc)) nrdocs,  --STRING_AGG(i.nrdoc::VARCHAR, '''') nrdocs,
                   i1.codcmdint1,
                   i1.codobiect
                 from intrari1 i1
                      inner join intrari i on i1.codintr = i.codintr
                 where COALESCE(i.anulat,0) = 0 and i.operat = 1 and i.tipdoc = 7
                 group by i1.codcmdint1, i1.codobiect
                ) NR_NP on nr_np.codcmdint1 = ci1.codcomanda1 and nr_np.codobiect = mat.codobiect
      ';
    END IF;
    sInsert := sInsert || '
      LEFT JOIN cmdlink  cl    ON cl.codcomanda1   = ci1.codcomanda1
      LEFT JOIN comanda1 cc1   ON cc1.codcomanda1  = cl.codliniecomanda
      LEFT JOIN comanda  cc    ON cc.codcomanda    = cc1.codcomanda
      LEFT JOIN npart    cli   ON cli.codpart      = cc.partener
      LEFT JOIN nclasea  ca    ON ca.codclasea     = a.clasa
      LEFT JOIN LANSARE1 LANS1 ON LANS1.CODCMD1    = CI1.CODCOMANDA1
      LEFT JOIN LANSARE  LANS  ON LANS1.CODLANSARE = LANS.CODLANSARE
    where i1.codies1 is null ' || COALESCE((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'CI',NULL,NULL,NULL)),'') || '
       and CI.DATADOC BETWEEN TO_DATE(''' || COALESCE(current_setting('PKG_LIST_SELECTPER.vDataIni', TRUE),'') || ''',''DD/MM/YYYY'') AND TO_DATE('''
          || COALESCE(current_setting('PKG_LIST_SELECTPER.vDataFin', TRUE),'') || ''',''DD/MM/YYYY'')';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

    sInsert := 'INSERT INTO ' || TMPNAME || ' (
      NAV_CodDoc,NAV_TipDoc,PREFIXDOC,NRDOC,DATADOC,DOCIESIRE,
      GEST_PROD,GEST_SURSA, DENUMIRE,PRODUS,CONT,CHELTUIELI,
      PU,CANT,UM,VALOARE, CANTUM1, CANTUM2, UM1, UM2,
      PERS, MASINA, SERII, SEROBS, SERCANT, TIPRETETA,
      NRCI, DATACI, NRCC, DATACC, CLIENT,
      PMP, PMPVALUTA, PMPPREC, PMPPRECVAL, SERIIPROD, NRNP ' || gUserFields || ' )
    SELECT
      i.codies, i.tipdoc, i.prefixdoc, i.nrdoc, i.datadoc, i.prefixdoc||''/''||i.nrdoc||''/''||to_char(i.datadoc, ''dd.mm.yyyy'') dociesire,
      gp.den_gest, gs.den_gest, o.denumire, oc.denumire, c.simbol,cch.simbol,
      i1.pu*u.paritate, 0, u.den_um1, 0, 0, 0, u1.den_um, u2.den_um,
      pers.nume||'' ''||pers.prenume, auto.nrinreg, null, null, null, (Case When pc.tipreteta=1 then ''Agregare'' When pc.tipreteta=2 THEN ''Dezagregare'' END),
      ci.nrdoc, ci.datadoc, cc.nrdoc, cc.datadoc, cli.den_part,
      case when io1.mg = 3 then pkg_PMP_GET_PMP_LEI(i1.codobiect,i.subunitatea,i.an,i.luna) end,
      case when io1.mg = 3 then (SELECT pkg_PMP_GET_PMP_VALUTA_FROM_VAR.WME_RESULT FROM pkg_PMP_GET_PMP_VALUTA_FROM_VAR(NULL, NULL)) end,
      case when io1.mg = 3 then (SELECT pkg_PMP_GET_PMP_PREC_FROM_VAR.WME_RESULT FROM pkg_PMP_GET_PMP_PREC_FROM_VAR(NULL, NULL)) end,
      case when io1.mg = 3 then (SELECT pkg_PMP_GET_PMP_PREC_VALUTA_FROM_VAR.WME_RESULT FROM pkg_PMP_GET_PMP_PREC_VALUTA_FROM_VAR(NULL, NULL)) end '||sColNP || gUserAlias || '
    FROM TMP_LST_SITCONSUM TMP
      INNER JOIN comanda1    ci1   ON ci1.codcomanda1  = tmp.codcmdint1
      INNER JOIN comanda     ci    ON ci.codcomanda    = ci1.codcomanda
      INNER JOIN cmdprodmat  mat   ON mat.codcomanda1  = ci1.codcomanda1 and mat.tip = 1
      INNER JOIN cmdprodmat  prod  ON prod.codcomanda1 = ci1.codcomanda1 AND prod.tip = 0
      INNER JOIN ngest       gp    ON gp.codgest       = ci.codgest
      INNER JOIN nartobj     o     ON o.codobiect      = mat.codobiect
      INNER JOIN nart        a     ON a.codarticol     = o.codarticol
      INNER JOIN num1        u     ON u.codum          = a.um and coalesce(u.secundara,0) = 0
      LEFT  JOIN iesiri1     i1    ON i1.codcmdint1    = tmp.codcmdint1
      LEFT  JOIN iesiri      i     ON i.codies         = i1.codies
      LEFT  JOIN livr        l     ON l.codies         = i.codies
      LEFT  JOIN ioart1      io1   ON io1.codioart1    = tmp.codcmdint1 - tmp.codcmdint1
      LEFT  JOIN ioart       io    ON io1.codioart     = tmp.codcmdint1 - tmp.codcmdint1
      LEFT  JOIN ncont       c     ON c.codcont        = tmp.codcmdint1 - tmp.codcmdint1
      LEFT  JOIN ncont       cch   ON cch.codcont      = tmp.codcmdint1 - tmp.codcmdint1
      LEFT  JOIN ngest       gs    ON gs.codgest       = i.codgestprod
      LEFT  JOIN num         u1    ON u1.codum         = a.um1
      LEFT  JOIN num         u2    ON u2.codum         = a.um2
      LEFT  JOIN npers       pers  ON pers.codpers     = i.codpers
      LEFT  JOIN nparcaut    auto  ON auto.codnparcaut = i.codauto
      LEFT  JOIN nartamb     aa    ON aa.codobiect     = mat.codobiect AND aa.umsec = u.codum1
      LEFT  JOIN iesprodlink ipl   ON ipl.codies1      = tmp.codies1
      LEFT  JOIN prodcomp    pc    ON pc.codprodcomp   = ci1.codreteta
      LEFT  JOIN nartobj     oc    ON oc.codobiect     = prod.codobiect
      LEFT  JOIN cmdlink     cl    ON cl.codcomanda1   = ci1.codcomanda1
      LEFT  JOIN comanda1    cc1   ON cc1.codcomanda1  = cl.codliniecomanda
      LEFT  JOIN comanda     cc    ON cc.codcomanda    = cc1.codcomanda
      LEFT  JOIN npart       cli   ON cli.codpart      = cc.partener
      LEFT  JOIN nirstoc           ON tmp.codnirstoc   = nirstoc.codnirstoc
      LEFT  JOIN nclasea     ca    ON ca.codclasea     = a.clasa
      LEFT  JOIN nirser      nse   ON nse.codnirser    = tmp.codnirser
      LEFT  JOIN nserii      ser   ON nse.codserie     = ser.codserie
      LEFT  JOIN centrecost  cco   on i1.codcentru     = cco.codcentru
      LEFT  JOIN LANSARE1    LANS1 ON LANS1.CODCMD1    = CI1.CODCOMANDA1
      LEFT  JOIN LANSARE     LANS  ON LANS1.CODLANSARE = LANS.CODLANSARE' || gSuplJoins || '
    where i1.codies1 is null ';
    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_sitimob_setjoinuri</obj_name>
  <obj_hashval>7a33ec53630b85ff350494273424b714</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitimob_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 15.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec (current_setting ('PKG_LIST_BASE_SITIMOB.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitpen_setjoinuri</obj_name>
  <obj_hashval>8f35be690a286b059d3cc2e1b2b0b8a8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitpen_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_SITPEN.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_soldpart_setgnullalias</obj_name>
  <obj_hashval>6eebc22672249e20b19aee91b6b25042</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_soldpart_setgnullalias(agnullalias character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_SOLDPART.gNullAlias',agNullAlias,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_vtoatafirma</obj_name>
  <obj_hashval>b7afcbffd68a0e376daa88035042d2f7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_vtoatafirma(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.vToataFirma'));
  RETURN ;
  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_taskuri_setjoinuri</obj_name>
  <obj_hashval>8fa1f96cd5a5f261b305d4b8a9e524bb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_taskuri_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 11 septembrie 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_TASKURI.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_tehprod_setallparams</obj_name>
  <obj_hashval>62c45e466c06e045a38a766447818105</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_tehprod_setallparams(v_flgallart numeric, v_sursa numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 14.09.2020
  perform set_config ('PKG_LIST_BASE_TEHPROD.p_flgAllArt',v_flgAllArt::varchar,false);
  perform set_config ('PKG_LIST_BASE_TEHPROD.p_Sursa'    ,v_Sursa::varchar    ,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topart_processlist</obj_name>
  <obj_hashval>fafc56743a0f7001b22992064ed8b628</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topart_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sInsert1    varchar;
  sUpdate     varchar;
  sOrdine     varchar;
  sMoneda     varchar;
  aSitV       numeric;
  aBancaV     numeric;
  aMonedaV    numeric;
  sCurs       varchar;
  sCod        varchar;
  aUserID     numeric;
  vALIni      numeric;
  vALFin      numeric;
  sFurn       varchar := '0 CODFURN, 0 TIPFURN,';
  sJoinFurn   varchar := '';
  sArtAtrib1  varchar := ', NULL ARTATRIB1';
  sFiltruObj  varchar := '';
  gSuplCols   varchar := 'NARTOBJ NAO, NUM NUM, NART NART, NCLASEA CLSA, NCLASEAS CLSAS';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  wmeRes      boolean;
BEGIN
  --Florin 20.11.2025 - sinc. Oracle
  --Florin 08.10.2024 - sinc. Oracle
  --Florin 17.11.2022 - sinc. Oracle
  --Florin 28.04.2022 - sinc. Oracle (27.04.2022)
  --Florin 08.03.2022 - sinc. Oracle (53391)
  --Florin 18.10.2021 - sinc. Oracle (14-15.10)
  --Adina 19.02.2021 - GetInfoSitValuta
  --Adina 03.02.2021 tichet 42698
  --Stef 21.12.2020 PKG_LIST_BASE_UTILS_GetCoefDiscMonetar
  --Florin 01.09.2020

  IF (CASE WHEN current_setting('PKG_LIST_BASE_TOPART.vCodAtribut', TRUE) = '' THEN NULL
           ELSE current_setting('PKG_LIST_BASE_TOPART.vCodAtribut', TRUE)::NUMERIC END) &gt; 0
  THEN
    sArtAtrib1 := ',
      ( SELECT Min(aa1.valoare)
        FROM nartatr aa
          LEFT JOIN natrobj ao  ON ao.codartatr  = aa.codartatr
          LEFT JOIN natrib1 aa1 ON aa1.codvalatr = ao.codvalatr
        WHERE aa.codarticol = nao.codarticol AND ao.codobiect = nao.codobiect AND aa.codatribut = ' || coalesce(current_setting('PKG_LIST_BASE_TOPART.vCodAtribut', true)::numeric::varchar ,'') || '
      ) ARTATRIB1';
    sFiltruObj := ' and exists (select aa.codatribut from nartatr aa where aa.codarticol = nao.codarticol AND aa.codatribut = ' || coalesce(current_setting('PKG_LIST_BASE_TOPART.vCodAtribut', true)::numeric::varchar ,'') || ') ';
  END IF;

  vALIni := EXTRACT(YEAR FROM To_Date(current_setting('PKG_LIST_BASE_TOPART.vDataIni', true), 'DD.MM.YYYY')) * 12 + EXTRACT(MONTH FROM To_Date(current_setting('PKG_LIST_BASE_TOPART.vDataIni', true), 'DD.MM.YYYY'));
  vALFin := EXTRACT(YEAR FROM To_Date(current_setting('PKG_LIST_BASE_TOPART.vDataFin', true), 'DD.MM.YYYY')) * 12 + EXTRACT(MONTH FROM To_Date(current_setting('PKG_LIST_BASE_TOPART.vDataFin', true), 'DD.MM.YYYY'));

  IF current_setting('PKG_LIST_BASE_TOPART.vDocType', true)::numeric = 1 THEN
    sCod := ', 26';
  ELSE
    sCod := ', 20';
  END IF;

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

  aUserID := GETUSERID();

  DELETE from TMP_ANLUNA_VAL;
  DELETE from TMP_LST_TOPART;
  DELETE from TMP_CMD WHERE USERID = aUserID;

  --folosesc tmp_cmd pentru cursorul de valachiz de stingeri la nedescarcate
  insert into tmp_cmd(codobiect,cantc,canta,userid, auxfield)
  SELECT II1.CODIES1, SUM(LL1.CANT * (NS.PRET - Coalesce(NS.ADAOS,0))) VAL, sum(LL1.cant), aUserID, string_agg(P.DEN_PART, '')
  FROM IESIRI1 I1
    INNER JOIN IESIRI     I   ON I.CODIES       = I1.CODIES
    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
    LEFT  JOIN NPART        P ON P.CODPART      = NS.FURN
  WHERE I.ANULAT = 0 AND I.DATADOC BETWEEN To_Date(current_setting('PKG_LIST_BASE_TOPART.vdataIni', true),'DD.MM.YYYY') AND To_Date(current_setting('PKG_LIST_BASE_TOPART.vdataFin', true) ,'DD.MM.YYYY')
        AND (GETSUBUNITATE() = 1 OR GETSUBUNITATE() = I.SUBUNITATEA)
  GROUP BY II1.CODIES1;

 INSERT INTO TMP_ANLUNA_VAL(AL, VALOARE)
 (WITH RECURSIVE aa AS
                (
                  SELECT vALIni An,  Coalesce((select wme_result from pkg_categconst_GetValConstanta(null, 'ContIncasareFactura' , 0, vALIni - 1))::numeric,-1) Valoare
                  UNION ALL
                  SELECT aa.An + 1, Coalesce((select wme_result from pkg_categconst_GetValConstanta(null, 'ContIncasareFactura' , 0, aa.An + 1))::numeric,-1) Valoare FROM aa WHERE aa.An &lt; vALFin
                )
                SELECT An, Valoare FROM aa
               );

  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 current_setting('PKG_LIST_BASE_TOPART.vSortType', true)::numeric IN (3, 5) AND wmeRes    THEN
    sCurs   := ' (SELECT PKG_LIST_BASE_UTILS_GETCURSREFERINTA.wme_result FROM PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, ' || coalesce(aMonedaV,0) || ',' || coalesce(aBancaV,0) || ', to_char(i.datadoc,''dd.mm.yyyy'')))';
    sMoneda := (SELECT pkg_monede_get_simbol_moneda.WME_RESULT FROM pkg_monede_get_simbol_moneda(NULL,aMonedaV));
  ELSE
    sCurs := '1';
    sMoneda := (SELECT pkg_monede_get_simbol_moneda.WME_RESULT FROM pkg_monede_get_simbol_moneda(NULL,0));
  END IF;

  sOrdine := CASE current_setting('PKG_LIST_BASE_TOPART.vSortType', true)::numeric
   WHEN 1 THEN 'T.CANT'
   WHEN 2 THEN 'T.VALLEI'
   WHEN 3 THEN 'T.VALLEI/T.CURS'
   WHEN 4 THEN 'T.VALADAOSLEI'
   WHEN 5 THEN 'T.VALADAOSLEI/T.CURS'
   END;

  IF current_setting('PKG_LIST_BASE_TOPART.vPeFurn', true)::boolean THEN
    sFurn := '
        CASE
          WHEN COALESCE(NS_ROOT.CODGESTPROD ,0) &lt;&gt; 0 THEN NS_ROOT.CODGESTPROD
          WHEN COALESCE(NS_ROOT.FURN ,0) &lt;&gt; 0        THEN NS_ROOT.FURN
          WHEN COALESCE(I_ROOT.TIPDOC, 0)= 7         THEN I_ROOT.CODGESTPROD
          ELSE COALESCE(I_ROOT.PARTENER, 0)
        END CODFURN,
        CASE
          WHEN COALESCE(NS_ROOT.CODGESTPROD ,0) &lt;&gt; 0 THEN 1
          WHEN COALESCE(NS_ROOT.FURN ,0) &lt;&gt; 0        THEN 0
          WHEN COALESCE(I_ROOT.TIPDOC, 0)= 7         THEN 1
          ELSE 0
        END TIPFURN,';
    sJoinFurn := '
        LEFT  JOIN NIRSTOC1 NS1     ON NS1.CODNIRSTOC     = L1.CODNIRSTOC
        LEFT  JOIN NIRSTOC  NS_ROOT ON NS_ROOT.CODNIRSTOC = NS1.CODNIRSTOCORIG
        LEFT  JOIN INTRARI1 I1_ROOT ON I1_ROOT.CODINTR1   = NS_ROOT.CODINTR1
        LEFT  JOIN INTRARI  I_ROOT  ON I_ROOT.CODINTR     = I1_ROOT.CODINTR';
  END IF;

  PERFORM set_config('PKG_LIST_BASE_TOPART.vCondData', 'BETWEEN TO_DATE (''' || current_setting('PKG_LIST_BASE_TOPART.vDataIni', true) || ''',''DD.MM.YYYY'')
                                                            AND TO_DATE (''' || current_setting('PKG_LIST_BASE_TOPART.vDataFin', true) || ''',''DD.MM.YYYY'')', FALSE);

  sInsert := 'INSERT INTO ' || tmpName || '(
      CodObiect, DenArt, DenUM, Valuta, Cant, DenFurn, CodExtern, CodIntern, Producator,
      PretLei, ValoareLei, ValAdaosLei, PretAchLei, AdaosLei, ProcAdaosLei,
      PretVal, ValoareVal, ValAdaosVal, PretAchVal, AdaosVal, ProcAdaosVal,
      Ordine,Doc,Subunitatea,ArtAtrib1' || gUserFields || ')
    SELECT
      NAO.CodObiect, NAO.DENUMIRE, NUM.DEN_UM, ''' || coalesce(sMoneda,'') || ''', T.CANT, COALESCE(FURN.DEN_PART, GPROD.DEN_GEST) DENFURN, NAO.CODEXTERN, NAO.CODINTERN, PROD.DEN_PART PRODUCATOR,
      T.VALLEI/T.CANT       , T.VALLEI       , T.VALADAOSLEI       , T.VALACHLEI/T.CANT       , T.VALADAOSLEI/T.CANT       , (Case When T.VALACHLEI=0 then 0 else T.VALLEI*100/T.VALACHLEI - 100 end),
      T.VALLEI/T.CANT/T.CURS, T.VALLEI/T.CURS, T.VALADAOSLEI/T.CURS, T.VALACHLEI/T.CANT/T.CURS, T.VALADAOSLEI/T.CANT/T.CURS, (Case When T.VALACHLEI=0 then 0 else T.VALLEI*100/T.VALACHLEI - 100 end),
      ' || coalesce(sOrdine,'') || ' Ordine,T.DOC,T.SUBUNITATEA' || coalesce(sArtAtrib1,'') || gUserAlias || '
     FROM TMP_LST_TOPART T
      LEFT JOIN NPART    FURN  ON FURN.CODPART      = T.CODFURN AND T.TIPFURN = 0
      LEFT JOIN NGEST    GPROD ON GPROD.CODGEST     = T.CODFURN AND T.TIPFURN = 1
      LEFT JOIN NARTOBJ  NAO   ON NAO.CODOBIECT     = T.CODOBIECT
      LEFT JOIN NPART    PROD  ON PROD.CODPART      = NAO.CODPRODUCATOR
      LEFT JOIN NART     NART  ON NART.CODARTICOL   = NAO.CODARTICOL
      LEFT JOIN NUM      NUM   ON NART.UM           = NUM.CODUM
      LEFT JOIN NCLASEA  CLSA  ON NART.Clasa        = CLSA.CodClaseA
      LEFT JOIN NCLASEAS CLSAS ON NART.ClasaStatist = CLSAS.CodClaseAS' || gSuplJoins || '
  WHERE T.CANT &lt;&gt; 0 AND Coalesce(NART.TIPARTICOL,''0'')::numeric = T.TIPARTICOL::numeric'||sFiltruObj;

  sInsert1 := 'INSERT INTO TMP_LST_TOPART(tiparticol,codobiect,codfurn,tipfurn,cant,valachlei,vallei,tvalei,datadoc,doc,subunitatea,curs)
      SELECT
        ''0'' TIPARTICOL, I1.CODOBIECT,' || coalesce(sFurn,'') || '
        L1.CANT,
        CASE
      WHEN Coalesce(L1.codnirstoc, 0) &lt;&gt; 0 then (NS.PRET - NS.ADAOS) * L1.CANT
      ELSE coalesce(LV.PretAchiz,0) * L1.RestIesVal + COALESCE(ST.CANTC,0)
        END VALACHLEI,
        CASE WHEN i1.pu*i1.cant = 0 THEN 0 ELSE (i1.pu*i1.cant-CASE WHEN i.tipdoc = 21 THEN i1.Tva ELSE 0 END)*CASE WHEN Coalesce(G.CURS,0)= 0 THEN 1 ELSE G.CURS END*Coalesce(i1.coefdiscmaj,1)*i1.pretorig*l1.cant/i1.pu/i1.cant END VALLEI,
        CASE WHEN i1.pu*i1.cant = 0 THEN 0 ELSE i1.Tva                                                        *CASE WHEN Coalesce(G.CURS,0)= 0 THEN 1 ELSE G.CURS END*Coalesce(i1.coefdiscmaj,1)*i1.pretorig*l1.cant/i1.pu/i1.cant END TVALEI,
        I.DATADOC, I.PREFIXDOC||'' ''||I.NRDOC||''/''||TO_CHAR(I.DATADOC,''DD.MM.YYYY'') DOC, S.DEN_SUBUNIT SUBUNITATEA,
        '||sCurs||'
      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.CODLIVR    = L.CODLIVR AND L1.CODIES1 = I1.CODIES1
        INNER JOIN NSUBUNIT S  ON S.CODSUBUNIT  = I.SUBUNITATEA
        LEFT  JOIN GENERAL  G  ON G.TIPDOC      = I.TIPDOC AND G.CODDOC = I.CODIES AND G.SEMNIFICATIE &lt;&gt; 210 AND G.SEMNIFICATIE &lt;&gt; 211
        LEFT  JOIN NIRSTOC  NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
    LEFT  JOIN LIVRVAL LV ON LV.CodLivr1 = L1.CodLivr1
        LEFT  JOIN TMP_CMD ST ON ST.CODOBIECT = I1.CODIES1 AND ST.USERID = '||aUserID||chr(13)||
        sJoinFurn||'
      WHERE I.DATADOC ' || coalesce(current_setting('PKG_LIST_BASE_TOPART.vCondData', true),'')
      || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || ' AND Coalesce(I.INFOCM,0) = 0
        AND NOT I.TIPDOC IN (14, 15, 16, 23, 24'||sCod||')
        AND Coalesce(I.ANULAT,0) = 0
        AND I1.TIPLINIE = ''=''
      UNION ALL
      SELECT
        ''0'' TIPARTICOL, I1.CODOBIECT,'
    ||sFurn||
        'L1.CANT CANT,
        case
      WHEN Coalesce(L1.codnirstoc, 0) &lt;&gt; 0 then (NS.PRET - NS.ADAOS) * L1.CANT
           ELSE coalesce(LV.PretAchiz,0) * L1.RestIesVal + COALESCE(ST.CANTC,0)
        end VALACHLEI,
      CASE WHEN i1.cant = 0 THEN i1.pu*l1.cant ELSE (i1.pu*i1.cant-i1.tva)*l1.cant/i1.cant END *
      CASE
        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, i1.contserv, -1, 1, i1.pu * i1.cant, i1.TVA)
      END VALLEI,
      CASE WHEN i1.cant = 0 THEN 0 ELSE Coalesce(i1.tva,0)*l1.cant/i1.cant END *
      CASE
        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, i1.contserv, -1, 2, i1.pu * i1.cant, i1.TVA)
      END TVALEI, I.DATADOC, I.PREFIXDOC||'' ''||I.NRDOC||''/''||TO_CHAR(I.DATADOC,''DD.MM.YYYY'') DOC, S.DEN_SUBUNIT SUBUNITATEA,
    '||sCurs||'
      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.CODLIVR = L.CODLIVR AND L1.CODIES1 = I1.CODIES1
       INNER JOIN NSUBUNIT S ON S.CODSUBUNIT = I.SUBUNITATEA
       LEFT  JOIN NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
       LEFT  JOIN LIVRVAL LV ON LV.CodLivr1 = L1.CodLivr1
       LEFT  JOIN TMP_CMD ST ON ST.CODOBIECT = I1.CODIES1 AND ST.USERID = '||aUserID||chr(13)||
       sJoinFurn||'
         LEFT JOIN TMP_ANLUNA_VAL Excl ON Excl.al = i.an*12+i.luna AND EXCL.VALOARE = COALESCE(NS.CodIOArt, LV.CodIOArt, 0)
      WHERE I.DATADOC ' || coalesce(current_setting('PKG_LIST_BASE_TOPART.vCondData', true),'')
      || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || ' AND Coalesce(I.INFOCM,0) = 0
        AND I.TIPDOC = 16
        AND Coalesce(I.ANULAT,0) = 0
    AND Excl.VALOARE IS NULL
        AND I1.TIPLINIE = ''=''
      UNION ALL
  SELECT
      ''0'' TIPARTICOL, I1.CODOBIECT,
      0 CODFURN, 0 TIPFURN,
      I1.CANT CANT,
      0 VALACHLEI,
      CASE WHEN i1.pu = 0 THEN 0 ELSE (i1.pu*i1.cant-CASE WHEN i.tipdoc = 21 THEN i1.Tva ELSE 0 END)*CASE WHEN Coalesce(G.CURS,0)= 0 THEN 1 ELSE G.CURS END*i1.pretorig/i1.pu*Coalesce(i1.coefdiscmaj,1) END VALLEI,
      CASE WHEN i1.pu = 0 THEN 0 ELSE i1.Tva                                                        *CASE WHEN Coalesce(G.CURS,0)= 0 THEN 1 ELSE G.CURS END*i1.pretorig/i1.pu*Coalesce(i1.coefdiscmaj,1) END TVALEI,
      I.DATADOC, I.PREFIXDOC||'' ''||I.NRDOC||''/''||TO_CHAR(I.DATADOC,''DD.MM.YYYY'') DOC, S.DEN_SUBUNIT SUBUNITATEA,
      '||sCurs||'
    FROM IESIRI I
      INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
      INNER JOIN GENERAL G ON G.TIPDOC = I.TIPDOC AND G.CODDOC = I.CODIES
      INNER JOIN NSUBUNIT S ON S.CODSUBUNIT = I.SUBUNITATEA
    WHERE I.DATADOC '||coalesce(current_setting('PKG_LIST_BASE_TOPART.vCondData', true),'')||PKG_LIST_BASE_UTILS_COND_SUBUNIT('I') ||' AND Coalesce(I.INFOCM,0) = 0
      AND NOT I.TIPDOC IN (14, 15, 16, 23, 24'||sCod||')
      AND Coalesce(I.ANULAT,0) = 0
      AND I1.TIPLINIE &lt;&gt; ''='' AND I1.TIPLINIE &lt;&gt; ''G'' AND I1.TIPLINIE &lt;&gt; ''T''
 UNION ALL
      SELECT
        ''0'' TIPARTICOL, I1.CODOBIECT,
        0 CODFURN, 0 TIPFURN,
        I1.CANT CANT,
        0 VALACHLEI,
        (i1.pu*i1.cant-i1.tva) *
        CASE
          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, i1.contserv, -1, 1, i1.pu * i1.cant, i1.TVA)
        END VALLEI,
        i1.tva *
        CASE
          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, i1.contserv, -1, 2, i1.pu * i1.cant, i1.TVA)
        END TVALEI,
        I.DATADOC, I.PREFIXDOC||'' ''||I.NRDOC||''/''||TO_CHAR(I.DATADOC,''DD.MM.YYYY'') DOC, S.DEN_SUBUNIT SUBUNITATEA,
        '||sCurs||'
      FROM IESIRI I
        INNER JOIN IESIRI1 I1 ON I1.CODIES    = I.CODIES
        INNER JOIN NSUBUNIT S ON S.CODSUBUNIT = I.SUBUNITATEA
      WHERE I.DATADOC ' || coalesce(current_setting('PKG_LIST_BASE_TOPART.vCondData', true),'')
      || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
        AND I.TIPDOC = 16
        AND Coalesce(I.ANULAT,0) = 0
        AND I1.TIPLINIE &lt;&gt; ''='' AND I1.TIPLINIE &lt;&gt; ''G'' AND I1.TIPLINIE &lt;&gt; ''T''';

  sUpdate := 'UPDATE ' || tmpName || ' SET Total = (SELECT SUM(ValoareLei) FROM ' || tmpName || ')';
  perform LIST_EXECUTE_IMMEDIATE(sInsert1, aListID, aListVer);
  execute 'UPDATE TMP_LST_TOPART SET VALADAOSLEI = CASE WHEN TIPARTICOL = ''1'' THEN 0 ELSE VALLEI - VALACHLEI END ';
  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_topcliani_processlist</obj_name>
  <obj_hashval>35fed67c5f9b0c2b26447667b3c59aea</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topcliani_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 := '';

  V_REC       RECORD;
  sInsert     varchar;
begin
  --Bogdan 02.09.2020
  gSuplCols := 'npart p, nagenda ss, npers ag';

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

  IF (pkg_list_base_topcliani_TotiPart()) THEN
      INSERT INTO tmp_manevra_liste (filtru, valoare )
      SELECT 'CODPART', codpart FROM npart WHERE codpart &gt; 0;
  END IF;

  DELETE FROM tmp_toppeani;
  IF  current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric &gt; 1 THEN
    INSERT INTO tmp_toppeani (an, val, codpart )
    SELECT mana.valoare::numeric, G.ValTot_Val, manp.valoare::numeric
    FROM tmp_manevra_liste mana,
         tmp_manevra_liste manp,
         (
           SELECT COALESCE(SUM(S.ValTot_Val), 0) VALTOT_VAL, S.An, S.Partener
          FROM (
                SELECT SUM(CASE WHEN  i.moneda &gt; 0 THEN i.valdoc * CASE WHEN  COALESCE(i.curs, 0)=0 THEN 1 ELSE  COALESCE(i.curs, 0) END
                                ELSE i.valdoc
                           END ) VALTOT_VAL,
                       I.An, I.Partener
                FROM IESIRI I
                WHERE
                  i.subunitatea = current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric
                    AND I.TipDoc NOT IN (20, 21)
                    AND  COALESCE(I.Anulat, 0) = 0
                    AND  COALESCE(I.Initializari, 0) = 0
                    AND  I.Operat = 1
                    AND  I.Luna &gt;= current_setting('PKG_LIST_BASE_TOPCLIANI.vLunaStart', true)::numeric
                    AND  I.Luna &lt;= current_setting('PKG_LIST_BASE_TOPCLIANI.vLunaFin'  , true)::numeric
                GROUP BY  I.An, I.Partener
                union ALL
                SELECT SUM(CASE WHEN  i.moneda &gt; 0 THEN i.valdoc * CASE WHEN  COALESCE(i.curs, 0)=0 THEN 1 ELSE  COALESCE(i.curs, 0) END
                                ELSE i.valdoc
                           END ) VALTOT_VAL,
                       I.An, I.Partener
                FROM IESIRI I
                WHERE
                   i.subunitatea = current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric
                     AND  I.TipDoc = 21
                     AND  COALESCE(I.Anulat, 0) = 0
                     AND  COALESCE(I.Initializari, 0) = 0
                     AND  I.Operat = 1
                     AND  I.Luna &gt;= current_setting('PKG_LIST_BASE_TOPCLIANI.vLunaStart', true)::numeric
                     AND  I.Luna &lt;= current_setting('PKG_LIST_BASE_TOPCLIANI.vLunaFin'  , true)::numeric
                GROUP BY   I.An, I.Partener
               ) S
          GROUP BY   S.An, S.Partener
         ) G
    WHERE
         mana.filtru = 'AN'
           and  manp.filtru = 'CODPART'
           AND  G.An = mana.valoare::numeric
           AND  G.Partener = manp.valoare::numeric;
  ELSE
    INSERT INTO tmp_toppeani(an, val, codpart )
    SELECT mana.valoare::numeric, G.ValTot_Val, manp.valoare::numeric
    FROM tmp_manevra_liste mana,
         tmp_manevra_liste manp,
        ( SELECT COALESCE(SUM(S.ValTot_Val), 0) VALTOT_VAL, S.An, S.Partener
          FROM (
            SELECT SUM(CASE WHEN  i.moneda &gt; 0 THEN i.valdoc * CASE WHEN  COALESCE(i.curs, 0)=0 THEN 1 ELSE  COALESCE(i.curs, 0) END
                             ELSE i.valdoc
                        END ) VALTOT_VAL,
                    I.An, I.Partener
            FROM IESIRI I
            WHERE
              I.TipDoc NOT IN (20, 21)
              AND  COALESCE(I.Anulat, 0) = 0
              AND  COALESCE(I.Initializari, 0) = 0
              AND  I.Operat = 1
              AND  I.Luna &gt;= current_setting('PKG_LIST_BASE_TOPCLIANI.vLunaStart', true)::numeric
              AND  I.Luna &lt;= current_setting('PKG_LIST_BASE_TOPCLIANI.vLunaFin'  , true)::numeric
            GROUP BY I.An, I.Partener
            union ALL
            SELECT SUM(CASE WHEN  i.moneda &gt; 0 THEN i.valdoc * CASE WHEN  COALESCE(i.curs, 0)=0 THEN 1 ELSE  COALESCE(i.curs, 0) END
                            ELSE i.valdoc
                       END ) VALTOT_VAL,
                   I.An, I.Partener
            FROM IESIRI I
            WHERE
               I.TipDoc = 21
               AND  COALESCE(I.Anulat, 0) = 0
               AND  COALESCE(I.Initializari, 0) = 0
               AND  I.Operat = 1
               AND  I.Luna &gt;= current_setting('PKG_LIST_BASE_TOPCLIANI.vLunaStart', true)::numeric
               AND  I.Luna &lt;= current_setting('PKG_LIST_BASE_TOPCLIANI.vLunaFin'  , true)::numeric
            GROUP BY   I.An, I.Partener ) S
          GROUP BY   S.An, S.Partener
        ) G
      WHERE
           mana.filtru = 'AN'
          and  manp.filtru = 'CODPART'
          AND  G.An = mana.valoare::numeric
           AND  G.Partener = manp.valoare::numeric;
  END IF;

  DELETE FROM tmp_toppeani where  COALESCE(val, 0) = 0;
  DELETE FROM tmp_manevra_liste man where  man.filtru = 'CODPART' and man.Valoare::numeric NOT IN (SELECT codpart FROM tmp_toppeani );

  sInsert := ' insert into ' || coalesce(tmpName,'')
        || ' (CodPart, Den_Part, Agent' || coalesce(gUserFields,'') || ') '                                                           || coalesce(chr(13),'')
        || ' select man.valoare::NUMERIC, p.den_part, ag.nume||'' ''||ag.prenume' || coalesce(gUserAlias,'')                          || coalesce(chr(13),'')
        || ' from tmp_manevra_liste man '                                                                                             || coalesce(chr(13),'')
        || '      inner join npart  p  on man.valoare::NUMERIC = p.codpart '                                                          || coalesce(chr(13),'')
        || '      left join nagenda ss on ss.codpart = p.codpart and ss.sediusocial between 4 and 7 and COALESCE(ss.INACTIV, 0) = 0 ' || coalesce(chr(13),'')
        || '      left join npers   ag on ag.codpers = COALESCE(ss.codagent,0)' || coalesce(gSuplJoins,'')                            || coalesce(chr(13),'')
        || ' where man.filtru = ''CODPART'' ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  FOR v_rec IN  (SELECT * FROM tmp_toppeani) LOOP
    sInsert := ' update ' || coalesce(tmpName,'') || ' set ' || '   AN' || coalesce(v_rec.an::varchar,'') || ' = ' || coalesce(replace((v_Rec.Val)::varchar, ',', '.'),'')
            || ' where CodPart = ' || coalesce(v_Rec.Codpart::varchar ,'');
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  END LOOP;
end;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_planifprod_processlist</obj_name>
  <obj_hashval>50ebddfdd837a41f6846ee66c5774f0c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_planifprod_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,planifprod pp,prodcomp pc,nartobj objsemip,num um,prodcomp pcimp,prodmat mat,nartobj1 comp1,pretm pretm';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vAnLunaLucru    numeric;
BEGIN
  --Florin 30.08.2022 - sinc. Oracle (26.08.2022)
  --Adina 20.04.2021 - sinc.Oracle
  --Adina 16.04.2021 - alstart,alstop,vAnLunaLucru
  --Adina 18.02.2021 - dupa modif.Oracle din 17.02.2021
  --Adina 07.01.2021 tichet 42054
  --Adina 14 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_PLANIFPROD.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  vAnLunaLucru := getanlucru()*12+getlunalucru();
  CALL PRC_AL_CHECK('nartobj1',0);

  sString :=
  'insert into ' || tmpName || ' (NAV_CodDoc, NAV_TipDoc, nrdoc, datadoc, Produs, Necesar, Component, UM, Cant, Pozitie, Nivel, ordine, obs, varianta' || gUserFields || ')
   WITH RECURSIVE tt_w( CodPlanifNod, POZITIE, NODORIGINAL, IND) AS
   (SELECT CodPlanifNod,POZITIE,NODORIGINAL,   LPAD(POZITIE::varchar, 2, ''0'') || ''''
    FROM PLANIFNOD WHERE NODORIGINAL=0
    UNION ALL
    SELECT n.CodPlanifNod, n.POZITIE, n.NODORIGINAL, w.IND || ''.'' || LPAD(n.POZITIE::varchar, 2, ''0'')
    FROM PLANIFNOD n inner join tt_w w ON w.CodPlanifNod = n.NODORIGINAL
   )
  select pp.codplanifprod, 85, pp.nrdoc, pp.datadoc, prod.denumire, pp1.necesar, comp.denumire, UM.den_um, nod.necesar, nod.Pozitie, nod.Nivel, substr(''.''||x.ind,5, length(''.''||x.ind)-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 nartobj1       comp1    on comp.codobiect     = comp1.codobiect AND '||vAnLunaLucru::varchar||' BETWEEN comp1.ALStart and comp1.ALStop
    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 nartobj        objsemi  on objsemi.codobiect  = pc.codobiect
    left  join pretm          pretm    on pretm.codobiect    = objsemi.codobiect and pretm.implicit = 1 and pretm.subunitatea = pp.subunitatea
    left  join prodcomp       pcimp    on pcimp.codobiect    = objsemi.codobiect and pcimp.implicit = 1
    left  join nartobj        objsemip on nodp.codobiect     = objsemip.codobiect
    left  join prodcomp       ppc      on ppc.codprodcomp    = (case when coalesce(nodp.codreteta,0)=-1 then nod.codreteta else nodp.codreteta end) 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      impo     on prod.codobiect     = impo.codobiect and impo.codsubunit = pp.subunitatea
    LEFT  JOIN IOART          IOAP     ON IOAP.CODIOART      = case when coalesce(impo.contimplicit,0) = 0 then imp.contimplicit else coalesce(impo.contimplicit,0) end
    LEFT  JOIN
    --(
    --  SELECT CodPlanifNod, sys_connect_by_path(LPAD(POZITIE, 2, ''0''),''.'') IND
    --  FROM PLANIFNOD START WITH NODORIGINAL = 0 CONNECT BY PRIOR CODPLANIFNOD = NODORIGINAL
    --) X
    tt_w                      X        on x.CodPlanifNod = nod.CodPlanifNod' || gSuplJoins || '
    WHERE ((nod.versiune = 1 and nod.tip &lt;&gt; 3) or nod.tip = 3) and coalesce(nod.nodoriginal, 0) &gt; 0  and pp.saptamana = '||coalesce(current_setting('PKG_LIST_BASE_PLANIFPROD.pSetimana', true),'')
    ||' and pp.An = '||coalesce(current_setting('PKG_LIST_BASE_PLANIFPROD.pAn', true),'');

    --and comp1.anstart * 12 + comp1.lunastart =
    --  (SELECT MAX(n2.anstart*12+n2.lunastart) FROM nartobj1 n2
    --     WHERE comp1.codobiect = n2.codobiect AND n2.anstart*12+n2.lunastart &lt;= getanlucru()*12+getlunalucru() ) ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sstring, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_pmp_processlist</obj_name>
  <obj_hashval>33781102affd25b16f799e84823f3d1f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pmp_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sInsertTMP       varchar := '';
  vAnPrec         numeric;
  vLunaPrec       numeric;
  vAnCur           numeric;
  vLunaCur         numeric;
  vAnFin           numeric;
  vLunaFin         numeric;
  gSuplCols        VARCHAR := 'nartobj o, nart a';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 06.04.2021 - alstart,alstop
  --Adina 07 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_PMP.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  vLunaCur := trunc( mod(PKG_LIST_SELECTLUNAAN_LunaStart(), 12) );
  IF  vLunaCur = 0 THEN vLunaCur := 12; END IF;
  vAnCur := trunc( (PKG_LIST_SELECTLUNAAN_LunaStart() - vLunaCur)  / 12 );

  vLunaFin := trunc( mod(PKG_LIST_SELECTLUNAAN_LunaStop(), 12) );
  IF  vLunaFin = 0 THEN vLunaFin := 12; END IF;
  vAnFin := trunc( (PKG_LIST_SELECTLUNAAN_LunaStop() - vLunaFin)  / 12 );

  sInsert :=
  'INSERT INTO ' || tmpName || '(DenArt, TipLinie, Doc, An, Luna, Ord, CANT, VACHIZLEI, VACHIZVAL, VPMPLEI, VPMPVAL' || gUserFields || ' )
  SELECT o.denumire, t.tiplinie, t.document, t.an, t.luna, t.tip, t.cant, t.vachizlei, t.vachizval, t.vpmplei, t.vpmpval ' || gUserAlias || '
  FROM tmp_list_pmp t
    LEFT JOIN nartobj o ON o.codobiect  = t.codobiect
    LEFT JOIN nart    a ON a.codarticol = o.codarticol ' || gSuplJoins || '
  WHERE t.tip &gt;= 0';

  SELECT newan,newluna INTO vAnPrec, vLunaPrec FROM  pkg_globals_Calculeaza_Luna_Precedenta(vAnCur, vLunaCur, vAnPrec, vLunaPrec);

  sInsertTMP :=
  'INSERT INTO tmp_list_pmp ( CODOBIECT, AN, LUNA, TIP, TIPLINIE, CANT, VACHIZLEI, VACHIZVAL, VPMPLEI, VPMPVAL )
  WITH
    SI AS (
      SELECT NS.CODOBIECT, SUM(NL.REST) CANT, SUM(NL.REST * (NS.PRET - NS.ADAOS)) VACHIZLEI, SUM(NL.REST * NS.PUVAL) VACHIZVAL
      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((vANPrec * 12 + vLunaPrec)::varchar,'') || ' BETWEEN ioa.ALStart and ioa.ALStop
                                  AND ioa.mg = 3
      WHERE nl.an = ' || coalesce(vANPrec::varchar,'') || ' AND nl.luna = ' || coalesce(vLunaPrec::varchar,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('g', 'codsubunit',NULL,NULL),'') || '
      GROUP BY NS.CODOBIECT
    ),
    PMP AS (
      SELECT CODOBIECT,
        CASE WHEN SUM(CANTINTR) = 0 THEN 0 ELSE SUM(VALINTR)  /SUM(CANTINTR) END PMPLEI,
        CASE WHEN SUM(CANTINTR) = 0 THEN 0 ELSE SUM(VALVALUTA)/SUM(CANTINTR) END PMPVAL
      FROM pmpluna p
      WHERE p.an = ' || coalesce(vANPrec::varchar,'') || ' AND p.luna = ' || coalesce(vLunaPrec::varchar,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('p', 'codsubunit',NULL,NULL),'') || '
      GROUP BY P.CODOBIECT
    )
    SELECT si.codobiect, ' || coalesce(vAnCur::varchar,'') || ', ' || coalesce(vLunaCur::varchar,'') || ', 0, ''Stoc initial'', si.cant, si.vachizlei, si.vachizval, si.cant * pmp.pmplei, si.cant * pmp.pmpval
    FROM SI LEFT JOIN PMP ON PMP.CODOBIECT = SI.CODOBIECT';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInserttmp, aListID, aListVer);

  WHILE  (vAnCur * 12 + vLunaCur) &lt;= (vAnFin * 12 + vLunaFin)
  LOOP
    sInsertTMP :=
    'INSERT INTO tmp_list_pmp ( CODOBIECT, AN, LUNA, TIP, CANT, VACHIZLEI, VACHIZVAL, TIPLINIE, DOCUMENT )
    WITH
      M AS (
        SELECT -- NIR Intrari
          NS.CODOBIECT, 1 TIP, NS.CANTNIR CANT,
          NS.CANTNIR * (NS.PRET - NS.ADAOS) VACHIZLEI, NS.CANTNIR * NS.PUVAL VACHIZVAL,
          ''Intrari luna ''||I.An||''.''||I.Luna TIPLINIE,
          I.PREFIXDOC||I.NRDOC||''/''||To_char(I.DATADOC,''dd.mm.yyyy'') DOC
        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((vAnCur * 12 + vLunaCur)::varchar,'') || ' BETWEEN IOA.ALStart and IOA.ALStop AND ioa.mg = 3
        WHERE N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7)
          AND N.ANULAT = 0 AND N.OPERAT = 1
          AND I.AN = ' || coalesce(vAnCur::varchar,'') || ' AND I.LUNA = ' || coalesce(vLunaCur::varchar,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
        UNION ALL
        SELECT -- NIR-uri din MISCARI INTERNE
          NS.CODOBIECT, 1 TIP, NS.CANTNIR CANT,
          NS.CANTNIR * (NS.PRET - NS.ADAOS) VACHIZLEI, NS.CANTNIR * NS.PUVAL VACHIZVAL,
          ''Intrari luna ''||T.An||''.''||T.Luna TIPLINIE,
          T.PREFIXDOC||T.NRDOC||''/''||To_char(T.DATADOC,''dd.mm.yyyy'') DOC
        FROM NIRSTOC NS
          INNER JOIN NIR     N   ON N.CODNIR       = NS.CODNIR
          INNER JOIN TRANSF  T   ON T.CODTRANSF    = N.CODTRANSF
          INNER JOIN NIRSTOC NSP ON NSP.CODNIRSTOC = NS.CODNIRSTOCPARINTE
          INNER JOIN ioart1  IOA ON IOA.CODIOART   = NS.CODIOART  AND ' || coalesce((vAnCur * 12 + vLunaCur)::varchar,'') || ' BETWEEN IOA.ALStart and IOA.ALStop AND IOA.mg = 3
          LEFT  JOIN ioart1  I2  ON IOA.CODIOART   = NSP.CODIOART AND ' || coalesce((vAnCur * 12 + vLunaCur)::varchar,'') || ' BETWEEN  I2.ALStart and  I2.ALStop AND  I2.mg = 3
        WHERE N.TIPNIR IN (12, 13)
          AND N.ANULAT = 0 AND N.OPERAT = 1
          AND T.AN = ' || coalesce(vAnCur::varchar,'') || ' AND T.LUNA = ' || coalesce(vLunaCur::varchar,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL),'') || '
          AND I2.CODIOARt IS NULL
        UNION ALL
        SELECT -- RETURURI INTRARI
          NS.CODOBIECT, -1 TIP, -L1.CANT,
          -L1.CANT * (NS.PRET - NS.ADAOS) VACHIZLEI, -L1.CANT * NS.PUVAL VACHIZVAL,
          NULL TIPLINIE,
          NULL DOC
        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 ioart1  IOA ON IOA.CODIOART  = NS.CODIOART AND ' || coalesce((vAnCur * 12 + vLunaCur)::varchar,'') || ' BETWEEN IOA.ALStart and IOA.ALStop AND IOA.mg = 3
        WHERE L.TIPLIVR IN (1, 2, 3, 4, 5, 6, 7)
          AND L.OPERAT = 1 AND L.ANULAT = 0
          AND I.AN = ' || coalesce(vAnCur::varchar,'') || ' AND I.LUNA = ' || coalesce(vLunaCur::varchar,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
        UNION ALL -- IESIRI
        SELECT
          NS.CODOBIECT, CASE WHEN N.CODIES = I.CODIES THEN 1 ELSE -1 END TIP, -L1.CANT CANT,
          -L1.CANT * (NS.PRET - NS.ADAOS) VACHIZLEI, -L1.CANT * NS.PUVAL VACHIZVAL,
          CASE WHEN N.CODIES = I.CODIES THEN ''Iesiri in rosu cu creare de stoc luna ''||I.An||''.''||I.Luna ELSE NULL END TIPLINIE,
          CASE WHEN N.CODIES = I.CODIES THEN I.PREFIXDOC||I.NRDOC||''/''||To_char(I.DATADOC,''dd.mm.yyyy'') ELSE NULL END DOC
        FROM LIVR1 L1
          INNER JOIN LIVR    L   ON L.CODLIVR     =  L1.CODLIVR
          INNER JOIN IESIRI  I   ON I.CODIES      = L.CODIES
          INNER JOIN IESIRI1 I1  ON I1.CODIES1    = L1.CODIES1
          INNER JOIN NIRSTOC NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
          INNER JOIN ioart1  IOA ON IOA.CODIOART  = NS.CODIOART AND ' || coalesce((vAnCur * 12 + vLunaCur)::varchar,'') || ' BETWEEN IOA.ALStart and IOA.ALStop AND IOA.mg = 3
          INNER JOIN NIR     N   ON N.CODNIR      = NS.CODNIR
        WHERE L.TIPLIVR IN (14, 16, 19, 20, 21, 22, 23, 24)
          AND L.OPERAT = 1 AND L.ANULAT = 0
          AND I.AN = ' || coalesce(vAnCur::varchar,'') || ' AND I.LUNA = ' || coalesce(vLunaCur::varchar,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
      )
    SELECT m.codobiect, ' || coalesce(vAnCur::varchar,'') || ', ' || coalesce(vLunaCur::varchar,'') || ', m.tip, Sum(m.cant), Sum(m.vachizlei), Sum(m.vachizval), m.tiplinie, m.doc
    FROM m
    GROUP BY m.codobiect, m.tip, m.tiplinie, m.doc';

    PERFORM LIST_EXECUTE_IMMEDIATE(sInserttmp, aListID, aListVer);

    INSERT INTO tmp_list_pmp(CODOBIECT, AN, LUNA, TIP, CANT, VACHIZLEI, VACHIZVAL, VPMPLEI, VPMPVAL, TIPLINIE)
    SELECT codobiect, vAnCur, vLunaCur, 3, Sum(cant), Sum(VACHIZLEI), Sum(VACHIZVAL),
      CASE WHEN  Sum(CASE WHEN  TIP=-1 THEN 0 ELSE CANT END ) = 0 THEN 0
           ELSE  Sum(CANT) * Sum(CASE WHEN TIP=1 THEN VACHIZLEI WHEN TIP=-1 THEN 0 ELSE VPMPLEI END ) / Sum(CASE WHEN TIP=-1 THEN 0 ELSE CANT END )
       END  VPMPLEI,
      CASE WHEN  Sum(CASE WHEN  TIP=-1 THEN 0 ELSE  CANT END ) = 0 THEN 0
           ELSE  Sum(CANT) * Sum(CASE WHEN  TIP=1 THEN VACHIZVAL WHEN  TIP=-1 THEN 0 ELSE  VPMPVAL END ) / Sum(CASE WHEN  TIP=-1 THEN 0 ELSE  CANT END )
       END  VPMPVAL,
       'Sold final ' || vAnCur::varchar || '.' || vLunaCur::varchar
    FROM tmp_list_pmp
    GROUP BY codobiect;

    INSERT INTO tmp_list_pmp(CODOBIECT, AN, LUNA, TIP, CANT, VACHIZLEI, VACHIZVAL, TIPLINIE)
    SELECT codobiect, vAnCur, vLunaCur, 2, Sum(cant), Sum(VACHIZLEI), Sum(VACHIZVAL), 'Total intrari ' || coalesce(vAnCur::varchar,'') || '.' || coalesce(vLunaCur::varchar,'')
    FROM tmp_list_pmp
    WHERE tip = 1
    GROUP BY codobiect;

    DELETE FROM tmp_list_pmp WHERE an &lt;&gt; vAnCur OR  luna &lt;&gt; vLunaCur;
    EXECUTE sInsert;
    DELETE FROM tmp_list_pmp WHERE tip &lt; 3;

    IF  vLunaCur &lt; 12 THEN
      vLunaCur := vLunaCur + 1;
    ELSE
      vAnCur := vAnCur + 1;
      vLunaCur := 1;
    END IF;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_termedfurn_processlist</obj_name>
  <obj_hashval>451d34a0677ad54c5b7d06cb6b80742d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_termedfurn_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 := 'npart npart, nmonede mon, nclasep clsp, nagenda ag, nlocalit loc, njudet jud, npers agent, npers agent_inc, nsubunit substingatori, nsubunit substinsi';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 19.10.2020 (??)
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_TERMEDFURN.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert := 'INSERT INTO '||tmpName ||'(PARTENER, MONEDA, '                ||chr(13)||
                                         'TOTAL, TERMED'||gUserFields||') '  ||chr(13);
   sSelect :=
      'with stingeri as ( '        ||chr(13)||
      'select stingere.*, '        ||chr(13)||
      '       general.codgeneral '||chr(13)||
      'from stingere '            ||chr(13)||
      '     inner join obligpif on stingere.codstingatorpif = obligpif.codobligpif '||chr(13)||
      '     inner JOIN general  ON obligpif.codgeneral = general.codgeneral '        ||chr(13)||
      '), '          ||chr(13)||
      'stinsi as ( '||chr(13)||
      'SELECT '      ||chr(13)||
      '  i.datadoc data_stins, '            ||chr(13)||
      '  obstins.codobligpif codobligpif, '  ||chr(13)||
      '  obstins.codpart codpart '          ||chr(13)||
      'FROM intrari i '                      ||chr(13)||
      '     INNER JOIN general g        ON g.coddoc = i.codintr and g.semnificatie &lt;&gt; 600 '                  ||chr(13)||
      '     INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral '                              ||chr(13)||
      'WHERE (coalesce(i.anulat, 0) = 0) and (coalesce(i.initializari, 0) = 1) and (g.tipdoc = i.tipdoc) '  ||chr(13)||
      '      AND (i.datadoc &lt;= TO_DATE('''||to_char(pkg_list_alegperioada_getDataF(),'dd/mm/yyyy')||''',''DD/MM/YYYY''))'          ||chr(13)||
      'UNION ALL '                                                                                          ||chr(13)||
      'SELECT '                                    ||chr(13)||
            '  i.datadoc data_stins, '            ||chr(13)||
            '  obstins.codobligpif codobligpif, '  ||chr(13)||
            '  obstins.codpart codpart '          ||chr(13)||
            'FROM intrari i '                      ||chr(13)||
            '     INNER JOIN general g        ON g.coddoc = i.codintr and g.semnificatie &lt;&gt; 600 '                ||chr(13)||
            '     INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral '                            ||chr(13)||
            'WHERE (coalesce(i.anulat, 0) = 0) and (coalesce(i.initializari, 0) = 0) and (g.tipdoc = i.tipdoc) '||chr(13)||
            '      AND (i.datadoc &lt;= TO_DATE('''||to_char(pkg_list_alegperioada_getDataF(),'dd/mm/yyyy')||''',''DD/MM/YYYY''))'        ||chr(13)||
      'UNION ALL '                                ||chr(13)||
      'SELECT '                                    ||chr(13)||
            '  i.datadoc data_stins, '            ||chr(13)||
            '  obstins.codobligpif codobligpif, '  ||chr(13)||
            '  obstins.codpart codpart '          ||chr(13)||
            'FROM iesiri i '                      ||chr(13)||
            '     INNER JOIN general g        ON g.coddoc = i.codies and g.semnificatie = 200 '                  ||chr(13)||
            '     INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral '                            ||chr(13)||
            'WHERE (coalesce(i.anulat, 0) = 0) and (coalesce(i.initializari, 0) = 0) and (g.tipdoc = i.tipdoc) '||chr(13)||
            '      AND (i.datadoc &lt;= TO_DATE('''||to_char(pkg_list_alegperioada_getDataF(),'dd/mm/yyyy')||''',''DD/MM/YYYY''))'        ||chr(13)||
      'UNION ALL '                                ||chr(13)||
      'SELECT '                                    ||chr(13)||
            '  nc.datadoc data_stins, '            ||chr(13)||
            '  obstins.codobligpif codobligpif, '  ||chr(13)||
            '  obstins.codpart codpart '          ||chr(13)||
            'FROM nc1 '                            ||chr(13)||
            '     INNER JOIN general g        ON g.coddoc = nc1.codnc1 and g.semnificatie &lt;&gt; 600 '      ||chr(13)||
            '     INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral '                    ||chr(13)||
            '     INNER JOIN nc ON nc1.codnc = nc.codnc '                                                ||chr(13)||
            'WHERE g.tipdoc = 35 '                                                                      ||chr(13)||
            '      AND nc.datadoc &lt;= TO_DATE('''||to_char(pkg_list_alegperioada_getDataF(),'dd/mm/yyyy')||''',''DD/MM/YYYY'')'||chr(13)||
      'UNION ALL '                                ||chr(13)||
      'SELECT '                                    ||chr(13)||
            '  tr1.datadoc data_stins, '          ||chr(13)||
            '  obstins.codobligpif codobligpif, '  ||chr(13)||
            '  obstins.codpart codpart '          ||chr(13)||
            'FROM trezor1 tr1 '                    ||chr(13)||
            '     INNER JOIN general g        ON g.coddoc = tr1.codtrezor1 and g.semnificatie &lt;&gt; 600 '    ||chr(13)||
            '     INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral '                      ||chr(13)||
            '     INNER JOIN trezor tr        ON tr1.codtrezor = tr.codtrezor '                            ||chr(13)||
            'WHERE (coalesce(tr1.anulat, 0) = 0) and (g.tipdoc = 35 OR g.tipdoc = 31 OR g.tipdoc = 29) '  ||chr(13)||
            '      AND tr1.datadoc &lt;= TO_DATE('''||to_char(pkg_list_alegperioada_getDataF(),'dd/mm/yyyy')||''',''DD/MM/YYYY'') '||chr(13)||
      'UNION ALL '                                ||chr(13)||
      'SELECT '                                    ||chr(13)||
            '  cstins.datadoc data_stins, '        ||chr(13)||
            '  obstins.codobligpif codobligpif, '  ||chr(13)||
            '  obstins.codpart codpart '          ||chr(13)||
            'FROM compens cstins '                ||chr(13)||
            '     INNER JOIN general g        ON g.coddoc = cstins.codcompens and g.semnificatie &lt;&gt; 600 '      ||chr(13)||
            '     INNER JOIN obligpif obstins ON g.codgeneral = obstins.codgeneral '                          ||chr(13)||
            'WHERE g.tipdoc = 28 '                                                                            ||chr(13)||
            '      AND cstins.datadoc &lt;= TO_DATE('''||to_char(pkg_list_alegperioada_getDataF(),'dd/mm/yyyy')||''',''DD/MM/YYYY'') '  ||chr(13)||
            ' ), '                            ||chr(13)||
            'stingatori as ('                  ||chr(13)||
            '  SELECT '                        ||chr(13)||
            '    o.codobligpif CodObligPIF,'  ||chr(13)||
            '    t1.datadoc as DATA, '        ||chr(13)||
            '    t.subunitatea Subunitatea, '  ||chr(13)||
            '    g.moneda '                    ||chr(13)||
            '  FROM trezor1 t1 '              ||chr(13)||
            '       INNER JOIN trezor t   ON t1.codtrezor = t.codtrezor '                        ||chr(13)||
            '       INNER JOIN general g  ON t1.codtrezor1 = g.coddoc and g.tipdoc = t.tipdoc '  ||chr(13)||
            '       INNER JOIN obligpif o ON o.codgeneral = g.codgeneral '                      ||chr(13)||
            '  WHERE (T1.DATADOC BETWEEN TO_DATE('''||to_char(pkg_list_alegperioada_getDataS(),'dd/mm/yyyy')||''',''DD/MM/YYYY'') AND TO_DATE('''||to_char(pkg_list_alegperioada_getDataF(),'dd/mm/yyyy')||''',''DD/MM/YYYY'')) AND (((G.TipDoc IN (29, 30, 31)) AND (t1.TipTranz = 0)) OR (t1.TipTranz = 0 AND t1.ObiectTranz = 1)) '||chr(13)||
            '  UNION ALL '                    ||chr(13)||
            '  SELECT '                        ||chr(13)||
            '    o.codobligpif CodObligPIF,'  ||chr(13)||
            '    c.datadoc as DATA, '          ||chr(13)||
            '    c.subunitatea Subunitatea, '  ||chr(13)||
            '    g.moneda '                    ||chr(13)||
            '  FROM compens c '                ||chr(13)||
            '       INNER JOIN general g  ON g.coddoc = c.codcompens and g.tipdoc = 28 '||chr(13)||
            '       INNER JOIN obligpif o ON o.codgeneral = g.codgeneral '              ||chr(13)||
            '  WHERE C.DATADOC BETWEEN TO_DATE('''||to_char(pkg_list_alegperioada_getDataS(),'dd/mm/yyyy')||''',''DD/MM/YYYY'') AND TO_DATE('''||to_char(pkg_list_alegperioada_getDataF(),'dd/mm/yyyy')||''',''DD/MM/YYYY'') '||chr(13)||
            ')'||chr(13)||
         'SELECT centralizare.partener, centralizare.SimbolMoneda, sum(centralizare.val_stingator) TOTAL, sum(centralizare.val_stingator*centralizare.difzile)/sum(centralizare.val_stingator) TERMED'||gUserAlias||' FROM ( '||chr(13)||
             'select stingeri.valoare VAL_STINGATOR, '              ||chr(13)||
             'npart.den_part PARTENER,'                              ||chr(13)||
             'stingatori.Data as DATA, '                            ||chr(13)||
             'stinsi.Data_stins DATA_STINS, '                        ||chr(13)||
             'date_trunc(''day'',stingatori.Data - stinsi.data_stins) DIFZILE, '  ||chr(13)||
             'mon.simbol SimbolMoneda '                              ||chr(13)||
       ' FROM stingatori '                                          ||chr(13)||
       '      INNER JOIN stingeri    on stingeri.codstingatorpif = stingatori.codobligpif '  ||chr(13)||
       '      INNER JOIN stinsi      on stingeri.codstinspif = stinsi.codobligpif '          ||chr(13)||
       '      LEFT  JOIN npart npart on stinsi.codpart = npart.codpart '                    ||chr(13)||
       '      LEFT  JOIN nmonede mon on stingatori.moneda = mon.codmoneda '|| gSuplJoins|| PKG_LIST_BASE_UTILS_COND_SUBUNIT('stingatori','subunitatea',' WHERE',null);
  sSelect := sSelect||'  ) CENTRALIZARE GROUP BY centralizare.partener, centralizare.SimbolMoneda ';

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topclientiold_processlist</obj_name>
  <obj_hashval>04d9c515b7ea69ca172598addd765766</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topclientiold_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       VARCHAR := '';
  sWith         VARCHAR := '';
  sSelect       VARCHAR := '';
  vCondData     VARCHAR := '';
  sCust         VARCHAR := '';
  vDataINI      varchar := current_setting('pkg_list_base_topclientiold.vDataIni',true);
  vDataFIN      varchar := current_setting('pkg_list_base_topclientiold.vDataFin',true);
  gSuplCols     VARCHAR := 'NARTOBJ NAO, NUM1 NUM1, NPART P, NPARTCODFISC CF, NAGENDA AG, NLOCALIT LOC, NJUDET JUD, NMONEDE MON, NART ART, NCLASEA CLSA, NCLASEP CLSP, NPERS AGENT, NLOCALIT LOCL, NJUDET JUDL';
   gUserFields   VARCHAR := '';
  gUserAlias    VARCHAR := '';
  gNullAlias    VARCHAR := '';
  gSuplJoins    VARCHAR := '';
  vAvize        numeric := current_setting('pkg_list_base_topclientiold.vAvize'      ,true)::numeric;
  vOrder        numeric := current_setting('pkg_list_base_topclientiold.vOrder'      ,true)::numeric;
  vSediiL        numeric := current_setting('pkg_list_base_topclientiold.vSediiL'     ,true)::numeric;
  vSubunit      boolean := current_setting('pkg_list_base_topclientiold.vSubunit'    ,true)::boolean;
  vAduCustodie  boolean := current_setting('pkg_list_base_topclientiold.vAduCustodie',true)::boolean;
  vAllIOArt      boolean := current_setting('pkg_list_base_topclientiold.vAllIOArt'   ,true)::boolean;
  vAllCls        boolean := current_setting('pkg_list_base_topclientiold.vAllCls'     ,true)::boolean;
  vWithEmul      boolean := current_setting('pkg_list_base_topclientiold.vWithEmul'   ,true)::boolean;
BEGIN
  --Florin 31.05.2024 - immediate
  --Adina 11.02.2021 - corectat PKG_LIST_BASE_UTILS_GETCURSREFERINTA in loc de PKG_LIST_BASE_UTILS.GETCURSREFERINTA
  --Adina 19.10.2020
  sCust := '';
  if not vAduCustodie then
    sCust := ' and coalesce(I.Custodie,0) = 0 ';
  end if;

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

  vCondData := 'BETWEEN TO_DATE ('''||vDataINI||''',''DD.MM.YYYY'') AND TO_DATE ('''||vDataFIN||''',''DD.MM.YYYY'')';

  DELETE FROM TMP_TOPCLI_ADAOSURI;
  DELETE FROM TMP_TOPCLI_VALCLIENT;
  DELETE FROM MP_TOPCLI_VALAGENT;
  DELETE FROM TMP_TOPCLI_VALAGENTART;

  if vSubunit then
    sInsert :=
     'INSERT INTO '||tmpName||'(DenArt,
                                DenUM,
                                Cant,
                                Pret,
                                Valoare,
                                Pret_Val,
                                Valoare_Val,
                                Valuta,
                                Client,
                                ValTot,
                                ValTot_Val,
                                ValTotAgent,
                                ValTotAgent_Val,
                                NrFactPerArt,
                                NrFactPerClient,
                                Adaos,
                                Proc_Adaos,
                                Adaos_val,
                                Proc_Adaos_val,
                                PretAchiz,
                                Agent,
                                SediuL, Subunitatea,
                                ValArtAgent,
                                ValArtAgent_Val,
                                CantArtAgent '||gUserFields||')';
  else
    sInsert :=
     'INSERT INTO '||tmpName||'(DenArt,
                                DenUM,
                                Cant,
                                Pret,
                                Valoare,
                                Pret_Val,
                                Valoare_Val,
                                Valuta,
                                Client,
                                ValTot,
                                ValTot_Val,
                                ValTotAgent,
                                ValTotAgent_Val,
                                NrFactPerArt,
                                NrFactPerClient,
                                Adaos,
                                Proc_Adaos,
                                Adaos_val,
                                Proc_Adaos_val,
                                PretAchiz,
                                Agent,
                                SediuL,
                                ValArtAgent,
                                ValArtAgent_Val,
                                CantArtAgent '||gUserFields||')';
  end if;

  if vOrder in (1,3) then
    if vAvize = 1 then
      sWith := 'INSERT INTO TMP_TOPCLI_ADAOSURI(CODIES1,ADAOS) '||
               'select CODIES1, SUM(ADAOS) ADAOS
                FROM ( '||chr(13)||
                     'SELECT I1.CodIes1, '||chr(13)||
                     'case '||chr(13)||
                     'when i1.tiplinie &lt;&gt; ''='' then 0 '||chr(13)||
                     'else case '||chr(13)||
                     'when I.tipdoc &lt;&gt; 21 then'||chr(13)||
                     '(case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) end)
                        * (I1.PretOrig * coalesce(i1.coefdiscmaj,1)
                        * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) -  case when coalesce(NS.CodNirStoc, 0) = 0 then LV.PretAchiz else NS.Pret - NS.Adaos end) '||chr(13)||
                     'else (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) end)
                            * ((I1.PU-I1.TVA) * coalesce(i1.coefdiscmaj,1)
                            * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) -  case when coalesce(NS.CodNirStoc, 0) = 0 then LV.PretAchiz else NS.Pret - NS.Adaos end)  '||chr(13)||
                     'end '||chr(13)||
                     'end adaos '||chr(13)||
                     'from IESIRI1 I1 '||chr(13)||
                     'INNER JOIN IESIRI  I  ON I1.CodIes     = I.CodIes '||chr(13)||
                     'INNER JOIN LIVR    L  ON I.CodIes      = L.CodIes '||chr(13)||
                     'INNER JOIN LIVR1   L1 ON I1.CodIes1    = L1.CodIes1 AND L1.CODLIVR = L.CODLIVR '||chr(13)||
                     'LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc '||chr(13)||
                     'LEFT  JOIN LIVRVAL LV ON L1.CodLivr1   = LV.CodLivr1 '||chr(13)||
                     'WHERE I.DATADOC  '||vCondData||' '||chr(13)||
                     PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL)||chr(13)||
                     'AND coalesce(I.Anulat, 0) = 0  '||chr(13)||
                     'AND coalesce(I.Initializari, 0) = 0 '||sCust||chr(13)||
                     'AND I.Operat = 1 AND I.TipDoc &lt;&gt; 26 '||chr(13)||
                     'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
                     'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0 '||chr(13)||
                     'UNION ALL'||chr(13)||
                     'SELECT I1.CodIes1, '||chr(13)||
                     'case '||chr(13)||
                     'when I.tipdoc &lt;&gt; 21 then'||chr(13)||
                     '  (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT end) end)
                        * (I1.PretOrig * coalesce(i1.coefdiscmaj,1)
                        * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) '||chr(13)||
                     'else (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT end) end)
                            * ((I1.PU-I1.TVA) * coalesce(i1.coefdiscmaj,1)
                            * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) '||chr(13)||
                     'end adaos '||chr(13)||
                     'from IESIRI1 I1 '||chr(13)||
                     'INNER JOIN IESIRI I ON I1.CodIes = I.CodIes '||chr(13)||
                     'WHERE I.DATADOC  '||vCondData||' '||chr(13)||
                     PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL)||chr(13)||
                     '  AND coalesce(I.Anulat, 0) = 0  '||chr(13)||
                     '  AND coalesce(I.Initializari, 0) = 0 '||sCust||chr(13)||
                     '  AND I.Operat = 1 AND I.TipDoc &lt;&gt; 26 AND I1.TIPLINIE = ''S'' '||chr(13)||
                     '  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0 '||chr(13)||
                     ')
                GROUP BY CodIes1 ';
      EXECUTE SWITH;
    else
      sWith := 'INSERT INTO TMP_TOPCLI_ADAOSURI(CODIES1,ADAOS) '||
               'select codies1, sum(adaos) adaos from ( '||chr(13)||
               'select I1.CodIes1, '||chr(13)||
               'case '||chr(13)||
               'when i1.tiplinie &lt;&gt; ''='' then 0 '||chr(13)||
               'else case '||chr(13)||
               'when I.tipdoc &lt;&gt; 21 then'||chr(13)||
               '(case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) end)
                  * (I1.PretOrig * coalesce(i1.coefdiscmaj,1)
                  * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) -  case when coalesce(NS.CodNirStoc, 0) = 0 then LV.PretAchiz else NS.Pret - NS.Adaos end) '||chr(13)||
               'else (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) end)
                      * ((I1.PU-I1.TVA) * coalesce(i1.coefdiscmaj,1)
                      * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) -  case when coalesce(NS.CodNirStoc, 0) = 0 then LV.PretAchiz else NS.Pret - NS.Adaos end)  '||chr(13)||
               'end '||chr(13)||
               'end adaos '||chr(13)||
               'from IESIRI1 I1 '||chr(13)||
               'INNER JOIN IESIRI  I  ON I1.CodIes     = I.CodIes '||chr(13)||
               'INNER JOIN LIVR    L  ON I.CodIes      = L.CodIes '||chr(13)||
               'INNER JOIN LIVR1   L1 ON I1.CodIes1    = L1.CodIes1 AND L1.CODLIVR = L.CODLIVR '||chr(13)||
               'LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc '||chr(13)||
               'LEFT  JOIN LIVRVAL LV ON L1.CodLivr1   = LV.CodLivr1 '||chr(13)||
               'WHERE I.DATADOC  '||vCondData||' '||chr(13)||
               PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL)||chr(13)||
               'AND coalesce(I.Anulat, 0) = 0  '||chr(13)||
               'AND coalesce(I.Initializari, 0) = 0 '||chr(13)||
               'AND I.Operat = 1 AND I.TipDoc not in (20, 26) '||chr(13)||
               'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
               'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0 '||chr(13)||
               'UNION ALL '||chr(13)||
               'select I1.CodIes1, '||chr(13)||
               'case '||chr(13)||
               'when i1.tiplinie &lt;&gt; ''='' then 0 '||chr(13)||
               'else case '||chr(13)||
               'when I.tipdoc &lt;&gt; 21 then'||chr(13)||
               '(case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT end) end)
                  * (I1.PretOrig * coalesce(i1.coefdiscmaj,1)
                  * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) ) '||chr(13)||
               'else (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)
                      * ((I1.PU-I1.TVA) * coalesce(i1.coefdiscmaj,1) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) )  '||chr(13)||
               'end '||chr(13)||
               'end adaos '||chr(13)||
               'from IESIRI1 I1 '||chr(13)||
               'INNER JOIN IESIRI I ON I1.CodIes = I.CodIes '||chr(13)||
               'WHERE I.DATADOC  '||vCondData||' '||chr(13)||
               PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL)||chr(13)||
               'AND coalesce(I.Anulat, 0) = 0  '||chr(13)||
               'AND coalesce(I.Initializari, 0) = 0 '||chr(13)||
               'AND I.Operat = 1 AND I.TipDoc not in (20, 26) AND I1.TIPLINIE = ''S'' '||chr(13)||
               'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0 '||chr(13)||
               'UNION ALL '||chr(13)||
               'select  '||chr(13)||
               'I1.CodIes1, '||chr(13)||
               'case when i1.tiplinie = ''S'' then 0 else I1.Cant * (I1.PretOrig * coalesce(i1.coefdiscmaj,1) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) -  case when coalesce(NS.CodNirStoc, 0) = 0 then LV.PretAchiz else NS.Pret - NS.Adaos end) end adaos '||chr(13)||
               'from IESIRI1       I1 '||chr(13)||
               'INNER JOIN IESIRI  I   ON I1.CodIes     = I.CodIes '||chr(13)||
               'INNER JOIN IESLINK L   ON I1.CodIes1    = L.CodIes1 '||chr(13)||
               'INNER JOIN IESIRI1 IV1 ON IV1.CodIes1   = L.CodLinieAviz '||chr(13)||
               'INNER JOIN LIVR1   L1  ON IV1.CodIes1   = L1.CodIes1 '||chr(13)||
               'LEFT  JOIN NIRSTOC NS  ON L1.CodNirStoc = NS.CodNirSToc '||chr(13)||
               'LEFT  JOIN LIVRVAL LV  ON L1.CodLivr1   = LV.CodLivr1 '||chr(13)||
               'WHERE I.DATADOC  '||vCondData||' '||chr(13)||
               PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL)||chr(13)||
               'AND coalesce(I.Anulat, 0) = 0  '||chr(13)||
               'AND coalesce(I.Initializari, 0) = 0 '||chr(13)||
               'AND I.Operat = 1 AND I.TipDoc = 26 '||chr(13)||
               'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
               'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0 '||chr(13)||
               'UNION ALL '||chr(13)||
               'select  '||chr(13)||
               'I1.CodIes1, '||chr(13)||
               'case when i1.tiplinie = ''S'' then 0 else I1.Cant * (I1.PretOrig * coalesce(i1.coefdiscmaj,1) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) ) end adaos '||chr(13)||
               'from IESIRI1       I1 '||chr(13)||
               'INNER JOIN IESIRI  I   ON I1.CodIes   = I.CodIes '||chr(13)||
               'INNER JOIN IESLINK L   ON I1.CodIes1  = L.CodIes1 '||chr(13)||
               'INNER JOIN IESIRI1 IV1 ON IV1.CodIes1 = L.CodLinieAviz '||chr(13)||
               'WHERE I.DATADOC  '||vCondData||' '||chr(13)||
               PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL)||chr(13)||
               'AND coalesce(I.Anulat, 0) = 0  '||chr(13)||
               'AND coalesce(I.Initializari, 0) = 0 '||chr(13)||
               'AND I.Operat = 1 AND I.TipDoc = 26 AND I1.TIPLINIE = ''S'' '||chr(13)||
               'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0 '||chr(13)||
               ')GROUP BY CodIes1 ';
      EXECUTE SWITH;
    end if;
  else
    if vAvize = 1 then
      sWith := 'INSERT INTO TMP_TOPCLI_ADAOSURI(CODIES1,ADAOS) '||
                'select codies1, sum(adaos) adaos from ( '||chr(13)||
                'select  '||chr(13)||
                'I1.CodIes1, '||chr(13)||
                'case when i1.tiplinie &lt;&gt; ''='' then 0 '||chr(13)||
                'else '||chr(13)||
                '(CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) * (I1.PretOrig * coalesce(i1.coefdiscmaj,1) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) -  case when coalesce(NS.CodNirStoc, 0) = 0 then LV.PretAchiz else NS.Pret - NS.Adaos end) end adaos '||chr(13)||
                'from IESIRI1       I1 '||chr(13)||
                'INNER JOIN IESIRI  I  ON I1.CodIes     = I.CodIes '||chr(13)||
                'INNER JOIN LIVR1   L1 ON I1.CodIes1    = L1.CodIes1 '||chr(13)||
                'INNER JOIN LIVR    L  ON I.CodIes      = L.CodIes AND L.CODLIVR = L1.CODLIVR '||chr(13)||
                'LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc '||chr(13)||
                'LEFT  JOIN LIVRVAL LV ON L1.CodLivr1   = LV.CodLivr1 '||chr(13)||
                'WHERE I.DATADOC  '||vCondData||' '||chr(13)||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL)||chr(13)||
                'AND coalesce(I.Anulat, 0) = 0  '||chr(13)||
                'AND coalesce(I.Initializari, 0) = 0 '||sCust||chr(13)||
                'AND I.Operat = 1 AND I.TipDoc &lt;&gt; 26 '||chr(13)||
                'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
                'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0 '||chr(13)||
                'UNION ALL '||chr(13)||
                'select  '||chr(13)||
                'I1.CodIes1, '||chr(13)||
                'case when i1.tiplinie &lt;&gt; ''='' then 0 '||chr(13)||
                'else '||chr(13)||
                '(case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) * (I1.PretOrig * coalesce(i1.coefdiscmaj,1) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) ) end adaos '||chr(13)||
                'from IESIRI1 I1 '||chr(13)||
                'INNER JOIN IESIRI I ON I1.CodIes = I.CodIes '||chr(13)||
                'WHERE I.DATADOC  '||vCondData||' '||chr(13)||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL)||chr(13)||
                'AND coalesce(I.Anulat, 0) = 0  '||chr(13)||
                'AND coalesce(I.Initializari, 0) = 0 '||sCust||chr(13)||
                'AND I.Operat = 1 AND I.TipDoc &lt;&gt; 26 AND I1.TIPLINIE = ''S'' '||chr(13)||
                'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0 '||chr(13)||
                ')GROUP BY CodIes1 ';
      EXECUTE SWITH;
    else
      sWith := 'INSERT INTO TMP_TOPCLI_ADAOSURI(CODIES1,ADAOS) '||
                'select codies1, sum(adaos) adaos from ( '||chr(13)||
                'select  '||chr(13)||
                'I1.CodIes1, '||chr(13)||
                'case when i1.tiplinie &lt;&gt; ''='' then 0 '||chr(13)||
                'else '||chr(13)||
                '(CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) * (I1.PretOrig * coalesce(i1.coefdiscmaj,1) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) -  case when coalesce(NS.CodNirStoc, 0) = 0 then LV.PretAchiz else NS.Pret - NS.Adaos end) end adaos '||chr(13)||
                'from IESIRI1       I1 '||chr(13)||
                'INNER JOIN IESIRI  I  ON I1.CodIes     = I.CodIes '||chr(13)||
                'INNER JOIN LIVR1   L1 ON I1.CodIes1    = L1.CodIes1 '||chr(13)||
                'INNER JOIN LIVR    L  ON I.CodIes      = L.CodIes AND L.CODLIVR = L1.CODLIVR '||chr(13)||
                'LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc '||chr(13)||
                'LEFT  JOIN LIVRVAL LV ON L1.CodLivr1   = LV.CodLivr1 '||chr(13)||
                'WHERE I.DATADOC  '||vCondData||' '||chr(13)||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL)||chr(13)||
                'AND coalesce(I.Anulat, 0) = 0  '||chr(13)||
                'AND coalesce(I.Initializari, 0) = 0 '||chr(13)||
                'AND I.Operat = 1 AND I.TipDoc not in (20, 26) '||chr(13)||
                'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
                'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0 '||chr(13)||
                'UNION ALL '||chr(13)||
                'select  '||chr(13)||
                'I1.CodIes1, '||chr(13)||
                'case when i1.tiplinie &lt;&gt; ''='' then 0 '||chr(13)||
                'else '||chr(13)||
                '(case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) * (I1.PretOrig * coalesce(i1.coefdiscmaj,1) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) ) end adaos '||chr(13)||
                'from IESIRI1 I1 '||chr(13)||
                'INNER JOIN IESIRI I ON I1.CodIes = I.CodIes '||chr(13)||
                'WHERE I.DATADOC  '||vCondData||' '||chr(13)||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL)||chr(13)||
                'AND coalesce(I.Anulat, 0) = 0  '||chr(13)||
                'AND coalesce(I.Initializari, 0) = 0 '||chr(13)||
                'AND I.Operat = 1 AND I.TipDoc not in (20, 26) AND I1.TIPLINIE = ''S'' '||chr(13)||
                'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0 '||chr(13)||
                'UNION ALL '||chr(13)||
                'select  '||chr(13)||
                'I1.CodIes1, '||chr(13)||
                'case when i1.tiplinie = ''S'' then 0 else (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) * (I1.PretOrig * coalesce(i1.coefdiscmaj,1) -  case when coalesce(NS.CodNirStoc, 0) = 0 then LV.PretAchiz else NS.Pret - NS.Adaos end) end adaos '||chr(13)||
                'from IESIRI1       I1 '||chr(13)||
                'INNER JOIN IESIRI  I   ON I1.CodIes     = I.CodIes '||chr(13)||
                'INNER JOIN IESLINK L   ON I1.CodIes1    = L.CodIes1 '||chr(13)||
                'INNER JOIN IESIRI1 IV1 ON IV1.CodIes1   = L.CodLinieAviz '||chr(13)||
                'INNER JOIN IESIRI  IV  ON IV.CodIes     = IV.CodIES '||chr(13)||
                'INNER JOIN LIVR1   L1  ON IV1.CodIes1   = L1.CodIes1 '||chr(13)||
                'INNER JOIN LIVR    L   ON IV.CodIes     = L.CodIes AND L1.CODLIVR = L.CODLIVR '||chr(13)||
                'LEFT  JOIN NIRSTOC NS  ON L1.CodNirStoc = NS.CodNirSToc '||chr(13)||
                'LEFT  JOIN LIVRVAL LV  ON L1.CodLivr1   = LV.CodLivr1 '||chr(13)||
                'WHERE I.DATADOC  '||vCondData||' '||chr(13)||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL)||chr(13)||
                'AND coalesce(I.Anulat, 0) = 0  '||chr(13)||
                'AND coalesce(I.Initializari, 0) = 0 '||chr(13)||
                'AND I.Operat = 1 AND I.TipDoc = 26 '||chr(13)||
                'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
                'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0 '||chr(13)||
                'UNION ALL '||chr(13)||
                'select  '||chr(13)||
                'I1.CodIes1, '||chr(13)||
                'case when i1.tiplinie = ''S'' then 0 else (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) * (I1.PretOrig * coalesce(i1.coefdiscmaj,1)) end adaos '||chr(13)||
                'from IESIRI1       I1 '||chr(13)||
                'INNER JOIN IESIRI  I   ON I1.CodIes   = I.CodIes '||chr(13)||
                'INNER JOIN IESLINK L   ON I1.CodIes1  = L.CodIes1 '||chr(13)||
                'INNER JOIN IESIRI1 IV1 ON IV1.CodIes1 = L.CodLinieAviz '||chr(13)||
                'WHERE I.DATADOC  '||vCondData||' '||chr(13)||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL)||chr(13)||
                'AND coalesce(I.Anulat, 0) = 0  '||chr(13)||
                'AND coalesce(I.Initializari, 0) = 0 '||chr(13)||
                'AND I.Operat = 1 AND I.TipDoc = 26 AND I1.TIPLINIE = ''S'' '||chr(13)||
                'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0 '||chr(13)||
                ')GROUP BY CodIes1 ';
      EXECUTE SWITH;
    end if;
  end if;


  if vSubunit then
    if vSediiL = 0 then
      if vOrder in (1,3) then
        if vAvize = 1 then
          sWith :=
              'INSERT INTO TMP_TOPCLI_VALCLIENT (
                CODPART,
                SUBUNITATEA,
                VALTOT,
                VALTOT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL)'||chr(13)||
                'SELECT S.CodPart,'||chr(13)||
                       'S.Subunitatea,'||chr(13)||
                       'SUM(S.ValTot) ValTot,'||chr(13)||
                       '0 ValTot_Val,'||chr(13)||
                       'SUM(S.AdaosTot) AdaosTot,'||chr(13)||
                       '0 AdaosTot_Val'||chr(13)||
                'FROM'||chr(13)||
                '('||chr(13)||
                'SELECT'||chr(13)||
                    'I.Partener CodPart,'||chr(13)||
                    'I.Subunitatea,'||chr(13)||
                    'case'||chr(13)||
                    'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                    '(i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'else'||chr(13)||
                    '(I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'end ValTot,'||chr(13)||
                    'ADAOSURI.ADAOS ADAOSTOT'||chr(13)||
                  'FROM IESIRI I'||chr(13)||
                       'INNER JOIN IESIRI1 I1 ON I1.CODIES     = I.CODIES'||chr(13)||
                       'INNER JOIN NPART   P  ON I.PARTENER    = P.CODPART'||chr(13)||
                       'INNER JOIN LIVR1   L1 ON I1.CodIes1    = L1.CodIes1'||chr(13)||
                       'INNER JOIN LIVR    L  ON I.CodIes      = L.CodIes AND L.CODLIVR = L1.CODLIVR'||chr(13)||
                       'LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc'||chr(13)||
                       'LEFT  JOIN LIVRVAL LV ON L1.CodLivr1   = LV.CodLivr1'||chr(13)||
                       'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
                  'WHERE I.DATADOC '||vCondData||
                  'AND I.TipDoc  NOT IN (21, 26)'||chr(13)||
                  'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
                  'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
                  'AND I.Operat = 1 '||sCust||''||chr(13)||
                  'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'''||chr(13)||
                  'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
                  'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
                'UNION ALL'||chr(13)||
                'SELECT'||chr(13)||
                    'I.Partener CodPart,'||chr(13)||
                    'I.Subunitatea,'||chr(13)||
                    'case'||chr(13)||
                    'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                    '(i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'else'||chr(13)||
                    '(I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'end ValTot,'||chr(13)||
                    'ADAOSURI.ADAOS ADAOSTOT'||chr(13)||
                  'FROM IESIRI I'||chr(13)||
                       'INNER JOIN IESIRI1 I1 ON I1.CODIES  = I.CODIES'||chr(13)||
                       'INNER JOIN NPART   P  ON I.PARTENER = P.CODPART'||chr(13)||
                       'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
                  'WHERE I.DATADOC '||vCondData||''||chr(13)||
                  'AND I.TipDoc  NOT IN (21, 26)'||chr(13)||
                  'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
                  'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
                  'AND I.Operat = 1 '||sCust||''||chr(13)||
                  'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S'''||chr(13)||
                  'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
                'UNION ALL'||chr(13)||
                  'SELECT'||chr(13)||
                    'I.Partener CodPart,'||chr(13)||
                    'I.Subunitatea,'||chr(13)||
                    'SUM(case'||chr(13)||
                        'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                       '((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                        'else'||chr(13)||
                       '(I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                        'end) ValTot,'||chr(13)||
                        'sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT'||chr(13)||
                  'FROM IESIRI I'||chr(13)||
                       'INNER JOIN IESIRI1 I1 ON I1.CODIES     = I.CODIES'||chr(13)||
                       'INNER JOIN NPART   P  ON I.PARTENER    = P.CODPART'||chr(13)||
                       'INNER JOIN LIVR1   L1 ON I1.CodIes1    = L1.CodIes1'||chr(13)||
                       'INNER JOIN LIVR    L  ON I.CodIes      = L.CodIes AND L.CODLIVR = L1.CODLIVR'||chr(13)||
                       'LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc'||chr(13)||
                       'LEFT  JOIN LIVRVAL LV ON L1.CodLivr1   = LV.CodLivr1'||chr(13)||
                       'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
                  'WHERE I.DATADOC '||vCondData||''||chr(13)||
                  'AND I.TipDoc = 21'||chr(13)||
                  'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
                  'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
                  'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'''||chr(13)||
                  'AND I.Operat = 1'||chr(13)||
                  'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
                  'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
                  'GROUP BY I.Partener, I.Subunitatea'||chr(13)||
                'UNION ALL'||chr(13)||
                  'SELECT'||chr(13)||
                    'I.Partener CodPart,'||chr(13)||
                    'I.Subunitatea,'||chr(13)||
                    'SUM(case'||chr(13)||
                        'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                       '((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                        'else'||chr(13)||
                       '(I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                        'end) ValTot,'||chr(13)||
                        'SUM(ADAOSURI.ADAOS) ADAOSTOT'||chr(13)||
                  'FROM IESIRI I'||chr(13)||
                       'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                       'INNER JOIN NPART P ON I.PARTENER = P.CODPART'||chr(13)||
                       'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
                  'WHERE I.DATADOC '||vCondData||''||chr(13)||
                  'AND I.TipDoc = 21'||chr(13)||
                  'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
                  'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
                  'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S'''||chr(13)||
                  'AND I.Operat = 1'||chr(13)||
                  'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
                  'GROUP BY I.Partener, I.Subunitatea'||chr(13);
           if vWithEmul then
             sWith := sWith||
             'UNION ALL'||chr(13)||
             'SELECT '||chr(13)||
               'E.CODPART,'||chr(13)||
               'C.SUBUNITATEA,'||chr(13)||
               'SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,'||chr(13)||
               '0 ADAOSTOT'||chr(13)||
             'FROM EMULARE E'||chr(13)||
                  'INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE'||chr(13)||
                  'INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT'||chr(13)||
             'WHERE E.DATABON '||vCondData||chr(13)||
                   'AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0'||chr(13)||
                   'AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0'||chr(13)||
             'GROUP BY E.CODPART, C.SUBUNITATEA'||chr(13);
           end if;
           swith := swith||
              '   ) S'||chr(13)||
              '   GROUP BY S.CodPart, S.Subunitatea';
           EXECUTE SWITH;

           SWITH := 'INSERT INTO TMP_TOPCLI_ValAgent '||chr(13)||
              '(
                AGENT,
                SUBUNITATEA,
                VALTOTAGENT,
                VALTOTAGENT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL
                )'||chr(13)||
                'SELECT S.Agent,'||chr(13)||
                       'S.Subunitatea,'||chr(13)||
                       'SUM(S.ValTot) ValTotAgent,'||chr(13)||
                       '0 ValTotAgent_Val,'||chr(13)||
                       'SUM(S.AdaosTot) AdaosTot,'||chr(13)||
                       '0 AdaosTot_Val'||chr(13)||
                'FROM'||chr(13)||
                '('||chr(13)||
                'SELECT'||chr(13)||
                    'I.Agent,'||chr(13)||
                    'I.Subunitatea,'||chr(13)||
                    'SUM(case'||chr(13)||
                        'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                        '(i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                        'else'||chr(13)||
                        '(I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                        'end) ValTot,'||chr(13)||
                    'sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT'||chr(13)||
                  'FROM IESIRI I'||chr(13)||
                       'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                       'INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1'||chr(13)||
                       'INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR'||chr(13)||
                       'LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc'||chr(13)||
                       'LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1'||chr(13)||
                       'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
                  'WHERE I.DATADOC '||vCondData||''||chr(13)||
                  'AND I.TipDoc  NOT IN (21, 26)'||chr(13)||
                  'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
                  'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
                  'AND I.Operat = 1 '||sCust||''||chr(13)||
                  'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'''||chr(13)||
                  'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
                  'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
                  'GROUP BY I.Agent, I.Subunitatea'||chr(13)||
                'UNION ALL'||chr(13)||
                'SELECT'||chr(13)||
                    'I.Agent,'||chr(13)||
                    'I.Subunitatea,'||chr(13)||
                    'SUM(case'||chr(13)||
                        'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                        '(i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                        'else'||chr(13)||
                        '(I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                        'end) ValTot,'||chr(13)||
                    'SUM(ADAOSURI.ADAOS) ADAOSTOT'||chr(13)||
                  'FROM IESIRI I'||chr(13)||
                       'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                       'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
                  'WHERE I.DATADOC '||vCondData||''||chr(13)||
                  'AND I.TipDoc  NOT IN (21, 26)'||chr(13)||
                  'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
                  'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
                  'AND I.Operat = 1 '||sCust||''||chr(13)||
                  'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S'''||chr(13)||
                  'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
                  'GROUP BY I.Agent, I.Subunitatea'||chr(13)||
                'UNION ALL'||chr(13)||
                  'SELECT'||chr(13)||
                    'I.Agent,'||chr(13)||
                    'I.Subunitatea,'||chr(13)||
                    'SUM(case'||chr(13)||
                        'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                       '((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                        'else'||chr(13)||
                       '(I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                        'end) ValTot,'||chr(13)||
                    'sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT'||chr(13)||
                  'FROM IESIRI I'||chr(13)||
                       'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                       'INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1'||chr(13)||
                       'INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR AND L1.CODLIVR = L.CODLIVR'||chr(13)||
                       'LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc'||chr(13)||
                       'LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1'||chr(13)||
                       'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
                  'WHERE I.DATADOC '||vCondData||''||chr(13)||
                  'AND I.TipDoc = 21'||chr(13)||
                  'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
                  'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
                  'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'''||chr(13)||
                  'AND I.Operat = 1'||chr(13)||
                  'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
                  'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
                  'GROUP BY I.Agent, I.Subunitatea'||chr(13)||
                'UNION ALL'||chr(13)||
                  'SELECT'||chr(13)||
                    'I.Agent,'||chr(13)||
                    'I.Subunitatea,'||chr(13)||
                    'SUM(case'||chr(13)||
                        'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                       '((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                        'else'||chr(13)||
                       '(I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                        'end) ValTot,'||chr(13)||
                    'SUM(ADAOSURI.ADAOS) ADAOSTOT'||chr(13)||
                  'FROM IESIRI I'||chr(13)||
                       'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                       'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
                  'WHERE I.DATADOC '||vCondData||''||chr(13)||
                  'AND I.TipDoc = 21'||chr(13)||
                  'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
                  'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
                  'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S'''||chr(13)||
                  'AND I.Operat = 1'||chr(13)||
                  'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
                  'GROUP BY I.Agent, I.Subunitatea';
           if vWithEmul then
             sWith := sWith||
             'UNION ALL'||chr(13)||
             'SELECT '||chr(13)||
               'E.CODAGENT AGENT,'||chr(13)||
               'C.SUBUNITATEA,'||chr(13)||
               'SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,'||chr(13)||
               '0 ADAOSTOT'||chr(13)||
             'FROM EMULARE E'||chr(13)||
                  'INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE'||chr(13)||
                  'INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT'||chr(13)||
             'WHERE E.DATABON '||vCondData||''||chr(13)||
                   'AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0'||chr(13)||
                   'AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0'||chr(13)||
             'GROUP BY E.CODAGENT, C.SUBUNITATEA';
           end if;
           swith := swith||
                 ') S'||chr(13)||
                 'GROUP BY S.Agent, S.Subunitatea';
           EXECUTE SWITH;

           SWITH :=
              'INSERT INTO TMP_TOPCLI_ValAgentArt (
                 AGENT,
                 SUBUNITATEA,
                 CODOBIECT,
                 VALTOTAGENT,
                 VALTOTAGENT_VAL,
                 CANT,
                 ADAOSTOT,
                 ADAOSTOT_VAL
               )
               SELECT S.Agent,'||chr(13)||
                       'S.Subunitatea,'||chr(13)||
                       'S.CodObiect,'||chr(13)||
                       'SUM(S.ValTot) ValTotAgent,'||chr(13)||
                       '0 ValTotAgent_Val,'||chr(13)||
                       'SUM(S.Cant) Cant,'||chr(13)||
                       'SUM(S.AdaosTot) AdaosTot,'||chr(13)||
                       '0 AdaosTot_Val'||chr(13)||
                'FROM'||chr(13)||
                '('||chr(13)||
                'SELECT'||chr(13)||
                    'I.Agent,'||chr(13)||
                    'I.Subunitatea,'||chr(13)||
                    'I1.CodObiect,'||chr(13)||
                    'SUM(case'||chr(13)||
                        'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                        '(i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                        'else'||chr(13)||
                        '(I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                        'end) ValTot,'||chr(13)||
                    'SUM((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) Cant,'||chr(13)||
                    'sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT'||chr(13)||
                  'FROM IESIRI I'||chr(13)||
                       'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                       'INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1'||chr(13)||
                       'INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR'||chr(13)||
                       'LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc'||chr(13)||
                       'LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1'||chr(13)||
                       'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
                  'WHERE I.DATADOC '||vCondData||chr(13)||
                  'AND I.TipDoc  NOT IN (21, 26)'||chr(13)||
                  'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
                  'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
                  'AND I.Operat = 1 '||sCust||''||chr(13)||
                  'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'''||chr(13)||
                  'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
                  'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
                  'GROUP BY I.Agent, I.Subunitatea, I1.CodObiect'||chr(13)||
                'UNION ALL'||chr(13)||
                  'SELECT'||chr(13)||
                    'I.Agent,'||chr(13)||
                    'I.Subunitatea,'||chr(13)||
                    'I1.CodObiect,'||chr(13)||
                    'SUM(case'||chr(13)||
                        'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                        '(i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                        'else'||chr(13)||
                        '(I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                        'end) ValTot,'||chr(13)||
                    'SUM((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) Cant,'||chr(13)||
                    'SUM(ADAOSURI.ADAOS) ADAOSTOT'||chr(13)||
                  'FROM IESIRI I'||chr(13)||
                       'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                       'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
                  'WHERE I.DATADOC '||vCondData||''||chr(13)||
                  'AND I.TipDoc  NOT IN (21, 26)'||chr(13)||
                  'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
                  'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
                  'AND I.Operat = 1 '||sCust||''||chr(13)||
                  'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S'''||chr(13)||
                  'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
                  'GROUP BY I.Agent, I.Subunitatea, I1.CodObiect'||chr(13)||
                'UNION ALL'||chr(13)||
                  'SELECT'||chr(13)||
                    'I.Agent,'||chr(13)||
                    'I.Subunitatea,'||chr(13)||
                    'I1.CodObiect,'||chr(13)||
                    'SUM(case'||chr(13)||
                        'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                       '((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                        'else'||chr(13)||
                       '(I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                        'end) ValTot,'||chr(13)||
                    'SUM((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) Cant,'||chr(13)||
                    'sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT'||chr(13)||
                  'FROM IESIRI I'||chr(13)||
                       'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                       'INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1'||chr(13)||
                       'INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR'||chr(13)||
                       'LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc'||chr(13)||
                       'LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1'||chr(13)||
                       'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
                  'WHERE I.DATADOC '||vCondData||''||chr(13)||
                  'AND I.TipDoc = 21'||chr(13)||
                  'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
                  'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
                  'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'''||chr(13)||
                  'AND I.Operat = 1'||chr(13)||
                  'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
                  'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
                  'GROUP BY I.Agent, I.Subunitatea, I1.CodObiect'||chr(13)||
                'UNION ALL'||chr(13)||
                  'SELECT'||chr(13)||
                    'I.Agent,'||chr(13)||
                    'I.Subunitatea,'||chr(13)||
                    'I1.CodObiect,'||chr(13)||
                    'SUM(case'||chr(13)||
                        'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                       '((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                        'else'||chr(13)||
                       '(I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                        'end) ValTot,'||chr(13)||
                    'SUM((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) Cant,'||chr(13)||
                    'SUM(ADAOSURI.ADAOS) ADAOSTOT'||chr(13)||
                  'FROM IESIRI I'||chr(13)||
                       'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                       'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
                  'WHERE I.DATADOC '||vCondData||''||chr(13)||
                  'AND I.TipDoc = 21'||chr(13)||
                  'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
                  'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
                  'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S'''||chr(13)||
                  'AND I.Operat = 1'||chr(13)||
                  'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
                  'GROUP BY I.Agent, I.Subunitatea, I1.CodObiect';
           if vWithEmul then
             sWith := sWith||
             'UNION ALL'||chr(13)||
             'SELECT '||chr(13)||
             '  E.CODAGENT AGENT,'||chr(13)||
             '  C.SUBUNITATEA,'||chr(13)||
             '  E1.CODOBIECT,'||chr(13)||
             '  SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,'||chr(13)||
             '  SUM(E1.CANT) CANT,'||chr(13)||
             '  0 ADAOSTOT'||chr(13)||
             'FROM EMULARE E'||chr(13)||
                  'INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE'||chr(13)||
                  'INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT'||chr(13)||
             'WHERE E.DATABON '||vCondData||''||chr(13)||
                   'AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0'||chr(13)||
                   'AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0'||chr(13)||
             'GROUP BY E.CODAGENT, E.CODPART, E.CODLOCATIE, C.SUBUNITATEA,E1.CODOBIECT';
           end if;
           swith := swith||'
                 ) S
                 GROUP BY S.Agent, S.Subunitatea, S.CodObiect';
           EXECUTE SWITH;
        else
          sWith :=
          'INSERT INTO TMP_TOPCLI_VALCLIENT (
                CODPART,
                SUBUNITATEA,
                VALTOT,
                VALTOT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL)'||chr(13)||
            'SELECT S.CodPart,'||chr(13)||
                   'S.Subunitatea,'||chr(13)||
                   'SUM(S.ValTot) ValTot,'||chr(13)||
                   '0 ValTot_Val,'||chr(13)||
                   'SUM(S.AdaosTot) AdaosTot,'||chr(13)||
                   '0 AdaosTot_Val'||chr(13)||
            'FROM'||chr(13)||
            '('||chr(13)||
            'SELECT'||chr(13)||
                'I.Partener CodPart,'||chr(13)||
                'I.Subunitatea,'||chr(13)||
                'SUM(case'||chr(13)||
                    'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                    '(i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'else'||chr(13)||
                    '(I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'end) ValTot,'||chr(13)||
                    'sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT'||chr(13)||
              'FROM IESIRI I'||chr(13)||
                   'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                   'INNER JOIN NPART P ON I.PARTENER = P.CODPART'||chr(13)||
                   'INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1'||chr(13)||
                   'INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR'||chr(13)||
                   'LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc'||chr(13)||
                   'LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1'||chr(13)||
                   'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
              'WHERE I.DATADOC '||vCondData||''||chr(13)||
              'AND I.TipDoc  NOT IN (21, 20)'||chr(13)||
              'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
              'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
              'AND I.Operat = 1'||chr(13)||
              'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'''||chr(13)||
              'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
              'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
              'GROUP BY I.Partener, I.Subunitatea'||chr(13)||
            'UNION ALL'||chr(13)||
            'SELECT'||chr(13)||
                'I.Partener CodPart,'||chr(13)||
                'I.Subunitatea,'||chr(13)||
                'SUM(case'||chr(13)||
                    'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                    '(i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'else'||chr(13)||
                    '(I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'end) ValTot,'||chr(13)||
                    'SUM(ADAOSURI.ADAOS) ADAOSTOT'||chr(13)||
              'FROM IESIRI I'||chr(13)||
                   'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                   'INNER JOIN NPART P ON I.PARTENER = P.CODPART'||chr(13)||
                   'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
              'WHERE I.DATADOC '||vCondData||''||chr(13)||
              'AND I.TipDoc  NOT IN (21, 20)'||chr(13)||
              'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
              'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
              'AND I.Operat = 1'||chr(13)||
              'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S'''||chr(13)||
              'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
            'GROUP BY I.Partener, I.Subunitatea'||chr(13)||
            'UNION ALL'||chr(13)||
              'SELECT'||chr(13)||
                'I.Partener CodPart,'||chr(13)||
                'I.Subunitatea,'||chr(13)||
                'SUM(case'||chr(13)||
                    'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                   '((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'else'||chr(13)||
                   '(I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'end) ValTot,'||chr(13)||
                    'sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT'||chr(13)||
              'FROM IESIRI I'||chr(13)||
                   'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                   'INNER JOIN NPART P ON I.PARTENER = P.CODPART'||chr(13)||
                   'INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1'||chr(13)||
                   'INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR'||chr(13)||
                   'LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc'||chr(13)||
                   'LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1'||chr(13)||
                   'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
              'WHERE I.DATADOC '||vCondData||''||chr(13)||
              'AND I.TipDoc = 21'||chr(13)||
              'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
              'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
              'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'''||chr(13)||
              'AND I.Operat = 1'||chr(13)||
              'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
              'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
              'GROUP BY I.Partener, I.Subunitatea'||chr(13)||
            'UNION ALL'||chr(13)||
              'SELECT'||chr(13)||
                'I.Partener CodPart,'||chr(13)||
                'I.Subunitatea,'||chr(13)||
                'SUM(case'||chr(13)||
                    'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                   '((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'else'||chr(13)||
                   '(I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'end) ValTot,'||chr(13)||
                    'SUM(ADAOSURI.ADAOS) ADAOSTOT'||chr(13)||
              'FROM IESIRI I'||chr(13)||
                   'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                   'INNER JOIN NPART P ON I.PARTENER = P.CODPART'||chr(13)||
                   'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
              'WHERE I.DATADOC '||vCondData||''||chr(13)||
              'AND I.TipDoc = 21'||chr(13)||
              'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
              'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
              'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S'''||chr(13)||
              'AND I.Operat = 1'||chr(13)||
              'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
              'GROUP BY I.Partener, I.Subunitatea'||chr(13);
           if vWithEmul then
             sWith := sWith||''||chr(13)||
             'UNION ALL'||chr(13)||
             'SELECT '||chr(13)||
               'E.CODPART,'||chr(13)||
               'C.SUBUNITATEA,'||chr(13)||
               'SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,'||chr(13)||
               '0 ADAOSTOT'||chr(13)||
             'FROM EMULARE E'||chr(13)||
                  'INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE'||chr(13)||
                  'INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT'||chr(13)||
             'WHERE E.DATABON '||vCondData||''||chr(13)||
                   'AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0'||chr(13)||
                   'AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0'||chr(13)||
             'GROUP BY E.CODPART, C.SUBUNITATEA'||chr(13);
           end if;
           swith := swith||''||chr(13)||
             ') S'||chr(13)||
             'GROUP BY S.CodPart, S.Subunitatea';

          EXECUTE SWITH;

          SWITH := 'INSERT INTO TMP_TOPCLI_ValAgent '||chr(13)||
              '(
                AGENT,
                SUBUNITATEA,
                VALTOTAGENT,
                VALTOTAGENT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL
                )'||chr(13)||
            'SELECT S.Agent,'||chr(13)||
                   'S.Subunitatea,'||chr(13)||
                   'SUM(S.ValTot) ValTotAgent,'||chr(13)||
                   '0 ValTotAgent_Val,'||chr(13)||
                   'SUM(S.AdaosTot) AdaosTot,'||chr(13)||
                   '0 AdaosTot_Val'||chr(13)||
            'FROM'||chr(13)||
            '('||chr(13)||
            'SELECT'||chr(13)||
                'I.Agent,'||chr(13)||
                'I.Subunitatea,'||chr(13)||
                'SUM(case'||chr(13)||
                    'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                    '(i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'else'||chr(13)||
                    '(I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'end) ValTot,'||chr(13)||
                    'sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT'||chr(13)||
              'FROM IESIRI I'||chr(13)||
                   'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                   'INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1'||chr(13)||
                   'INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR'||chr(13)||
                   'LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc'||chr(13)||
                   'LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1'||chr(13)||
                   'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
              'WHERE I.DATADOC '||vCondData||''||chr(13)||
              'AND I.TipDoc  NOT IN (21, 20)'||chr(13)||
              'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
              'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
              'AND I.Operat = 1'||chr(13)||
              'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'''||chr(13)||
              'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
              'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
              'GROUP BY I.Agent, I.Subunitatea'||chr(13)||
            'UNION ALL'||chr(13)||
            'SELECT'||chr(13)||
                'I.Agent,'||chr(13)||
                'I.Subunitatea,'||chr(13)||
                'SUM(case'||chr(13)||
                    'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                    '(i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'else'||chr(13)||
                    '(I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'end) ValTot,'||chr(13)||
                    'SUM(ADAOSURI.ADAOS) ADAOSTOT'||chr(13)||
              'FROM IESIRI I'||chr(13)||
                   'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                   'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
              'WHERE I.DATADOC '||vCondData||''||chr(13)||
              'AND I.TipDoc  NOT IN (21, 20)'||chr(13)||
              'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
              'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
              'AND I.Operat = 1'||chr(13)||
              'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S'''||chr(13)||
              'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
              'GROUP BY I.Agent, I.Subunitatea'||chr(13)||
            'UNION ALL'||chr(13)||
              'SELECT'||chr(13)||
                'I.Agent,'||chr(13)||
                'I.Subunitatea,'||chr(13)||
                'SUM(case'||chr(13)||
                    'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                   '((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'else'||chr(13)||
                   '(I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'end) ValTot,'||chr(13)||
                    'sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT'||chr(13)||
              'FROM IESIRI I'||chr(13)||
                   'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                   'INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1'||chr(13)||
                   'INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR'||chr(13)||
                   'LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc'||chr(13)||
                   'LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1'||chr(13)||
                   'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
              'WHERE I.DATADOC '||vCondData||''||chr(13)||
              'AND I.TipDoc = 21'||chr(13)||
              'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
              'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
              'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'''||chr(13)||
              'AND I.Operat = 1'||chr(13)||
              'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
              'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
              'GROUP BY I.Agent, I.Subunitatea'||chr(13)||
            'UNION ALL'||chr(13)||
              'SELECT'||chr(13)||
                'I.Agent,'||chr(13)||
                'I.Subunitatea,'||chr(13)||
                'SUM(case'||chr(13)||
                    'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                   '((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'else'||chr(13)||
                   '(I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'end) ValTot,'||chr(13)||
                    'SUM(ADAOSURI.ADAOS) ADAOSTOT'||chr(13)||
              'FROM IESIRI I'||chr(13)||
                   'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                   'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
              'WHERE I.DATADOC '||vCondData||''||chr(13)||
              'AND I.TipDoc = 21'||chr(13)||
              'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
              'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
              'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S'''||chr(13)||
              'AND I.Operat = 1'||chr(13)||
              'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
              'GROUP BY I.Agent, I.Subunitatea'||chr(13);
           if vWithEmul then
             sWith := sWith||
             'UNION ALL'||chr(13)||
             'SELECT '||chr(13)||
               'E.CODAGENT AGENT,'||chr(13)||
               'C.SUBUNITATEA,'||chr(13)||
               'SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,'||chr(13)||
               '0 ADAOSTOT'||chr(13)||
             'FROM EMULARE E'||chr(13)||
                  'INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE'||chr(13)||
                  'INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT'||chr(13)||
             'WHERE E.DATABON '||vCondData||''||chr(13)||
                   'AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0'||chr(13)||
                   'AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0'||chr(13)||
             'GROUP BY E.CODAGENT, C.SUBUNITATEA'||chr(13);
           end if;
           swith := swith||
             ') S'||chr(13)||
             'GROUP BY S.Agent, S.Subunitatea';
          EXECUTE SWITH;

          SWITH :=
              'INSERT INTO TMP_TOPCLI_ValAgentArt (
                 AGENT,
                 SUBUNITATEA,
                 CODOBIECT,
                 VALTOTAGENT,
                 VALTOTAGENT_VAL,
                 CANT,
                 ADAOSTOT,
                 ADAOSTOT_VAL
               )
            SELECT S.Agent,'||chr(13)||
                   'S.Subunitatea,'||chr(13)||
                   'S.CodObiect,'||chr(13)||
                   'SUM(S.ValTot) ValTotAgent,'||chr(13)||
                   '0 ValTotAgent_Val,'||chr(13)||
                   'SUM(S.Cant) Cant,'||chr(13)||
                   'SUM(S.AdaosTot) AdaosTot,'||chr(13)||
                   '0 AdaosTot_Val'||chr(13)||
            'FROM'||chr(13)||
            '('||chr(13)||
            'SELECT'||chr(13)||
                'I.Agent,'||chr(13)||
                'I.Subunitatea,'||chr(13)||
                'I1.CodObiect,'||chr(13)||
                'SUM(case'||chr(13)||
                    'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                    '(i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'else'||chr(13)||
                    '(I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'end) ValTot,'||chr(13)||
                'SUM((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) Cant,'||chr(13)||
                'sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT'||chr(13)||
              'FROM IESIRI I'||chr(13)||
                   'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                   'INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1'||chr(13)||
                   'INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR'||chr(13)||
                   'LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc'||chr(13)||
                   'LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1'||chr(13)||
                   'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
              'WHERE I.DATADOC '||vCondData||''||chr(13)||
              'AND I.TipDoc  NOT IN (21, 20)'||chr(13)||
              'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
              'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
              'AND I.Operat = 1'||chr(13)||
              'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'''||chr(13)||
              'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
              'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
              'GROUP BY I.Agent, I.Subunitatea, I1.CodObiect'||chr(13)||
            'UNION ALL'||chr(13)||
            'SELECT'||chr(13)||
                'I.Agent,'||chr(13)||
                'I.Subunitatea,'||chr(13)||
                'I1.CodObiect,'||chr(13)||
                'SUM(case'||chr(13)||
                    'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                    '(i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'else'||chr(13)||
                    '(I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'end) ValTot,'||chr(13)||
                'SUM((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) Cant,'||chr(13)||
                'SUM(ADAOSURI.ADAOS) ADAOSTOT'||chr(13)||
              'FROM IESIRI I'||chr(13)||
                   'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                   'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
              'WHERE I.DATADOC '||vCondData||''||chr(13)||
              'AND I.TipDoc  NOT IN (21, 20)'||chr(13)||
              'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
              'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
              'AND I.Operat = 1'||chr(13)||
              'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S'''||chr(13)||
              'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
              'GROUP BY I.Agent, I.Subunitatea, I1.CodObiect'||chr(13)||
            'UNION ALL'||chr(13)||
              'SELECT'||chr(13)||
                'I.Agent,'||chr(13)||
                'I.Subunitatea,'||chr(13)||
                'I1.CodObiect,'||chr(13)||
                'SUM(case'||chr(13)||
                    'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                   '((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'else'||chr(13)||
                   '(I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'end) ValTot,'||chr(13)||
                'SUM((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) Cant,'||chr(13)||
                'sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT'||chr(13)||
              'FROM IESIRI I'||chr(13)||
                   'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                   'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
                   'INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1'||chr(13)||
                   'INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR'||chr(13)||
                   'LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc'||chr(13)||
                   'LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1'||chr(13)||
              'WHERE I.DATADOC '||vCondData||''||chr(13)||
              'AND I.TipDoc = 21'||chr(13)||
              'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
              'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
              'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'''||chr(13)||
              'AND I.Operat = 1'||chr(13)||
              'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
              'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
              'GROUP BY I.Agent, I.Subunitatea, I1.CodObiect'||chr(13)||
           'UNION ALL'||chr(13)||
              'SELECT'||chr(13)||
                'I.Agent,'||chr(13)||
                'I.Subunitatea,'||chr(13)||
                'I1.CodObiect,'||chr(13)||
                'SUM(case'||chr(13)||
                    'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                   '((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'else'||chr(13)||
                   '(I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                    'end) ValTot,'||chr(13)||
                'SUM((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) Cant,'||chr(13)||
                'SUM(ADAOSURI.ADAOS) ADAOSTOT'||chr(13)||
              'FROM IESIRI I'||chr(13)||
                   'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                   'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
              'WHERE I.DATADOC '||vCondData||''||chr(13)||
              'AND I.TipDoc = 21'||chr(13)||
              'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
              'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
              'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S'''||chr(13)||
              'AND I.Operat = 1'||chr(13)||
              'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
              'GROUP BY I.Agent, I.Subunitatea, I1.CodObiect'||chr(13);
           if vWithEmul then
             sWith := sWith||
             'UNION ALL'||chr(13)||
             'SELECT '||chr(13)||
               'E.CODAGENT AGENT,'||chr(13)||
               'C.SUBUNITATEA,'||chr(13)||
               'E1.CODOBIECT,'||chr(13)||
               'SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,'||chr(13)||
               'SUM(E1.CANT) CANT,'||chr(13)||
               '0 ADAOSTOT'||chr(13)||
             'FROM EMULARE E'||chr(13)||
                  'INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE'||chr(13)||
                  'INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT'||chr(13)||
             'WHERE E.DATABON '||vCondData||''||chr(13)||
                   'AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0'||chr(13)||
                   'AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0'||chr(13)||
             'GROUP BY E.CODAGENT, C.SUBUNITATEA, E1.CODOBIECT'||chr(13);
           end if;
           swith := swith||
             ') S'||chr(13)||
             'GROUP BY S.Agent, S.Subunitatea, S.CodObiect';
          EXECUTE SWITH;
        end if;
      else
        if vAvize = 1 then
          sWith :=
              'INSERT INTO TMP_TOPCLI_VALCLIENT (
                CODPART,
                SUBUNITATEA,
                VALTOT,
                VALTOT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL)'||chr(13)||
              'SELECT S.CodPart,'||chr(13)||
                     'S.Subunitatea,'||chr(13)||
                     'SUM(S.ValTot) ValTot,'||chr(13)||
                     'SUM(S.ValTot_Val) ValTot_Val,'||chr(13)||
                     'SUM(S.AdaosTot) AdaosTot,'||chr(13)||
                     'SUM(S.AdaosTot_Val) AdaosTot_Val'||chr(13)||
              'FROM'||chr(13)||
              '('||chr(13)||
              'SELECT'||chr(13)||
                  'I.Partener CodPart,'||chr(13)||
                  'I.Subunitatea,'||chr(13)||
                  'SUM(case'||chr(13)||
                      'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                      '(i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                      'else'||chr(13)||
                      '(I1.RestFact * coalesce(I1.COEFDISCMAJ,1))*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                      'end) ValTot,'||chr(13)||
                  'SUM(case'||chr(13)||
                      'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                      '(i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /'||chr(13)||
                      'PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))'||chr(13)||
                      'else'||chr(13)||
                      '(I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /'||chr(13)||
                      'PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))'||chr(13)||
                      'end) ValTot_Val,'||chr(13)||
                  'sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,'||chr(13)||
                  'sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL'||chr(13)||
                'FROM IESIRI I'||chr(13)||
                     'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                     'INNER JOIN NPART P ON I.PARTENER = P.CODPART'||chr(13)||
                     'INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1'||chr(13)||
                     'INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR'||chr(13)||
                     'LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc'||chr(13)||
                     'LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1'||chr(13)||
                     'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
                'WHERE I.DATADOC '||vCondData||''||chr(13)||
                'AND I.TipDoc  NOT IN (26, 21)'||chr(13)||
                'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
                'AND coalesce(I.Initializari, 0) = 0 '||sCust||''||chr(13)||
                'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'''||chr(13)||
                'AND I.Operat = 1'||chr(13)||
                'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
                'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
                'GROUP BY I.Partener, I.Subunitatea'||chr(13)||
              'UNION ALL'||chr(13)||
              'SELECT'||chr(13)||
                  'I.Partener CodPart,'||chr(13)||
                  'I.Subunitatea,'||chr(13)||
                  'SUM(case'||chr(13)||
                      'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                      '(i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                      'else'||chr(13)||
                      '(I1.RestFact * coalesce(I1.COEFDISCMAJ,1))*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                      'end) ValTot,'||chr(13)||
                  'SUM(case'||chr(13)||
                      'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                      '(i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /'||chr(13)||
                      'PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))'||chr(13)||
                      'else'||chr(13)||
                      '(I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /'||chr(13)||
                      'PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))'||chr(13)||
                      'end) ValTot_Val,'||chr(13)||
                  'SUM(ADAOSURI.ADAOS) ADAOSTOT,'||chr(13)||
                  'SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL'||chr(13)||
                'FROM IESIRI I'||chr(13)||
                     'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                     'INNER JOIN NPART P ON I.PARTENER = P.CODPART'||chr(13)||
                     'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
                'WHERE I.DATADOC '||vCondData||''||chr(13)||
                'AND I.TipDoc  NOT IN (26, 21)'||chr(13)||
                'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
                'AND coalesce(I.Initializari, 0) = 0 '||sCust||''||chr(13)||
                'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S'''||chr(13)||
                'AND I.Operat = 1'||chr(13)||
                'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
                'GROUP BY I.Partener, I.Subunitatea'||chr(13)||
              'UNION ALL'||chr(13)||
                'SELECT'||chr(13)||
                  'I.Partener CodPart,'||chr(13)||
                  'I.Subunitatea,'||chr(13)||
                  'SUM(case'||chr(13)||
                      'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                      '((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                      'else'||chr(13)||
                      '(I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                      'end) ValTot,'||chr(13)||
                  'SUM(case'||chr(13)||
                      'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                      '((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) *'||chr(13)||
                      'PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))'||chr(13)||
                      'else'||chr(13)||
                      '(I1.RestFact - I1.TVA) *'||chr(13)||
                      'PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))'||chr(13)||
                      'end) ValTot_Val,'||chr(13)||
                  'sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,'||chr(13)||
                  'sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL'||chr(13)||
                'FROM IESIRI I'||chr(13)||
                     'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                     'INNER JOIN NPART P ON I.PARTENER = P.CODPART'||chr(13)||
                     'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
                     'INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1'||chr(13)||
                     'INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR'||chr(13)||
                     'LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc'||chr(13)||
                     'LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1'||chr(13)||
                'WHERE I.DATADOC '||vCondData||''||chr(13)||
                'AND I.TipDoc = 21'||chr(13)||
                'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
                'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
                'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'''||chr(13)||
                'AND I.Operat = 1'||chr(13)||
                'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
                'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
                'GROUP BY I.Partener, I.Subunitatea'||chr(13)||
              'UNION ALL'||chr(13)||
                'SELECT'||chr(13)||
                  'I.Partener CodPart,'||chr(13)||
                  'I.Subunitatea,'||chr(13)||
                  'SUM(case'||chr(13)||
                      'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                      '((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                      'else'||chr(13)||
                      '(I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                      'end) ValTot,'||chr(13)||
                  'SUM(case'||chr(13)||
                      'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                      '((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) *'||chr(13)||
                      'PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))'||chr(13)||
                      'else'||chr(13)||
                      '(I1.RestFact - I1.TVA) *'||chr(13)||
                      'PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))'||chr(13)||
                      'end) ValTot_Val,'||chr(13)||
                  'SUM(ADAOSURI.ADAOS) ADAOSTOT,'||chr(13)||
                  'SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL'||chr(13)||
                'FROM IESIRI I'||chr(13)||
                     'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                     'INNER JOIN NPART P ON I.PARTENER = P.CODPART'||chr(13)||
                     'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
                'WHERE I.DATADOC '||vCondData||''||chr(13)||
                'AND I.TipDoc = 21'||chr(13)||
                'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
                'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
                'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S'''||chr(13)||
                'AND I.Operat = 1'||chr(13)||
                'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
                'GROUP BY I.Partener, I.Subunitatea'||chr(13);
           if vWithEmul then
             sWith := sWith||
             'UNION ALL'||chr(13)||
             'SELECT '||chr(13)||
               'E.CODPART,'||chr(13)||
               'C.SUBUNITATEA,'||chr(13)||
               'SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,'||chr(13)||
               'SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,'||chr(13)||
               '0 ADAOSTOT,'||chr(13)||
               '0 ADAOSTOT_VAL'||chr(13)||
             'FROM EMULARE E'||chr(13)||
                  'INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE'||chr(13)||
                  'INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT'||chr(13)||
             'WHERE E.DATABON '||vCondData||''||chr(13)||
                   'AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0'||chr(13)||
                   'AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0'||chr(13)||
             'GROUP BY E.CODPART, C.SUBUNITATEA'||chr(13);
           end if;
           swith := swith||') S'||chr(13)||
               'GROUP BY S.CodPart, S.Subunitatea';
           EXECUTE SWITH;

           SWITH := 'INSERT INTO TMP_TOPCLI_ValAgent '||chr(13)||
              '(
                AGENT,
                SUBUNITATEA,
                VALTOTAGENT,
                VALTOTAGENT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL
                )'||chr(13)||
              'SELECT S.Agent,'||chr(13)||
                     'S.Subunitatea,'||chr(13)||
                     'SUM(S.ValTot) ValTotAgent,'||chr(13)||
                     'SUM(S.ValTot_Val) ValTotAgent_Val,'||chr(13)||
                     'SUM(S.AdaosTot) AdaosTot,'||chr(13)||
                     'SUM(S.AdaosTot_Val) AdaosTot_Val'||chr(13)||
              'FROM'||chr(13)||
              '('||chr(13)||
              'SELECT'||chr(13)||
                  'I.Agent,'||chr(13)||
                  'I.Subunitatea,'||chr(13)||
                  'SUM(case'||chr(13)||
                      'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                      '(i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                      'else'||chr(13)||
                      '(I1.RestFact * coalesce(I1.COEFDISCMAJ,1))*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                      'end) ValTot,'||chr(13)||
                  'SUM(case'||chr(13)||
                      'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                      '(i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /'||chr(13)||
                      'PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))'||chr(13)||
                      'else'||chr(13)||
                      '(I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /'||chr(13)||
                      'PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))'||chr(13)||
                      'end) ValTot_Val,'||chr(13)||
                  'sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,'||chr(13)||
                  'sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL'||chr(13)||
                'FROM IESIRI I'||chr(13)||
                     'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                     'INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1'||chr(13)||
                     'INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR'||chr(13)||
                     'LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc'||chr(13)||
                     'LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1'||chr(13)||
                     'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
                'WHERE I.DATADOC '||vCondData||''||chr(13)||
                'AND I.TipDoc  NOT IN (26, 21)'||chr(13)||
                'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
                'AND coalesce(I.Initializari, 0) = 0 '||sCust||''||chr(13)||
                'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'''||chr(13)||
                'AND I.Operat = 1'||chr(13)||
                'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
                'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
                'GROUP BY I.Agent, I.Subunitatea'||chr(13)||
              'UNION ALL'||chr(13)||
              'SELECT'||chr(13)||
                  'I.Agent,'||chr(13)||
                  'I.Subunitatea,'||chr(13)||
                  'SUM(case'||chr(13)||
                      'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                      '(i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                      'else'||chr(13)||
                      '(I1.RestFact * coalesce(I1.COEFDISCMAJ,1))*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                      'end) ValTot,'||chr(13)||
                  'SUM(case'||chr(13)||
                      'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                      '(i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /'||chr(13)||
                      'PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))'||chr(13)||
                      'else'||chr(13)||
                      '(I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /'||chr(13)||
                      'PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))'||chr(13)||
                      'end) ValTot_Val,'||chr(13)||
                  'SUM(ADAOSURI.ADAOS) ADAOSTOT,'||chr(13)||
                  'SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL'||chr(13)||
                'FROM IESIRI I'||chr(13)||
                     'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                     'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
                'WHERE I.DATADOC '||vCondData||''||chr(13)||
                'AND I.TipDoc  NOT IN (26, 21)'||chr(13)||
                'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
                'AND coalesce(I.Initializari, 0) = 0 '||sCust||''||chr(13)||
                'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S'''||chr(13)||
                'AND I.Operat = 1'||chr(13)||
                'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
                'GROUP BY I.Agent, I.Subunitatea'||chr(13)||
              'UNION ALL  '||chr(13)||
              'SELECT'||chr(13)||
                  'I.Agent,'||chr(13)||
                  'I.Subunitatea,'||chr(13)||
                  'SUM(case'||chr(13)||
                      'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                      '((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                      'else'||chr(13)||
                      '(I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                      'end) ValTot,'||chr(13)||
                  'SUM(case'||chr(13)||
                      'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                      '((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) *'||chr(13)||
                      'PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))'||chr(13)||
                      'else'||chr(13)||
                      '(I1.RestFact - I1.TVA) *'||chr(13)||
                      'PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))'||chr(13)||
                      'end) ValTot_Val,'||chr(13)||
                  'sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,'||chr(13)||
                  'sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL'||chr(13)||
                'FROM IESIRI I'||chr(13)||
                     'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                     'INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1'||chr(13)||
                     'INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR'||chr(13)||
                     'LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc'||chr(13)||
                     'LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1'||chr(13)||
                     'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
                'WHERE I.DATADOC '||vCondData||''||chr(13)||
                'AND I.TipDoc = 21'||chr(13)||
                'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
                'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
                'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'''||chr(13)||
                'AND I.Operat = 1'||chr(13)||
                'AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1) '||chr(13)||
                'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
                'GROUP BY I.Agent, I.Subunitatea'||chr(13)||
              'UNION ALL  '||chr(13)||
              'SELECT'||chr(13)||
                  'I.Agent,'||chr(13)||
                  'I.Subunitatea,'||chr(13)||
                  'SUM(case'||chr(13)||
                      'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                      '((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                      'else'||chr(13)||
                      '(I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)'||chr(13)||
                      'end) ValTot,'||chr(13)||
                  'SUM(case'||chr(13)||
                      'when I1.TipLinie &lt;&gt; ''G'' then'||chr(13)||
                      '((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) *'||chr(13)||
                      'PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))'||chr(13)||
                      'else'||chr(13)||
                      '(I1.RestFact - I1.TVA) *'||chr(13)||
                      'PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))'||chr(13)||
                      'end) ValTot_Val,'||chr(13)||
                  'SUM(ADAOSURI.ADAOS) ADAOSTOT,'||chr(13)||
                  'SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL'||chr(13)||
                'FROM IESIRI I'||chr(13)||
                     'INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES'||chr(13)||
                     'LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1'||chr(13)||
                'WHERE I.DATADOC '||vCondData||''||chr(13)||
                'AND I.TipDoc = 21'||chr(13)||
                'AND coalesce(I.Anulat, 0) = 0'||chr(13)||
                'AND coalesce(I.Initializari, 0) = 0'||chr(13)||
                'AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S'''||chr(13)||
                'AND I.Operat = 1'||chr(13)||
                'AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0'||chr(13)||
                'GROUP BY I.Agent, I.Subunitatea'||chr(13);
           if vWithEmul then
             sWith := sWith||
             'UNION ALL'||chr(13)||
             'SELECT '||chr(13)||
               'E.CODAGENT AGENT,'||chr(13)||
               'C.SUBUNITATEA,'||chr(13)||
               'SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,'||chr(13)||
               'SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,'||chr(13)||
               '0 ADAOSTOT,'||chr(13)||
               '0 ADAOSTOT_VAL'||chr(13)||
             'FROM EMULARE E'||chr(13)||
                  'INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE'||chr(13)||
                  'INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT'||chr(13)||
             'WHERE E.DATABON '||vCondData||''||chr(13)||
                   'AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0'||chr(13)||
                   'AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0'||chr(13)||
             'GROUP BY E.CODAGENT, C.SUBUNITATEA'||chr(13);
           end if;
           swith := swith||'
               ) S
               GROUP BY S.Agent, S.Subunitatea';
           EXECUTE SWITH;

           SWITH :=
              'INSERT INTO TMP_TOPCLI_ValAgentArt (
                 AGENT,
                 SUBUNITATEA,
                 CODOBIECT,
                 VALTOTAGENT,
                 VALTOTAGENT_VAL,
                 CANT,
                 ADAOSTOT,
                 ADAOSTOT_VAL
               )
              SELECT S.Agent,
                     S.Subunitatea,
                     S.CodObiect,
                     SUM(S.ValTot) ValTotAgent,
                     SUM(S.ValTot_Val) ValTotAgent_Val,
                     SUM(S.Cant) Cant,
                     SUM(S.AdaosTot) AdaosTot,
                     SUM(S.AdaosTot_Val) AdaosTot_Val
              FROM
              (
              SELECT
                  I.Agent,
                  I.Subunitatea,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact * coalesce(I1.COEFDISCMAJ,1))*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) Cant,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc  NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.Subunitatea, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I.Subunitatea,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact * coalesce(I1.COEFDISCMAJ,1))*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) Cant,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc  NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.Subunitatea, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I.Subunitatea,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) Cant,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.Subunitatea, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I.Subunitatea,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) Cant,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.Subunitatea, I1.CodObiect';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               C.SUBUNITATEA,
               E1.CODOBIECT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,
               SUM(E1.CANT) CANT,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, C.SUBUNITATEA,E1.CODOBIECT
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.Agent, S.Subunitatea, S.CodObiect';
           EXECUTE SWITH;
        else
          sWith :=
              'INSERT INTO TMP_TOPCLI_VALCLIENT (
                CODPART,
                SUBUNITATEA,
                VALTOT,
                VALTOT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL)
              SELECT
                  I.Partener CodPart,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Partener, I.Subunitatea
              UNION ALL
              SELECT
                  I.Partener CodPart,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Partener, I.Subunitatea
              UNION ALL
              SELECT
                  I.Partener CodPart,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact * coalesce(I1.COEFDISCMAJ,1) - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Partener, I.Subunitatea
              UNION ALL
              SELECT
                  I.Partener CodPart,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact * coalesce(I1.COEFDISCMAJ,1) - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Partener, I.Subunitatea';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODPART,
               C.SUBUNITATEA,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODPART, C.SUBUNITATEA
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.CodPart, S.Subunitatea';
           EXECUTE SWITH;

           SWITH := 'INSERT INTO TMP_TOPCLI_ValAgent '||chr(13)||
              '(
                AGENT,
                SUBUNITATEA,
                VALTOTAGENT,
                VALTOTAGENT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL
                )
              SELECT S.Agent,
                     S.Subunitatea,
                     SUM(S.ValTot) ValTotAgent,
                     SUM(S.ValTot_Val) ValTotAgent_Val,
                     SUM(S.AdaosTot) AdaosTot,
                     SUM(S.AdaosTot_Val) AdaosTot_Val
              FROM
              (
              SELECT
                  I.Agent,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.Subunitatea
              UNION ALL
              SELECT
                  I.Agent,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                     LEFT  JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     LEFT  JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.Subunitatea
              UNION ALL
              SELECT
                  I.Agent,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact * coalesce(I1.COEFDISCMAJ,1) - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.Subunitatea
              UNION ALL
              SELECT
                  I.Agent,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact * coalesce(I1.COEFDISCMAJ,1) - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                     LEFT  JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     LEFT  JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.Subunitatea';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               C.SUBUNITATEA,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, C.SUBUNITATEA
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.Agent, S.Subunitatea';
           EXECUTE SWITH;

           SWITH :=
              'INSERT INTO TMP_TOPCLI_ValAgentArt (
                 AGENT,
                 SUBUNITATEA,
                 CODOBIECT,
                 VALTOTAGENT,
                 VALTOTAGENT_VAL,
                 CANT,
                 ADAOSTOT,
                 ADAOSTOT_VAL
               )
              SELECT S.Agent,
                     S.Subunitatea,
                     S.CodObiect,
                     SUM(S.ValTot) ValTotAgent,
                     SUM(S.ValTot_Val) ValTotAgent_Val,
                     SUM(S.Cant) Cant,
                     SUM(S.AdaosTot) AdaosTot,
                     SUM(S.AdaosTot_Val) AdaosTot_Val
              FROM
              (
              SELECT
                  I.Agent,
                  I.Subunitatea,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) Cant,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.Subunitatea, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I.Subunitatea,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) Cant,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.Subunitatea, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I.Subunitatea,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact * coalesce(I1.COEFDISCMAJ,1) - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) Cant,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.Subunitatea, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I.Subunitatea,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact * coalesce(I1.COEFDISCMAJ,1) - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) Cant,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.Subunitatea, I1.CodObiect';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               C.SUBUNITATEA,
               E1.CODOBIECT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,
               SUM(E1.CANT) CANT,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, C.SUBUNITATEA,E1.CODOBIECT
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.Agent, S.Subunitatea, S.CodObiect';
           EXECUTE SWITH;
        end if;
      end if;
    else
      if vOrder in (1,3) then
        if vAvize = 1 then
          sWith :=
              'INSERT INTO TMP_TOPCLI_VALCLIENT (
                CODPART,
                CODLOCATIE,
                SUBUNITATEA,
                VALTOT,
                VALTOT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL)
                SELECT S.CodPart,
                       S.CODLOCATIE,
                       S.Subunitatea,
                       SUM(S.ValTot) ValTot,
                       0 ValTot_Val,
                       SUM(S.AdaosTot) AdaosTot,
                       0 AdaosTot_Val
                FROM
                (
                  SELECT
                    I.Partener CodPart,
                    I.CodLocatie,
                    I.Subunitatea,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                        (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                        (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN NPART P ON I.PARTENER = P.CODPART
                       INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                       INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                       LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                       LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||'
                  AND I.TipDoc  NOT IN (21, 26)
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                  AND I.Operat = 1
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                  AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Partener, I.CodLocatie, I.Subunitatea
                  UNION ALL
                  SELECT
                    I.Partener CodPart,
                    I.CodLocatie,
                    I.Subunitatea,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                        (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                        (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM(ADAOSURI.ADAOS) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN NPART P ON I.PARTENER = P.CODPART
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||'
                  AND I.TipDoc  NOT IN (21, 26)
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                  AND I.Operat = 1
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Partener, I.CodLocatie, I.Subunitatea
                UNION ALL
                SELECT
                    I.Partener CodPart,
                    I.CodLocatie,
                    I.Subunitatea,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                       ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                       (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN NPART P ON I.PARTENER = P.CODPART
                       INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                       INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                       LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                       LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||'
                  AND I.TipDoc = 21
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                  AND I.Operat = 1
                  AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Partener, I.CodLocatie, I.Subunitatea
                UNION ALL
                SELECT
                    I.Partener CodPart,
                    I.CodLocatie,
                    I.Subunitatea,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                       ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                       (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM(ADAOSURI.ADAOS) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN NPART P ON I.PARTENER = P.CODPART
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||'
                  AND I.TipDoc = 21
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                  AND I.Operat = 1
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Partener, I.CodLocatie, I.Subunitatea';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODPART,
               E.CODLOCATIE,
               C.SUBUNITATEA,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               0 ADAOSTOT,
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODPART, C.SUBUNITATEA, E.CODLOCATIE
             ';
           end if;
           swith := swith||'
                 ) S
                 GROUP BY S.CodPart, S.CodLocatie, S.Subunitatea';
           EXECUTE SWITH;

           SWITH := 'INSERT INTO TMP_TOPCLI_ValAgent '||chr(13)||
              '(
                AGENT,
                CODLOCATIE,
                SUBUNITATEA,
                VALTOTAGENT,
                VALTOTAGENT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL
                )
                SELECT S.Agent,
                       S.CODLOCATIE,
                       S.Subunitatea,
                       SUM(S.ValTot) ValTotAgent,
                       0 ValTotAgent_Val,
                       SUM(S.AdaosTot) AdaosTot,
                       0 AdaosTot_Val
                FROM
                (
                  SELECT
                    I.Agent,
                    I.CodLocatie,
                    I.Subunitatea,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                        (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                        (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                       INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                       LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                       LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||'
                  AND I.TipDoc  NOT IN (21, 26)
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                  AND I.Operat = 1
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                  AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent, I.CodLocatie, I.Subunitatea
                  UNION ALL
                  SELECT
                    I.Agent,
                    I.CodLocatie,
                    I.Subunitatea,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                        (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                        (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM(ADAOSURI.ADAOS) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||'
                  AND I.TipDoc  NOT IN (21, 26)
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                  AND I.Operat = 1
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent, I.CodLocatie, I.Subunitatea
                  UNION ALL
                  SELECT
                    I.Agent,
                    I.CodLocatie,
                    I.Subunitatea,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                       ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                       (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN NPART P ON I.PARTENER = P.CODPART
                       INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                       INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                       LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                       LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||'
                  AND I.TipDoc = 21
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                  AND I.Operat = 1
                  AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent, I.CodLocatie, I.Subunitatea
                  UNION ALL
                  SELECT
                    I.Agent,
                    I.CodLocatie,
                    I.Subunitatea,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                       ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                       (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM(ADAOSURI.ADAOS) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN NPART P ON I.PARTENER = P.CODPART
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||'
                  AND I.TipDoc = 21
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                  AND I.Operat = 1
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent, I.CodLocatie, I.Subunitatea';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               E.CODLOCATIE,
               C.SUBUNITATEA,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               0 ADAOSTOT
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, E.CODLOCATIE, C.SUBUNITATEA
             ';
           end if;
           swith := swith||'
                 ) S
                 GROUP BY S.Agent, S.CodLocatie, S.Subunitatea';
           EXECUTE SWITH;

           SWITH :=
              'INSERT INTO TMP_TOPCLI_ValAgentArt (
                 AGENT,
                 CODLOCATIE,
                 SUBUNITATEA,
                 CODOBIECT,
                 VALTOTAGENT,
                 VALTOTAGENT_VAL,
                 CANT,
                 ADAOSTOT,
                 ADAOSTOT_VAL
               )
                SELECT S.Agent,
                       S.CODLOCATIE,
                       S.Subunitatea,
                       S.CodObiect,
                       SUM(S.ValTot) ValTotAgent,
                       0 ValTotAgent_Val,
                       SUM(S.Cant) Cant,
                       SUM(S.AdaosTot) AdaosTot,
                       0 AdaosTot_Val
                FROM
                (
                  SELECT
                    I.Agent,
                    I.CodLocatie,
                    I.Subunitatea,
                    I1.CodObiect,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                        (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                        (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) Cant,
                    sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                       INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                       LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                       LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||'
                  AND I.TipDoc  NOT IN (21, 26)
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                  AND I.Operat = 1
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                  AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent, I.CodLocatie, I.Subunitatea, I1.CodObiect
                  UNION ALL
                  SELECT
                    I.Agent,
                    I.CodLocatie,
                    I.Subunitatea,
                    I1.CodObiect,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                        (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                        (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) Cant,
                    SUM(ADAOSURI.ADAOS) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||'
                  AND I.TipDoc  NOT IN (21, 26)
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                  AND I.Operat = 1
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent, I.CodLocatie, I.Subunitatea, I1.CodObiect
                  UNION ALL
                  SELECT
                    I.Agent,
                    I.CodLocatie,
                    I.Subunitatea,
                    I1.CodObiect,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                       ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                       (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) Cant,
                    sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN NPART P ON I.PARTENER = P.CODPART
                       INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                       INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                       LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                       LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||'
                  AND I.TipDoc = 21
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                  AND I.Operat = 1
                  AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent, I.CodLocatie, I.Subunitatea, I1.CodObiect
                  UNION ALL
                  SELECT
                    I.Agent,
                    I.CodLocatie,
                    I.Subunitatea,
                    I1.CodObiect,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                       ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                       (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) Cant,
                    SUM(ADAOSURI.ADAOS) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN NPART P ON I.PARTENER = P.CODPART
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||'
                  AND I.TipDoc = 21
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                  AND I.Operat = 1
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent, I.CodLocatie, I.Subunitatea, I1.CodObiect';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               E.CODLOCATIE,
               C.SUBUNITATEA,
               E1.CODOBIECT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT) CANT,
               0 ADAOSTOT
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, E.CODLOCATIE, C.SUBUNITATEA,E1.CODOBIECT
             ';
           end if;
           swith := swith||'
                 ) S
                 GROUP BY S.Agent, S.CodLocatie, S.Subunitatea, S.CodObiect';
           EXECUTE SWITH;
        else
          sWith :=
              'INSERT INTO TMP_TOPCLI_VALCLIENT (
                CODPART,
                CODLOCATIE,
                SUBUNITATEA,
                VALTOT,
                VALTOT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL)
            SELECT S.CodPart,
                   S.CodLocatie,
                   S.Subunitatea,
                   SUM(S.ValTot) ValTot,
                   0 ValTot_Val,
                   SUM(S.AdaosTot) AdaosTot,
                   0 AdaosTot_Val
            FROM
            (
            SELECT
                I.Partener CodPart,
                I.CodLocatie,
                I.Subunitatea,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                    (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                    (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||'
              AND I.TipDoc  NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Partener, I.CodLocatie
            UNION ALL
            SELECT
                I.Partener CodPart,
                I.CodLocatie,
                I.Subunitatea,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                    (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                    (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM(ADAOSURI.ADAOS) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||'
              AND I.TipDoc  NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Partener, I.CodLocatie
            UNION ALL
            SELECT
                I.Partener CodPart,
                I.CodLocatie,
                I.Subunitatea,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                   ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END) end)) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                   (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Partener, I.CodLocatie, I.Subunitatea
            UNION ALL
            SELECT
                I.Partener CodPart,
                I.CodLocatie,
                I.Subunitatea,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                   ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 then 1 ELSE (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                   (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM(ADAOSURI.ADAOS) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Partener, I.CodLocatie, I.Subunitatea
             ) S
             GROUP BY S.CodPart, S.CodLocatie, S.Subunitatea';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODPART,
               E.CODLOCATIE,
               C.SUBUNITATEA,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               0 ADAOSTOT,
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODPART, C.SUBUNITATEA, E.CODLOCATIE
             ';
           end if;
         EXECUTE SWITH;

          SWITH := 'INSERT INTO TMP_TOPCLI_ValAgent '||chr(13)||
              '(
                AGENT,
                CODLOCATIE,
                SUBUNITATEA,
                VALTOTAGENT,
                VALTOTAGENT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL
                )
            SELECT S.Agent,
                   S.CodLocatie,
                   S.Subunitatea,
                   SUM(S.ValTot) ValTotAgent,
                   0 ValTotAgent_Val,
                   SUM(S.AdaosTot) AdaosTot,
                   0 AdaosTot_Val
            FROM
            (
            SELECT
                I.Agent,
                I.CodLocatie,
                I.Subunitatea,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                    (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                    (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||'
              AND I.TipDoc  NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie
            UNION ALL
            SELECT
                I.Agent,
                I.CodLocatie,
                I.Subunitatea,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                    (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                    (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM(ADAOSURI.ADAOS) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||'
              AND I.TipDoc  NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie
            UNION ALL
            SELECT
                I.Agent,
                I.CodLocatie,
                I.Subunitatea,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                   ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE (CASE WHEN i1.tiplinie=''S'' THEN I1.cant ELSE coalesce(L1.Cant,I1.CANT) END) END), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                   (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie, I.Subunitatea
            UNION ALL
            SELECT
                I.Agent,
                I.CodLocatie,
                I.Subunitatea,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                   ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                   (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM(ADAOSURI.ADAOS) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie, I.Subunitatea';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               E.CODLOCATIE,
               C.SUBUNITATEA,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               0 ADAOSTOT
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, E.CODLOCATIE, C.SUBUNITATEA
             ';
           end if;
           swith := swith||'
             ) S
             GROUP BY S.Agent, S.CodLocatie, S.Subunitatea';
           EXECUTE SWITH;

         SWITH :=
              'INSERT INTO TMP_TOPCLI_ValAgentArt (
                 AGENT,
                 CODLOCATIE,
                 SUBUNITATEA,
                 CODOBIECT,
                 VALTOTAGENT,
                 VALTOTAGENT_VAL,
                 CANT,
                 ADAOSTOT,
                 ADAOSTOT_VAL
               )
            SELECT S.Agent,
                   S.CodLocatie,
                   S.Subunitatea,
                   S.CodObiect,
                   SUM(S.ValTot) ValTotAgent,
                   0 ValTotAgent_Val,
                   SUM(S.Cant) Cant,
                   SUM(S.AdaosTot) AdaosTot,
                   0 AdaosTot_Val
            FROM
            (
            SELECT
                I.Agent,
                I.CodLocatie,
                I.Subunitatea,
                I1.CodObiect,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                    (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                    (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||'
              AND I.TipDoc  NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie, I1.CodObiect
            UNION ALL
            SELECT
                I.Agent,
                I.CodLocatie,
                I.Subunitatea,
                I1.CodObiect,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                    (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                    (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM(ADAOSURI.ADAOS) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||'
              AND I.TipDoc  NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie, I1.CodObiect
            UNION ALL
            SELECT
                I.Agent,
                I.CodLocatie,
                I.Subunitatea,
                I1.CodObiect,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                   ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                   (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie, I.Subunitatea, I1.CodObiect
            UNION ALL
            SELECT
                I.Agent,
                I.CodLocatie,
                I.Subunitatea,
                I1.CodObiect,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                   ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                   (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM(ADAOSURI.ADAOS) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie, I.Subunitatea, I1.CodObiect';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               E.CODLOCATIE,
               C.SUBUNITATEA,
               E1.CODOBIECT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT) CANT,
               0 ADAOSTOT
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, E.CODLOCATIE, C.SUBUNITATEA,E1.CODOBIECT
             ';
           end if;
           swith := swith||'
             ) S
             GROUP BY S.Agent, S.CodLocatie, S.Subunitatea, S.CodObiect';
          EXECUTE SWITH;
        end if;
      else
        if vAvize = 1 then
          sWith :=
              'INSERT INTO TMP_TOPCLI_VALCLIENT (
                CODPART,
                CODLOCATIE,
                SUBUNITATEA,
                VALTOT,
                VALTOT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL)
              SELECT S.CodPart,
                     S.CodLocatie,
                     S.Subunitatea,
                     SUM(S.ValTot) ValTot,
                     SUM(S.ValTot_Val) ValTot_Val,
                     SUM(S.AdaosTot) AdaosTot,
                     SUM(S.AdaosTot_Val) AdaosTot_Val
              FROM
              (
              SELECT
                  I.Partener CodPart,
                  I.CodLocatie,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc  NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Partener, I.CodLocatie, I.Subunitatea
              UNION ALL
              SELECT
                  I.Partener CodPart,
                  I.CodLocatie,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc  NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Partener, I.CodLocatie, I.Subunitatea
              UNION ALL
              SELECT
                  I.Partener CodPart,
                  I.CodLocatie,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Partener, I.CodLocatie, I.Subunitatea
              UNION ALL
              SELECT
                  I.Partener CodPart,
                  I.CodLocatie,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Partener, I.CodLocatie, I.Subunitatea';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODPART,
               E.CODLOCATIE,
               C.SUBUNITATEA,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODPART, C.SUBUNITATEA, E.CODLOCATIE
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.CodPart, S.CodLocatie, S.Subunitatea';
           EXECUTE SWITH;

           SWITH := 'INSERT INTO TMP_TOPCLI_ValAgent '||chr(13)||
              '(
                AGENT,
                CODLOCATIE,
                SUBUNITATEA,
                VALTOTAGENT,
                VALTOTAGENT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL
                )
              SELECT S.Agent,
                     S.CodLocatie,
                     S.Subunitatea,
                     SUM(S.ValTot) ValTotAgent,
                     SUM(S.ValTot_Val) ValTotAgent_Val,
                     SUM(S.AdaosTot) AdaosTot,
                     SUM(S.AdaosTot_Val) AdaosTot_Val
              FROM
              (
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc  NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.CodLocatie, I.Subunitatea
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc  NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.CodLocatie, I.Subunitatea
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.CodLocatie, I.Subunitatea
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie, I.Subunitatea';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               E.CODLOCATIE,
               C.SUBUNITATEA,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, E.CODLOCATIE, C.SUBUNITATEA
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.Agent, S.CodLocatie, S.Subunitatea';
           EXECUTE SWITH;

           SWITH :=
              'INSERT INTO TMP_TOPCLI_ValAgentArt (
                 AGENT,
                 CODLOCATIE,
                 SUBUNITATEA,
                 CODOBIECT,
                 VALTOTAGENT,
                 VALTOTAGENT_VAL,
                 CANT,
                 ADAOSTOT,
                 ADAOSTOT_VAL
               )
              SELECT S.Agent,
                     S.CodLocatie,
                     S.Subunitatea,
                     S.CodObiect,
                     SUM(S.ValTot) ValTotAgent,
                     SUM(S.ValTot_Val) ValTotAgent_Val,
                     SUM(S.Cant) Cant,
                     SUM(S.AdaosTot) AdaosTot,
                     SUM(S.AdaosTot_Val) AdaosTot_Val
              FROM
              (
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I.Subunitatea,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc  NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.CodLocatie, I.Subunitatea, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I.Subunitatea,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc  NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.CodLocatie, I.Subunitatea, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I.Subunitatea,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.CodLocatie, I.Subunitatea, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I.Subunitatea,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.CodLocatie, I.Subunitatea, I1.CodObiect';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               E.CODLOCATIE,
               C.SUBUNITATEA,
               E1.CODOBIECT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,
               SUM(E1.CANT) CANT,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, E.CODLOCATIE, C.SUBUNITATEA,E1.CODOBIECT
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.Agent, S.CodLocatie, S.Subunitatea, S.CodObiect';
           EXECUTE SWITH;
        else
          sWith :=
              'INSERT INTO TMP_TOPCLI_VALCLIENT (
                CODPART,
                CODLOCATIE,
                SUBUNITATEA,
                VALTOT,
                VALTOT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL)
              SELECT S.CodPart,
                     S.CodLocatie,
                     S.Subunitatea,
                     SUM(S.ValTot) ValTot,
                     SUM(S.ValTot_Val) ValTot_Val,
                     SUM(S.AdaosTot) AdaosTot,
                     SUM(S.AdaosTot_Val) AdaosTot_Val
              FROM
              (
              SELECT
                  I.Partener CodPart,
                  I.CodLocatie,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Partener, I.CodLocatie, I.Subunitatea
              UNION ALL
              SELECT
                  I.Partener CodPart,
                  I.CodLocatie,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Partener, I.CodLocatie, I.Subunitatea
              UNION ALL
              SELECT
                  I.Partener CodPart,
                  I.CodLocatie,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Partener, I.CodLocatie, I.Subunitatea
              UNION ALL
              SELECT
                  I.Partener CodPart,
                  I.CodLocatie,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Partener, I.CodLocatie, I.Subunitatea';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODPART,
               E.CODLOCATIE,
               C.SUBUNITATEA,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODPART, C.SUBUNITATEA, E.CODLOCATIE
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.CodPart, S.CodLocatie, S.Subunitatea';
           EXECUTE SWITH;

           SWITH := 'INSERT INTO TMP_TOPCLI_ValAgent '||chr(13)||
              '(
                AGENT,
                CODLOCATIE,
                SUBUNITATEA,
                VALTOTAGENT,
                VALTOTAGENT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL
                )
              SELECT S.Agent,
                     S.CodLocatie,
                     S.Subunitatea,
                     SUM(S.ValTot) ValTotAgent,
                     SUM(S.ValTot_Val) ValTotAgent_Val,
                     SUM(S.AdaosTot) AdaosTot,
                     SUM(S.AdaosTot_Val) AdaosTot_Val
              FROM
              (
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.CodLocatie, I.Subunitatea
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.CodLocatie, I.Subunitatea
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.CodLocatie, I.Subunitatea
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I.Subunitatea,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.CodLocatie, I.Subunitatea';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               E.CODPART,
               C.SUBUNITATEA,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, E.CODLOCATIE, C.SUBUNITATEA
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.Agent, S.CodLocatie, S.Subunitatea';
           EXECUTE SWITH;

           SWITH :=
              'INSERT INTO TMP_TOPCLI_ValAgentArt (
                 AGENT,
                 CODLOCATIE,
                 SUBUNITATEA,
                 CODOBIECT,
                 VALTOTAGENT,
                 VALTOTAGENT_VAL,
                 CANT,
                 ADAOSTOT,
                 ADAOSTOT_VAL
               )
              SELECT S.Agent,
                     S.CodLocatie,
                     S.Subunitatea,
                     S.CodObiect,
                     SUM(S.ValTot) ValTotAgent,
                     SUM(S.ValTot_Val) ValTotAgent_Val,
                     SUM(S.Cant) Cant,
                     SUM(S.AdaosTot) AdaosTot,
                     SUM(S.AdaosTot_Val) AdaosTot_Val
              FROM
              (
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I.Subunitatea,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.CodLocatie, I.Subunitatea, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I.Subunitatea,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.CodLocatie, I.Subunitatea, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I.Subunitatea,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie, I.Subunitatea, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I.Subunitatea,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.CodLocatie, I.Subunitatea, I1.CodObiect';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               E.CODLOCATIE,
               C.SUBUNITATEA,
               E1.CODOBIECT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,
               SUM(E1.CANT) CANT,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, E.CODLOCATIE, C.SUBUNITATEA,E1.CODOBIECT
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.Agent, S.CodLocatie, S.Subunitatea, S.CodObiect';
           EXECUTE SWITH;
        end if;
      end if;
    end if;
  else
    if vSediiL = 0 then
      if vOrder in (1,3) then
        if vAvize = 1 then
          sWith :=
              'INSERT INTO TMP_TOPCLI_VALCLIENT (
                CODPART,
                VALTOT,
                VALTOT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL)
                SELECT S.CodPart,
                       SUM(S.ValTot) ValTot,
                       0 ValTot_Val,
                       SUM(S.AdaosTot) AdaosTot,
                       0 AdaosTot_Val
                FROM
                (
                SELECT
                    I.Partener CodPart,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                        (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                        (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN NPART P ON I.PARTENER = P.CODPART
                       INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                       INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                       LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                       LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL) ||'
                  AND I.TipDoc  NOT IN (21, 26)
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                  AND I.Operat = 1
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                  AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Partener
                UNION ALL
                SELECT
                    I.Partener CodPart,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                        (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                        (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM(ADAOSURI.ADAOS) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN NPART P ON I.PARTENER = P.CODPART
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL) ||'
                  AND I.TipDoc  NOT IN (21, 26)
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                  AND I.Operat = 1
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Partener
                UNION ALL
                SELECT
                    I.Partener CodPart,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                       ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                       (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN NPART P ON I.PARTENER = P.CODPART
                       INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                       INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                       LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                       LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL) ||'
                  AND I.TipDoc = 21
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                  AND I.Operat = 1
                  AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Partener
                UNION ALL
                SELECT
                    I.Partener CodPart,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                       ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                       (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM(ADAOSURI.ADAOS) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN NPART P ON I.PARTENER = P.CODPART
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL) ||'
                  AND I.TipDoc = 21
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                  AND I.Operat = 1
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Partener';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODPART,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               0 ADAOSTOT
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODPART
             ';
           end if;
           swith := swith||'
                 ) S
                 GROUP BY S.CodPart';
           EXECUTE SWITH;

           SWITH := 'INSERT INTO TMP_TOPCLI_ValAgent '||chr(13)||
              '(
                AGENT,
                VALTOTAGENT,
                VALTOTAGENT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL
                )
                SELECT S.Agent,
                       SUM(S.ValTot) ValTotAgent,
                       0 ValTotAgent_Val,
                       SUM(S.AdaosTot) AdaosTot,
                       0 AdaosTot_Val
                FROM
                (
                SELECT
                    I.Agent,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                        (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                        (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                       INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                       LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                       LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                  AND I.TipDoc  NOT IN (21, 26)
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                  AND I.Operat = 1
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                  AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent
                UNION ALL
                SELECT
                    I.Agent,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                        (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                        (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM(ADAOSURI.ADAOS) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                  AND I.TipDoc  NOT IN (21, 26)
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                  AND I.Operat = 1
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent
                UNION ALL
                SELECT
                    I.Agent,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                       ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                       (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                       INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                       LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                       LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                  AND I.TipDoc = 21
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                  AND I.Operat = 1
                  AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent
                UNION ALL
                SELECT
                    I.Agent,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                       ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                       (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM(ADAOSURI.ADAOS) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                  AND I.TipDoc = 21
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                  AND I.Operat = 1
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               0 ADAOSTOT
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT
             ';
           end if;
           swith := swith||'
                 ) S
                 GROUP BY S.Agent';
           EXECUTE SWITH;

           SWITH :=
              'INSERT INTO TMP_TOPCLI_ValAgentArt (
                 AGENT,
                 CODOBIECT,
                 VALTOTAGENT,
                 VALTOTAGENT_VAL,
                 CANT,
                 ADAOSTOT,
                 ADAOSTOT_VAL
               )
                SELECT S.Agent,
                       S.CodObiect,
                       SUM(S.ValTot) ValTotAgent,
                       0 ValTotAgent_Val,
                       SUM(S.Cant) Cant,
                       SUM(S.AdaosTot) AdaosTot,
                       0 AdaosTot_Val
                FROM
                (
                SELECT
                    I.Agent,
                    I1.CodObiect,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                        (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                        (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                    sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                       INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                       LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                       LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                  AND I.TipDoc  NOT IN (21, 26)
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                  AND I.Operat = 1
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                  AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent, I1.CodObiect
                UNION ALL
                SELECT
                    I.Agent,
                    I1.CodObiect,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                        (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                        (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                    SUM(ADAOSURI.ADAOS) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                  AND I.TipDoc  NOT IN (21, 26)
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                  AND I.Operat = 1
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent, I1.CodObiect
                UNION ALL
                SELECT
                    I.Agent,
                    I1.CodObiect,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                       ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                       (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                    sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                       INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                       LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                       LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                  AND I.TipDoc = 21
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                  AND I.Operat = 1
                  AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent, I1.CodObiect
                UNION ALL
                SELECT
                    I.Agent,
                    I1.CodObiect,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                       ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                       (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                    SUM(ADAOSURI.ADAOS) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                  AND I.TipDoc = 21
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                  AND I.Operat = 1
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent, I1.CodObiect  ';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               E1.CODOBIECT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT) CANT,
               0 ADAOSTOT
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, E1.CODOBIECT
             ';
           end if;
           swith := swith||'
                 ) S
                 GROUP BY S.Agent, S.CodObiect';
           EXECUTE SWITH;
        else
          sWith :=
              'INSERT INTO TMP_TOPCLI_VALCLIENT (
                CODPART,
                VALTOT,
                VALTOT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL)
            SELECT S.CodPart,
                   SUM(S.ValTot) ValTot,
                   0 ValTot_Val,
                   SUM(S.AdaosTot) AdaosTot,
                   0 AdaosTot_Val
            FROM
            (
            SELECT
                I.Partener CodPart,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                    (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                    (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc  NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Partener
            UNION ALL
            SELECT
                I.Partener CodPart,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                    (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                    (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM(ADAOSURI.ADAOS) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc  NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Partener
            UNION ALL
            SELECT
                I.Partener CodPart,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                   ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                   (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
            GROUP BY I.Partener
            UNION ALL
            SELECT
                I.Partener CodPart,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                   ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                   (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM(ADAOSURI.ADAOS) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
            GROUP BY I.Partener';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODPART,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               0 ADAOSTOT
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODPART';
           end if;
           swith := swith||'
             ) S
             GROUP BY S.CodPart';
          EXECUTE SWITH;

         SWITH := 'INSERT INTO TMP_TOPCLI_ValAgent '||chr(13)||
              '(
                AGENT,
                VALTOTAGENT,
                VALTOTAGENT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL
                )
            SELECT S.Agent,
                   SUM(S.ValTot) ValTotAgent,
                   0 ValTotAgent_Val,
                   SUM(S.AdaosTot) AdaosTot,
                   0 AdaosTot_Val
            FROM
            (
            SELECT
                I.Agent,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                    (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                    (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc  NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
            GROUP BY I.Agent
            UNION ALL
            SELECT
                I.Agent,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                    (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                    (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM(ADAOSURI.ADAOS) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc  NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
            GROUP BY I.Agent
            UNION ALL
            SELECT
                I.Agent,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                   ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                   (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent
            UNION ALL
            SELECT
                I.Agent,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                   ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                   (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM(ADAOSURI.ADAOS) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               0 ADAOSTOT
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT
             ';
           end if;
           swith := swith||'
             ) S
             GROUP BY S.Agent';
           EXECUTE SWITH;

          SWITH :=
              'INSERT INTO TMP_TOPCLI_ValAgentArt (
                 AGENT,
                 CODOBIECT,
                 VALTOTAGENT,
                 VALTOTAGENT_VAL,
                 CANT,
                 ADAOSTOT,
                 ADAOSTOT_VAL
               )
            SELECT S.Agent,
                   S.CodObiect,
                   SUM(S.ValTot) ValTotAgent,
                   0 ValTotAgent_Val,
                   SUM(S.Cant) Cant,
                   SUM(S.AdaosTot) AdaosTot,
                   0 AdaosTot_Val
            FROM
            (
            SELECT
                I.Agent,
                I1.CodObiect,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                    (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                    (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc  NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I1.CodObiect
            UNION ALL
            SELECT
                I.Agent,
                I1.CodObiect,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                    (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                    (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM(ADAOSURI.ADAOS) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc  NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I1.CodObiect
            UNION ALL
            SELECT
                I.Agent,
                I1.CodObiect,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                   ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                   (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
            GROUP BY I.Agent, I1.CodObiect
            UNION ALL
            SELECT
                I.Agent,
                I1.CodObiect,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                   ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                   (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM(ADAOSURI.ADAOS) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                   LEFT  JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   LEFT  JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
            GROUP BY I.Agent, I1.CodObiect';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               E1.CODOBIECT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT) CANT,
               0 ADAOSTOT
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, E.CODPART, E.CODLOCATIE, C.SUBUNITATEA,E1.CODOBIECT
             ';
           end if;
           swith := swith||'
             ) S
             GROUP BY S.Agent, S.CodObiect';
          EXECUTE SWITH;
        end if;
      else
        if vAvize = 1 then
          sWith :=
              'INSERT INTO TMP_TOPCLI_VALCLIENT (
                CODPART,
                VALTOT,
                VALTOT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL)
              SELECT S.CodPart,
                     SUM(S.ValTot) ValTot,
                     SUM(S.ValTot_Val) ValTot_Val,
                     SUM(S.AdaosTot) AdaosTot,
                     SUM(S.AdaosTot_Val) AdaosTot_Val
              FROM
              (
              SELECT
                  I.Partener CodPart,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact * coalesce(I1.COEFDISCMAJ,1))*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Partener
              UNION ALL
              SELECT
                  I.Partener CodPart,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact * coalesce(I1.COEFDISCMAJ,1))*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Partener
              UNION ALL
                SELECT
                  I.Partener CodPart,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Partener
              UNION ALL
                SELECT
                  I.Partener CodPart,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Partener';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODPART,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.PRET * E1.PRET) VALTOT_VAL,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODPART
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.CodPart';
          EXECUTE SWITH;

          SWITH := 'INSERT INTO TMP_TOPCLI_ValAgent '||chr(13)||
              '(
                AGENT,
                VALTOTAGENT,
                VALTOTAGENT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL
                )
              SELECT S.Agent,
                     SUM(S.ValTot) ValTotAgent,
                     SUM(S.ValTot_Val) ValTotAgent_Val,
                     SUM(S.AdaosTot) AdaosTot,
                     SUM(S.AdaosTot_Val) AdaosTot_Val
              FROM
              (
              SELECT
                  I.Agent,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact * coalesce(I1.COEFDISCMAJ,1))*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent
              UNION ALL
              SELECT
                  I.Agent,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact * coalesce(I1.COEFDISCMAJ,1))*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent
              UNION ALL
              SELECT
                  I.Agent,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent
              UNION ALL
              SELECT
                  I.Agent,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.Agent';
           EXECUTE SWITH;

           SWITH :=
              'INSERT INTO TMP_TOPCLI_ValAgentArt (
                 AGENT,
                 CODOBIECT,
                 VALTOTAGENT,
                 VALTOTAGENT_VAL,
                 CANT,
                 ADAOSTOT,
                 ADAOSTOT_VAL
               )
              SELECT S.Agent,
                     S.CodObiect,
                     SUM(S.ValTot) ValTotAgent,
                     SUM(S.ValTot_Val) ValTotAgent_Val,
                     SUM(S.Cant) Cant,
                     SUM(S.AdaosTot) AdaosTot,
                     SUM(S.AdaosTot_Val) AdaosTot_Val
              FROM
              (
              SELECT
                  I.Agent,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact * coalesce(I1.COEFDISCMAJ,1))*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact * coalesce(I1.COEFDISCMAJ,1))*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I1.CodObiect';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               E1.CODOBIECT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,
               SUM(E1.CANT) CANT,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, E1.CODOBIECT
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.Agent, S.CodObiect';
           EXECUTE SWITH;
        else
          sWith :=
              'INSERT INTO TMP_TOPCLI_VALCLIENT (
                CODPART,
                VALTOT,
                VALTOT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL)
              SELECT S.CodPart,
                     SUM(S.ValTot) ValTot,
                     SUM(S.ValTot_Val) ValTot_Val,
                     SUM(S.AdaosTot) AdaosTot,
                     SUM(S.AdaosTot_Val) AdaosTot_Val
              FROM
              (
              SELECT
                  I.Partener CodPart,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Partener
              UNION ALL
              SELECT
                  I.Partener CodPart,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Partener
              UNION ALL
              SELECT
                  I.Partener CodPart,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact * coalesce(I1.COEFDISCMAJ,1) - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Partener
              UNION ALL
              SELECT
                  I.Partener CodPart,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact * coalesce(I1.COEFDISCMAJ,1) - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Partener';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODPART,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODPART
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.CodPart';
           EXECUTE SWITH;

           SWITH := 'INSERT INTO TMP_TOPCLI_ValAgent '||chr(13)||
              '(
                AGENT,
                VALTOTAGENT,
                VALTOTAGENT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL
                )
              SELECT S.Agent,
                     SUM(S.ValTot) ValTotAgent,
                     SUM(S.ValTot_Val) ValTotAgent_Val,
                     SUM(S.AdaosTot) AdaosTot,
                     SUM(S.AdaosTot_Val) AdaosTot_Val
              FROM
              (
              SELECT
                  I.Agent,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent
              UNION ALL
              SELECT
                  I.Agent,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent
              UNION ALL
              SELECT
                  I.Agent,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact * coalesce(I1.COEFDISCMAJ,1) - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent
              UNION ALL
              SELECT
                  I.Agent,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact * coalesce(I1.COEFDISCMAJ,1) - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.Agent';
           EXECUTE SWITH;

           SWITH :=
              'INSERT INTO TMP_TOPCLI_ValAgentArt (
                 AGENT,
                 CODOBIECT,
                 VALTOTAGENT,
                 VALTOTAGENT_VAL,
                 CANT,
                 ADAOSTOT,
                 ADAOSTOT_VAL
               )
              SELECT S.Agent,
                     S.CodObiect,
                     SUM(S.ValTot) ValTotAgent,
                     SUM(S.ValTot_Val) ValTotAgent_Val,
                     SUM(S.Cant) Cant,
                     SUM(S.AdaosTot) AdaosTot,
                     SUM(S.AdaosTot_Val) AdaosTot_Val
              FROM
              (
              SELECT
                  I.Agent,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact * coalesce(I1.COEFDISCMAJ,1) - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact * coalesce(I1.COEFDISCMAJ,1) - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I1.CodObiect';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               E1.CODOBIECT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,
               SUM(E1.CANT) CANT,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, E1.CODOBIECT
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.Agent, S.CodObiect';
           EXECUTE SWITH;
        end if;
      end if;
    else
      if vOrder in (1,3) then
        if vAvize = 1 then
          sWith :=
              'INSERT INTO TMP_TOPCLI_VALCLIENT (
                CODPART,
                CODLOCATIE,
                VALTOT,
                VALTOT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL)
                SELECT S.CodPart,
                       S.CODLOCATIE,
                       SUM(S.ValTot) ValTot,
                       0 ValTot_Val,
                       SUM(S.AdaosTot) AdaosTot,
                       0 AdaosTot_Val
                FROM
                (
                  SELECT
                    I.Partener CodPart,
                    I.CodLocatie,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                        (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                        (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN NPART P ON I.PARTENER = P.CODPART
                       INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                       INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                       LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                       LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                  AND I.TipDoc  NOT IN (21, 26)
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                  AND I.Operat = 1
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                  AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Partener, I.CodLocatie
                  UNION ALL
                  SELECT
                    I.Partener CodPart,
                    I.CodLocatie,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                        (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                        (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM(ADAOSURI.ADAOS) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN NPART P ON I.PARTENER = P.CODPART
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                  AND I.TipDoc  NOT IN (21, 26)
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                  AND I.Operat = 1
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Partener, I.CodLocatie
                  UNION ALL
                  SELECT
                    I.Partener CodPart,
                    I.CodLocatie,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                       ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                       (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN NPART P ON I.PARTENER = P.CODPART
                       INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                       INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                       LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                       LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                  AND I.TipDoc = 21
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                  AND I.Operat = 1
                  AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Partener, I.CodLocatie
                  UNION ALL
                  SELECT
                    I.Partener CodPart,
                    I.CodLocatie,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                       ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                       (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM(ADAOSURI.ADAOS) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN NPART P ON I.PARTENER = P.CODPART
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                  AND I.TipDoc = 21
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                  AND I.Operat = 1
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Partener, I.CodLocatie';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODPART,
               E.CODLOCATIE,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               0 ADAOSTOT
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODPART, E.CODLOCATIE
             ';
           end if;
           swith := swith||'
                 ) S
                 GROUP BY S.CodPart, S.CodLocatie';
           EXECUTE SWITH;

           SWITH := 'INSERT INTO TMP_TOPCLI_ValAgent '||chr(13)||
              '(
                AGENT,
                CODLOCATIE,
                VALTOTAGENT,
                VALTOTAGENT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL
                )
                SELECT S.Agent,
                       S.CODLOCATIE,
                       SUM(S.ValTot) ValTotAgent,
                       0 ValTotAgent_Val,
                       SUM(S.AdaosTot) AdaosTot,
                       0 AdaosTot_Val
                FROM
                (
                  SELECT
                    I.Agent,
                    I.CodLocatie,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                        (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                        (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                       INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                       LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                       LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                  AND I.TipDoc  NOT IN (21, 26)
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                  AND I.Operat = 1
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                  AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent, I.CodLocatie
                  UNION ALL
                  SELECT
                    I.Agent,
                    I.CodLocatie,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                        (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                        (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM(ADAOSURI.ADAOS) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                  AND I.TipDoc  NOT IN (21, 26)
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                  AND I.Operat = 1
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent, I.CodLocatie
                  UNION ALL
                  SELECT
                    I.Agent,
                    I.CodLocatie,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                       ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                       (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                       INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                       LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                       LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                  AND I.TipDoc = 21
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                  AND I.Operat = 1
                  AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent, I.CodLocatie
                  UNION ALL
                  SELECT
                    I.Agent,
                    I.CodLocatie,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                       ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                       (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM(ADAOSURI.ADAOS) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                  AND I.TipDoc = 21
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                  AND I.Operat = 1
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent, I.CodLocatie';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               E.CODLOCATIE,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               0 ADAOSTOT
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, E.CODLOCATIE
             ';
           end if;
           swith := swith||'
                 ) S
                 GROUP BY S.Agent, S.CodLocatie';
           EXECUTE SWITH;

           SWITH :=
              'INSERT INTO TMP_TOPCLI_ValAgentArt (
                 AGENT,
                 CODLOCATIE,
                 CODOBIECT,
                 VALTOTAGENT,
                 VALTOTAGENT_VAL,
                 CANT,
                 ADAOSTOT,
                 ADAOSTOT_VAL
               )
                SELECT S.Agent,
                       S.CODLOCATIE,
                       S.CodObiect,
                       SUM(S.ValTot) ValTotAgent,
                       0 ValTotAgent_Val,
                       SUM(S.Cant) Cant,
                       SUM(S.AdaosTot) AdaosTot,
                       0 AdaosTot_Val
                FROM
                (
                  SELECT
                    I.Agent,
                    I.CodLocatie,
                    I1.CodObiect,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                        (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                        (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                    sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                       INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                       LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                       LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                  AND I.TipDoc  NOT IN (21, 26)
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                  AND I.Operat = 1
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                  AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent, I.CodLocatie, I1.CodObiect
                  UNION ALL
                  SELECT
                    I.Agent,
                    I.CodLocatie,
                    I1.CodObiect,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                        (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                        (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                    SUM(ADAOSURI.ADAOS) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                  AND I.TipDoc  NOT IN (21, 26)
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                  AND I.Operat = 1
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent, I.CodLocatie, I1.CodObiect
                  UNION ALL
                  SELECT
                    I.Agent,
                    I.CodLocatie,
                    I1.CodObiect,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                       ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                       (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                    sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                       INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                       LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                       LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                  AND I.TipDoc = 21
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                  AND I.Operat = 1
                  AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent, I.CodLocatie, I1.CodObiect
                  UNION ALL
                  SELECT
                    I.Agent,
                    I.CodLocatie,
                    I1.CodObiect,
                    SUM(case
                        when I1.TipLinie &lt;&gt; ''G'' then
                       ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        else
                       (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                        end) ValTot,
                    SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                    SUM(ADAOSURI.ADAOS) ADAOSTOT
                  FROM IESIRI I
                       INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                       LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                  WHERE I.DATADOC '||vCondData||
                  PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                  AND I.TipDoc = 21
                  AND coalesce(I.Anulat, 0) = 0
                  AND coalesce(I.Initializari, 0) = 0
                  AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                  AND I.Operat = 1
                  AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                  GROUP BY I.Agent, I.CodLocatie, I1.CodObiect';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               E.CODLOCATIE,
               E1.CODOBIECT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT) CANT,
               0 ADAOSTOT
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, E.CODLOCATIE, E1.CODOBIECT
             ';
           end if;
           swith := swith||'
                 ) S
                 GROUP BY S.Agent, S.CodLocatie, S.CodObiect';
           EXECUTE SWITH;
        else
          sWith :=
              'INSERT INTO TMP_TOPCLI_VALCLIENT (
                CODPART,
                CODLOCATIE,
                VALTOT,
                VALTOT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL)
            SELECT S.CodPart,
                   S.CodLocatie,
                   SUM(S.ValTot) ValTot,
                   0 ValTot_Val,
                   SUM(S.AdaosTot) AdaosTot,
                   0 AdaosTot_Val
            FROM
            (
            SELECT
                I.Partener CodPart,
                I.CodLocatie,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                    (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                    (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc  NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
            GROUP BY I.Partener, I.CodLocatie
            UNION ALL
            SELECT
                I.Partener CodPart,
                I.CodLocatie,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                    (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                    (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM(ADAOSURI.ADAOS) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc  NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
            GROUP BY I.Partener, I.CodLocatie
            UNION ALL
            SELECT
                I.Partener CodPart,
                I.CodLocatie,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                   ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                   (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
            GROUP BY I.Partener, I.CodLocatie
            UNION ALL
            SELECT
                I.Partener CodPart,
                I.CodLocatie,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                   ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                   (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM(ADAOSURI.ADAOS) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
            GROUP BY I.Partener, I.CodLocatie';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODPART,
               E.CODLOCATIE,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               0 ADAOSTOT
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODPART, E.CODLOCATIE
             ';
           end if;
           swith := swith||'
             ) S
             GROUP BY S.CodPart, S.CodLocatie';
          EXECUTE SWITH;

          SWITH := 'INSERT INTO TMP_TOPCLI_ValAgent '||chr(13)||
              '(
                AGENT,
                CODLOCATIE,
                VALTOTAGENT,
                VALTOTAGENT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL
                )
            SELECT S.Agent,
                   S.CodLocatie,
                   SUM(S.ValTot) ValTotAgent,
                   0 ValTotAgent_Val,
                   SUM(S.AdaosTot) AdaosTot,
                   0 AdaosTot_Val
            FROM
            (
            SELECT
                I.Agent,
                I.CodLocatie,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                    (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                    (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc  NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
            GROUP BY I.Agent, I.CodLocatie
            UNION ALL
            SELECT
                I.Agent,
                I.CodLocatie,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                    (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                    (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM(ADAOSURI.ADAOS) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc  NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
            GROUP BY I.Agent, I.CodLocatie
            UNION ALL
            SELECT
                I.Agent,
                I.CodLocatie,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                   ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                   (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
            GROUP BY I.Agent, I.CodLocatie
            UNION ALL
            SELECT
                I.Agent,
                I.CodLocatie,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                   ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                   (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM(ADAOSURI.ADAOS) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               E.CODLOCATIE,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               0 ADAOSTOT
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, E.CODLOCATIE
             ';
           end if;
           swith := swith||'
             ) S
             GROUP BY S.Agent, S.CodLocatie';
          EXECUTE SWITH;

          SWITH :=
              'INSERT INTO TMP_TOPCLI_ValAgentArt (
                 AGENT,
                 CODLOCATIE,
                 CODOBIECT,
                 VALTOTAGENT,
                 VALTOTAGENT_VAL,
                 CANT,
                 ADAOSTOT,
                 ADAOSTOT_VAL
               )
            SELECT S.Agent,
                   S.CodLocatie,
                   S.CodObiect,
                   SUM(S.ValTot) ValTotAgent,
                   0 ValTotAgent_Val,
                   SUM(S.Cant) Cant,
                   SUM(S.AdaosTot) AdaosTot,
                   0 AdaosTot_Val
            FROM
            (
            SELECT
                I.Agent,
                I.CodLocatie,
                I1.CodObiect,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                    (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                    (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc  NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
            GROUP BY I.Agent, I.CodLocatie, I1.CodObiect
            UNION ALL
            SELECT
                I.Agent,
                I.CodLocatie,
                I1.CodObiect,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                    (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                    (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM(ADAOSURI.ADAOS) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc  NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I.Operat = 1
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie, I1.CodObiect
            UNION ALL
            SELECT
                I.Agent,
                I.CodLocatie,
                I1.CodObiect,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                   ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                   (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
            GROUP BY I.Agent, I.CodLocatie, I1.CodObiect
            UNION ALL
            SELECT
                I.Agent,
                I.CodLocatie,
                I1.CodObiect,
                SUM(case
                    when I1.TipLinie &lt;&gt; ''G'' then
                   ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    else
                   (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                    end) ValTot,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM(ADAOSURI.ADAOS) ADAOSTOT
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
            GROUP BY I.Agent, I.CodLocatie, I1.CodObiect';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               E.CODLOCATIE,
               E1.CODOBIECT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT) CANT,
               0 ADAOSTOT
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, E.CODLOCATIE, E1.CODOBIECT
             ';
           end if;
           swith := swith||'
             ) S
             GROUP BY S.Agent, S.CodLocatie, S.CodObiect';
          EXECUTE SWITH;
        end if;
      else
        if vAvize = 1 then
          sWith :=
              'INSERT INTO TMP_TOPCLI_VALCLIENT (
                CODPART,
                CODLOCATIE,
                VALTOT,
                VALTOT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL)
              SELECT S.CodPart,
                     S.CodLocatie,
                     SUM(S.ValTot) ValTot,
                     SUM(S.ValTot_Val) ValTot_Val,
                     SUM(S.AdaosTot) AdaosTot,
                     SUM(S.AdaosTot_Val) AdaosTot_Val
              FROM
              (
              SELECT
                  I.Partener CodPart,
                  I.CodLocatie,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Partener, I.CodLocatie
              UNION ALL
              SELECT
                  I.Partener CodPart,
                  I.CodLocatie,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Partener, I.CodLocatie
              UNION ALL
              SELECT
                  I.Partener CodPart,
                  I.CodLocatie,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Partener, I.CodLocatie
              UNION ALL
              SELECT
                  I.Partener CodPart,
                  I.CodLocatie,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Partener, I.CodLocatie';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODPART,
               E.CODLOCATIE,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODPART, E.CODLOCATIE
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.CodPart, S.CodLocatie';
           EXECUTE SWITH;

           SWITH := 'INSERT INTO TMP_TOPCLI_ValAgent '||chr(13)||
              '(
                AGENT,
                CODLOCATIE,
                VALTOTAGENT,
                VALTOTAGENT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL
                )
              SELECT S.Agent,
                     S.CodLocatie,
                     SUM(S.ValTot) ValTotAgent,
                     SUM(S.ValTot_Val) ValTotAgent_Val,
                     SUM(S.AdaosTot) AdaosTot,
                     SUM(S.AdaosTot_Val) AdaosTot_Val
              FROM
              (
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.CodLocatie
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Agent, I.CodLocatie';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               E.CODLOCATIE,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, E.CODLOCATIE
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.Agent, S.CodLocatie';
           EXECUTE SWITH;

           SWITH :=
              'INSERT INTO TMP_TOPCLI_ValAgentArt (
                 AGENT,
                 CODLOCATIE,
                 CODOBIECT,
                 VALTOTAGENT,
                 VALTOTAGENT_VAL,
                 CANT,
                 ADAOSTOT,
                 ADAOSTOT_VAL
               )
              SELECT S.Agent,
                     S.CodLocatie,
                     S.CodObiect,
                     SUM(S.ValTot) ValTotAgent,
                     SUM(S.ValTot_Val) ValTotAgent_Val,
                     SUM(S.Cant) Cant,
                     SUM(S.AdaosTot) AdaosTot,
                     SUM(S.AdaosTot_Val) AdaosTot_Val
              FROM
              (
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie, I1.CodObiect';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               E.CODLOCATIE,
               E1.CODOBIECT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,
               SUM(E1.CANT) CANT,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, E.CODLOCATIE, E1.CODOBIECT
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.Agent, S.CodLocatie, S.CodObiect';
           EXECUTE SWITH;
        else
          sWith :=
              'INSERT INTO TMP_TOPCLI_VALCLIENT (
                CODPART,
                CODLOCATIE,
                VALTOT,
                VALTOT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL)
              SELECT S.CodPart,
                     S.CodLocatie,
                     SUM(S.ValTot) ValTot,
                     SUM(S.ValTot_Val) ValTot_Val,
                     SUM(S.AdaosTot) AdaosTot,
                     SUM(S.AdaosTot_Val) AdaosTot_Val
              FROM
              (
              SELECT
                  I.Partener CodPart,
                  I.CodLocatie,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Partener, I.CodLocatie
              SELECT
                  I.Partener CodPart,
                  I.CodLocatie,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Partener, I.CodLocatie
              UNION ALL
              SELECT
                  I.Partener CodPart,
                  I.CodLocatie,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Partener, I.CodLocatie
             UNION ALL
              SELECT
                  I.Partener CodPart,
                  I.CodLocatie,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I.Partener, I.CodLocatie';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODPART,
               E.CODLOCATIE,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODPART, E.CODLOCATIE
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.CodPart, S.CodLocatie';
           EXECUTE SWITH;

           SWITH := 'INSERT INTO TMP_TOPCLI_ValAgent '||chr(13)||
              '(
                AGENT,
                CODLOCATIE,
                VALTOTAGENT,
                VALTOTAGENT_VAL,
                ADAOSTOT,
                ADAOSTOT_VAL
                )
              SELECT S.Agent,
                     S.CodLocatie,
                     SUM(S.ValTot) ValTotAgent,
                     SUM(S.ValTot_Val) ValTotAgent_Val,
                     SUM(S.AdaosTot) AdaosTot,
                     SUM(S.AdaosTot_Val) AdaosTot_Val
              FROM
              (
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               E.CODLOCATIE,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, E.CODLOCATIE
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.Agent, S.CodLocatie';
           EXECUTE SWITH;

           SWITH :=
              'INSERT INTO TMP_TOPCLI_ValAgentArt (
                 AGENT,
                 CODLOCATIE,
                 CODOBIECT,
                 VALTOTAGENT,
                 VALTOTAGENT_VAL,
                 CANT,
                 ADAOSTOT,
                 ADAOSTOT_VAL
               )
              SELECT S.Agent,
                     S.CodLocatie,
                     S.CodObiect,
                     SUM(S.ValTot) ValTotAgent,
                     SUM(S.ValTot_Val) ValTotAgent_Val,
                     SUM(S.Cant) Cant,
                     SUM(S.AdaosTot) AdaosTot,
                     SUM(S.AdaosTot_Val) AdaosTot_Val
              FROM
              (
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact)*(case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc  NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  sum(l1.cant/i1.cant*adaosuri.adaos) ADAOSTOT,
                  sum(l1.cant/i1.cant*adaosuri.adaos/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie, I1.CodObiect
              UNION ALL
              SELECT
                  I.Agent,
                  I.CodLocatie,
                  I1.CodObiect,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      else
                      (I1.RestFact - I1.TVA) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)
                      end) ValTot,
                  SUM(case
                      when I1.TipLinie &lt;&gt; ''G'' then
                      ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      else
                      (I1.RestFact - I1.TVA) *
                      PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))
                      end) ValTot_Val,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM(ADAOSURI.ADAOS) ADAOSTOT,
                  SUM(ADAOSURI.ADAOS/PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) ADAOSTOT_VAL
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES = I.CODIES
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON ADAOSURI.CODIES1 = I1.CODIES1
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I.Agent, I.CodLocatie, I1.CodObiect';
           if vWithEmul then
             sWith := sWith||'
             UNION ALL
             SELECT
               E.CODAGENT AGENT,
               E.CODLOCATIE,
               E1.CODOBIECT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT,
               SUM(E1.CANT * E1.PRET - E1.TVA) VALTOT_VAL,
               SUM(E1.CANT) CANT,
               0 ADAOSTOT,
               0 ADAOSTOT_VAL
             FROM EMULARE E
                  INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                  INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
             WHERE E.DATABON '||vCondData||'
                   AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                   AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
             GROUP BY E.CODAGENT, E.CODLOCATIE, E1.CODOBIECT
             ';
           end if;
           swith := swith||'
               ) S
               GROUP BY S.Agent, S.CodLocatie, S.CodObiect';
           EXECUTE SWITH;
        end if;
      end if;
    end if;
  end if;

  if vSubunit then
    if vSediiL = 0 then
      if vOrder in (1,3) then
        if vAvize = 1 then
          sSelect :=
          'SELECT coalesce(NAO.Denumire, C.Den_Cont),
                 NUM.Den_UM DenUM,
                 V.Cant Cant,
                 V.Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret,
                 V.Val Valoare,
                 0 Pret_Val,
                 0 Valoare_Val,
                 ''Lei'' Valuta,
                 P.Den_Part,
                 ValClient.ValTot ValTot,
                 0 ValTot_Val,
                 ValAgent.ValTotAgent,
                 0 ValTotAgent_Val,
                 case when coalesce(NAO.CodObiect, -1) &lt;&gt; -1 then
                 pkg_list_base_topclientiold_GetNrFact_Art(NAO.CodObiect, P.CodPart, 1,0)
                 else
                 pkg_list_base_topclientiold_GetNrFact_Art(C.CodCont, P.CodPart, -1,0)
                 end,
                 pkg_list_base_topclientiold_GetNrFact_Part(P.CodPart, 0),
                 coalesce(V.adaos, 0),
                 coalesce(v.adaos * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end), 0),
                 0,
                 0,
                 V.ValAchiz/(case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) PretAchiz, V.agent, '''', SUB.Den_Subunit,
                 coalesce(ValAgentArt.ValTotAgent,0),
                 0,
                 coalesce(ValAgentArt.Cant,0) '||gUserAlias||'
          FROM
              (
                SELECT S.CodPart,
                       S.CodObiect,
                       SUM(S.Cant) Cant,
                       SUM(S.Val) Val,
                       0 Val_Val,
                       null CodCont,
                       SUM(S.Adaos) adaos,
                       sum(coalesce(S.ValAchiz, 0)) valachiz,
                       S.Agent,
                       S.CodAgent,
                       S.Subunitatea
                FROM
                (
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) Adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (21, 26)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume, I.Subunitatea,AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  SUM(Adaosuri.Adaos) Adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (21, 26)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume, I.Subunitatea,AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1=adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21 AND I1.TipLinie &lt;&gt; ''G''
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume, I.Subunitatea,AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  SUM(adaosuri.adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT  JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     LEFT  JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1=adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21 AND I1.TipLinie &lt;&gt; ''G''
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume, I.Subunitatea,AG.CODPERS
              ) S
                GROUP BY S.CodObiect, S.CodPart, S.Semn, S.agent, S.Subunitatea, S.CODAGENT
                UNION ALL
                SELECT S.CodPart,
                       null CodObiect,
                       SUM(S.Cant) Cant,
                       SUM(S.Val) Val,
                       0 Val_Val,
                       S.CodCont,
                       sum(s.adaos) adaos,
                       sum(coalesce(S.ValAchiz, 0)) valachiz,
                       S.Agent,
                       S.CodAgent,
                       S.Subunitatea
                FROM
                (
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact * coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT JOIN TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  sum(Adaosuri.Adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact * coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT JOIN TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)* coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume, I.Subunitatea,AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  sum(adaosuri.adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)* coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume, I.Subunitatea,AG.CODPERS
              ) S
                GROUP BY S.CodCOnt, S.CodPart, S.Semn, S.agent, S.Subunitatea, S.CodAgent';
         if vWithEmul then
           sSelect := sSelect||'
              UNION ALL
              SELECT
                E.CodPart,
                E1.CodObiect,
                SUM(E1.Cant) Cant,
                SUM(E1.CANT * E1.PRET - E1.TVA) Val,
                0 Val_Val,
                0 CodCont,
                0 adaos,
                SUM(E1.CANT * E1.PRET - E1.TVA) valachiz,
                AG.NUME||'' ''||AG.PRENUME AGENT,
                E.CodAgent,
                C.SUBUNITATEA
              FROM EMULARE E
                   INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                   INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
                   LEFT JOIN NPERS AG ON AG.CODPERS = E.CODAGENT
              WHERE E.DATABON '||vCondData||'
                    AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                    AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
              GROUP BY E.CODPART, E1.CODOBIECT, E.CODAGENT, C.SUBUNITATEA, AG.NUME, AG.PRENUME';
         end if;
         sSelect := sSelect||'
              ) V
              INNER JOIN NSUBUNIT SUB ON SUB.CODSUBUNIT = V.SUBUNITATEA
              LEFT JOIN TMP_TOPCLI_VALCLIENT VALCLIENT ON V.CodPart = ValClient.CodPart and v.subunitatea = ValClient.Subunitatea
              LEFT JOIN TMP_TOPCLI_VALAGENT VALAGENT ON V.Agent = ValAgent.Agent and v.subunitatea = ValAgent.Subunitatea
              LEFT JOIN TMP_TOPCLI_VALAGENTART VALAGENTART ON V.Agent = ValAgentArt.Agent and v.subunitatea = ValAgentArt.Subunitatea and v.codobiect = ValAgentArt.CodObiect
              LEFT JOIN NARTOBJ NAO ON NAO.CODOBIECT = V.CODOBIECT
              LEFT JOIN NCONT C ON V.CODCONT = C.CODCONT
              LEFT JOIN NART ART ON NAO.CodArticol = ART.CodArticol
              LEFT JOIN NCLASEA CLSA ON ART.Clasa = CLSA.CodClaseA
              LEFT JOIN NUM ON ART.UM = NUM.CODUM
              LEFT JOIN NPART P ON V.CodPart = P.CodPart
              LEFT JOIN NPARTCODFISC CF ON P.CodPart = CF.CodPart AND CF.Principal = 1
              LEFT JOIN NCLASEP CLSP ON P.CodClasa = CLSP.CodClaseP
              LEFT JOIN NAGENDA AG ON AG.CodPart = V.CodPart AND AG.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(AG.INACTIV, 0) = 0
              LEFT JOIN NPERS AGENT ON AG.CodAgent = AGENT.CodPers
              LEFT JOIN NLOCALIT LOC ON AG.CodLocalit = LOC.CodLOcalit
              LEFT JOIN NJUDET JUD ON LOC.CodJudet = JUD.CodJudet
              LEFT JOIN NLOCALIT LOCL ON 0 = LOCL.CodLOcalit
              LEFT JOIN NJUDET JUDL ON LOCL.CodJudet = JUDL.CodJudet'||
              gSuplJoins||'
            WHERE V.CANT &lt;&gt; 0
            ';
        else
          sSelect :=
          'SELECT coalesce(NAO.Denumire, C.Den_Cont),
                 NUM.Den_UM DenUM,
                 V.Cant Cant,
                 V.Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret,
                 V.Val Valoare,
                 0 Pret_Val,
                 0 Valoare_Val,
                 ''Lei'' Valuta,
                 P.Den_Part,
                 ValClient.ValTot ValTot,
                 0 ValTot_Val,
                 ValAgent.ValTotAgent,
                 0 ValTotAgent_Val,
                 case when coalesce(NAO.CodObiect, -1) &lt;&gt; -1 then
                 pkg_list_base_topclientiold_GetNrFact_Art(NAO.CodObiect, P.CodPart, 1, 0)
                 else
                 pkg_list_base_topclientiold_GetNrFact_Art(C.CodCont, P.CodPart, -1, 0)
                 end,
                 pkg_list_base_topclientiold_GetNrFact_Part(P.CodPart, 0),
                 coalesce(V.adaos, 0),
                 coalesce(v.adaos * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end), 0),
                 0,
                 0,
                 V.ValAchiz/(case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) PretAchiz,
                 V.Agent, '''', SUB.Den_Subunit,
                 coalesce(ValAgentArt.ValTotAgent,0),
                 0,
                 coalesce(ValAgentArt.Cant,0) '||gUserAlias||'
          FROM
              (
                SELECT S.CodPart,
                       S.CodObiect,
                       SUM(S.Cant) Cant,
                       SUM(S.Val) Val,
                       0 Val_Val,
                       null CodCont,
                       SUM(S.Adaos) adaos,
                       sum(coalesce(S.ValAchiz, 0)) valachiz,
                       S.agent,
                       S.CodAgent,
                       S.Subunitatea
                FROM
                (
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) Adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     INNER JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     INNER JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (21, 20)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  SUM(Adaosuri.Adaos) Adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (21, 20)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1=adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21 AND I1.TipLinie &lt;&gt; ''G''
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  SUM(adaosuri.adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1=adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21 AND I1.TipLinie &lt;&gt; ''G''
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
              ) S
                GROUP BY S.CodObiect, S.CodPart, S.Semn, S.agent, S.Subunitatea, S.CodAgent
                UNION ALL
                SELECT S.CodPart,
                       null CodObiect,
                       SUM(S.Cant) Cant,
                       SUM(S.Val) Val,
                       0 Val_Val,
                       S.CodCont,
                       sum(s.adaos) adaos,
                       sum(coalesce(S.ValAchiz, 0)) valachiz,
                       S.agent,
                       S.CodAgent,
                       S.Subunitatea
                FROM
                (
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact * coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT JOIN TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  sum(Adaosuri.Adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact * coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT JOIN TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  sum(adaosuri.adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos,AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos,AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
              ) S
                GROUP BY S.CodCOnt, S.CodPart, S.Semn, S.Agent, S.Subunitatea, S.CodAgent';
        if vWithEmul then
           sSelect := sSelect||'
              UNION ALL
              SELECT
                E.CodPart,
                E1.CodObiect,
                SUM(E1.Cant) Cant,
                SUM(E1.CANT * E1.PRET - E1.TVA) Val,
                0 Val_Val,
                0 CodCont,
                0 adaos,
                SUM(E1.CANT * E1.PRET - E1.TVA) valachiz,
                AG.NUME||'' ''||AG.PRENUME AGENT,
                E.CodAgent,
                C.SUBUNITATEA
              FROM EMULARE E
                   INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                   INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
                   LEFT JOIN NPERS AG ON AG.CODPERS = E.CODAGENT
              WHERE E.DATABON '||vCondData||'
                    AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                    AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
              GROUP BY E.CODPART, E1.CODOBIECT, E.CODAGENT, C.SUBUNITATEA, AG.NUME, AG.PRENUME  ';
        end if;
        sselect := sselect ||'
              ) V
              INNER JOIN NSUBUNIT SUB ON SUB.CODSUBUNIT = V.SUBUNITATEA
              LEFT JOIN TMP_TOPCLI_VALCLIENT VALCLIENT ON V.CodPart = ValClient.CodPart and v.subunitatea = ValClient.Subunitatea
              LEFT JOIN TMP_TOPCLI_VALAGENT VALAGENT ON V.CodAgent = ValAgent.Agent and v.subunitatea = ValAgent.Subunitatea
              LEFT JOIN TMP_TOPCLI_VALAGENTART VALAGENTART ON V.CodAgent = ValAgentArt.Agent and v.subunitatea = ValAgentArt.Subunitatea and v.codobiect = ValAgentArt.CodObiect
              LEFT JOIN NARTOBJ NAO ON NAO.CODOBIECT = V.CODOBIECT
              LEFT JOIN NCONT C ON V.CODCONT = C.CODCONT
              LEFT JOIN NART ART ON NAO.CodArticol = ART.CodArticol
              LEFT JOIN NCLASEA CLSA ON ART.Clasa = CLSA.CodClaseA
              LEFT JOIN NUM ON ART.UM = NUM.CODUM
              LEFT JOIN NPART P ON V.CodPart = P.CodPart
              LEFT JOIN NPARTCODFISC CF ON P.CodPart = CF.CodPart AND CF.Principal = 1
              LEFT JOIN NCLASEP CLSP ON P.CodClasa = CLSP.CodClaseP
              LEFT JOIN NAGENDA AG ON AG.CodPart = V.CodPart AND AG.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(AG.INACTIV, 0) = 0
              LEFT JOIN NPERS AGENT ON AG.CodAgent = AGENT.CodPers
              LEFT JOIN NLOCALIT LOC ON AG.CodLocalit = LOC.CodLOcalit
              LEFT JOIN NJUDET JUD ON LOC.CodJudet = JUD.CodJudet
              LEFT JOIN NLOCALIT LOCL ON 0 = LOCL.CodLOcalit
              LEFT JOIN NJUDET JUDL ON LOCL.CodJudet = JUDL.CodJudet'||
              gSuplJoins||'
            WHERE V.CANT &lt;&gt; 0
            ';
        end if;
      else
        if vAvize = 1 then
          sSelect :=
          'SELECT coalesce(NAO.Denumire, C.Den_Cont),
                 NUM.Den_UM DenUM,
                 V.Cant Cant,
                 V.Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret,
                 V.Val Valoare,
                 V.Val_Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret_Val,
                 V.Val_Val Valoare_Val,
                 pkg_monede.get_simbol_moneda(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU())) Valuta,
                 P.Den_Part,
                 ValClient.ValTot ValTot,
                 ValClient.ValTot_Val ValTot_Val,
                 ValAgent.ValTotAgent ValTotAgent,
                 ValAgent.ValTotAgent_Val ValTotAgent_Val,
                 case when coalesce(NAO.CodObiect, -1) &lt;&gt; -1 then
                 pkg_list_base_topclientiold_GetNrFact_Art(NAO.CodObiect, P.CodPart, 1, 0)
                 else
                 pkg_list_base_topclientiold_GetNrFact_Art(C.CodCont, P.CodPart, -1, 0)
                 end,
                 pkg_list_base_topclientiold_GetNrFact_Part(P.CodPart, 0),
                 coalesce(v.adaos, 0),
                 coalesce(v.adaos * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end), 0),
                 V.adaos_val,
                 v.adaos_val * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end),
                 V.ValAchiz/(case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) PretAchiz,
                 V.Agent, '''', SUB.Den_Subunit,
                 coalesce(ValAgentArt.ValTotAgent,0),
                 coalesce(ValAgentArt.ValTotAgent_Val,0),
                 coalesce(ValAgentArt.Cant,0) '||gUserAlias||'
          FROM
              (
                SELECT S.CodPart,
                       S.CodObiect,
                       SUM(S.Cant) Cant,
                       SUM(S.Val) Val,
                       SUM(S.Val_Val) Val_Val,
                       null CodCont,
                       SUM(S.Adaos) adaos,
                       SUM(S.Adaos_Val) adaos_val,
                       SUM(coalesce(S.ValAchiz, 0)) ValAchiz,
                       S.Agent,
                       S.CodAgent,
                       S.Subunitatea
                FROM
                (
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  sum(l1.cant/i1.cant*adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(adaosuri.adaos) adaos,
                  sum(adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  sum(l1.cant/i1.cant*adaosuri.adaos /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.PU - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(adaosuri.adaos) adaos,
                  sum(adaosuri.adaos /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.PU - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
              ) S
                GROUP BY S.CodObiect, S.CodPart, S.Semn, S.agent, S.Subunitatea, S.CodAgent
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  sum(l1.cant/i1.cant*adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(adaosuri.adaos) adaos,
                  sum(adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
                UNION ALL
                SELECT S.CodPart,
                       null CodObiect,
                       SUM(S.Cant) Cant,
                       SUM(S.Val) Val,
                       SUM(S.Val_Val) Val_Val,
                       S.CodCont,
                       SUM(S.Adaos) adaos,
                       SUM(S.Adaos_val) adaos_val,
                       SUM(coalesce(S.ValAchiz, 0)) ValAchiz,
                       S.Agent,
                       S.CodAgent,
                       S.Subunitatea
                FROM
                (
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  sum(l1.cant/i1.cant*adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(adaosuri.adaos) adaos,
                  sum(adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
              ) S
                GROUP BY S.CodCont, S.CodPart, S.Semn, S.agent, S.Subunitatea, S.CodAgent';
        if vWithEmul then
           sSelect := sSelect||'
              UNION ALL
              SELECT
                E.CodPart,
                E1.CodObiect,
                SUM(E1.Cant) Cant,
                SUM(E1.CANT * E1.PRET - E1.TVA) Val,
                0 Val_Val,
                0 CodCont,
                0 adaos,
                SUM(E1.CANT * E1.PRET - E1.TVA) valachiz,
                AG.NUME||'' ''||AG.PRENUME AGENT,
                E.CodAgent,
                C.SUBUNITATEA
              FROM EMULARE E
                   INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                   INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
                   LEFT JOIN NPERS AG ON AG.CODPERS = E.CODAGENT
              WHERE E.DATABON '||vCondData||'
                    AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                    AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
              GROUP BY E.CODPART, E1.CODOBIECT, E.CODAGENT, C.SUBUNITATEA, AG.NUME, AG.PRENUME  ';
        end if;
        sselect := sselect ||'
              ) V
              INNER JOIN NSUBUNIT SUB ON SUB.CODSUBUNIT = V.SUBUNITATEA
              LEFT JOIN TMP_TOPCLI_VALCLIENT VALCLIENT ON V.CodPart = ValClient.CodPart and v.subunitatea = ValClient.Subunitatea
              LEFT JOIN TMP_TOPCLI_VALAGENT VALAGENT ON V.CodAgent = ValAgent.Agent and v.subunitatea = ValAgent.Subunitatea
              LEFT JOIN TMP_TOPCLI_VALAGENTART VALAGENTART ON V.CodAgent = ValAgentArt.Agent and v.subunitatea = ValAgentArt.Subunitatea and v.codobiect = ValAgentArt.codobiect
              LEFT JOIN NARTOBJ NAO ON NAO.CODOBIECT = V.CODOBIECT
              LEFT JOIN NCONT C ON V.CODCONT = C.CODCONT
              LEFT JOIN NART ART ON NAO.CodArticol = ART.CodArticol
              LEFT JOIN NCLASEA CLSA ON ART.Clasa = CLSA.CodClaseA
              LEFT JOIN NUM ON ART.UM = NUM.CODUM
              LEFT JOIN NPART P ON V.CodPart = P.CodPart
              LEFT JOIN NPARTCODFISC CF ON P.CodPart = CF.CodPart AND CF.Principal = 1
              LEFT JOIN NCLASEP CLSP ON P.CodClasa = CLSP.CodClaseP
              LEFT JOIN NAGENDA AG ON AG.CodPart = V.CodPart AND AG.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(AG.INACTIV, 0) = 0
              LEFT JOIN NPERS AGENT ON AG.CodAgent = AGENT.CodPers
              LEFT JOIN NLOCALIT LOC ON AG.CodLocalit = LOC.CodLOcalit
              LEFT JOIN NJUDET JUD ON LOC.CodJudet = JUD.CodJudet
              LEFT JOIN NLOCALIT LOCL ON 0 = LOCL.CodLOcalit
              LEFT JOIN NJUDET JUDL ON LOCL.CodJudet = JUDL.CodJudet'||
              gSuplJoins||'
            WHERE V.CANT &lt;&gt; 0
            ';
        else
          sSelect :=
          'SELECT coalesce(NAO.Denumire, C.Den_Cont),
                 NUM.Den_UM DenUM,
                 V.Cant Cant,
                 V.Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret,
                 V.Val Valoare,
                 V.Val_Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret_Val,
                 V.Val_Val Valoare_Val,
                 pkg_monede.get_simbol_moneda(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU())) Valuta,
                 P.Den_Part,
                 ValClient.ValTot ValTot,
                 ValClient.ValTot_Val ValTot_Val,
                 ValAgent.ValTotAgent ValTotAgent,
                 ValAgent.ValTotAgent_Val ValTotAgent_Val,
                 case when coalesce(NAO.CodObiect, -1) &lt;&gt; -1 then
                 pkg_list_base_topclientiold_GetNrFact_Art(NAO.CodObiect, P.CodPart, 1, 0)
                 else
                 pkg_list_base_topclientiold_GetNrFact_Art(C.CodCont, P.CodPart, -1, 0)
                 end,
                 pkg_list_base_topclientiold_GetNrFact_Part(P.CodPart, 0),
                 coalesce(v.adaos, 0),
                 coalesce(v.adaos * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end), 0),
                 V.adaos_val,
                 v.adaos_val * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end),
                 V.ValAchiz/(case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) PretAchiz, V.agent, '''', SUB.Den_Subunit,
                 coalesce(ValAgentArt.ValTotAgent,0),
                 coalesce(ValAgentArt.ValTotAgent_Val,0),
                 coalesce(ValAgentArt.Cant,0) '||gUserAlias||'
          FROM
              (
                SELECT S.CodPart,
                       S.CodObiect,
                       SUM(S.Cant) Cant,
                       SUM(S.Val) Val,
                       SUM(S.Val_Val) Val_Val,
                       null CodCont,
                       SUM(S.Adaos) adaos,
                       SUM(S.Adaos_Val) adaos_val,
                       SUM(coalesce(S.ValAchiz, 0)) ValAchiz,
                       S.agent,
                       S.CodAgent,
                       S.Subunitatea
                FROM
                (
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  sum(l1.cant/i1.cant*adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.PU * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz ,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(adaosuri.adaos) adaos,
                  sum(adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.PU * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz ,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  sum(l1.cant/i1.cant*adaosuri.adaos /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.PU - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(adaosuri.adaos) adaos,
                  sum(adaosuri.adaos /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.PU - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
              ) S
                GROUP BY S.CodObiect, S.CodPart, S.Semn, S.Agent, S.Subunitatea, S.CodAgent
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  sum(l1.cant/i1.cant*adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  Ag.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(adaosuri.adaos) adaos,
                  sum(adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  Ag.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
                UNION ALL
                SELECT S.CodPart,
                       null CodObiect,
                       SUM(S.Cant) Cant,
                       SUM(S.Val) Val,
                       SUM(S.Val_Val) Val_Val,
                       S.CodCont,
                       SUM(S.Adaos) adaos,
                       SUM(S.Adaos_val) adaos_val,
                       SUM(coalesce(S.ValAchiz, 0)) ValAchiz,
                       S.agent,
                       S.CodAgent,
                       S.Subunitatea
                FROM
                (
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  sum(l1.cant/i1.cant*adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(adaosuri.adaos) adaos,
                  sum(adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT,
                  I.Subunitatea
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, I.Subunitatea, AG.CODPERS
              ) S
                GROUP BY S.CodCont, S.CodPart, S.Semn, S.agent, S.Subunitatea, S.CodAgent';
        if vWithEmul then
           sSelect := sSelect||'
              UNION ALL
              SELECT
                E.CodPart,
                E1.CodObiect,
                SUM(E1.Cant) Cant,
                SUM(E1.CANT * E1.PRET - E1.TVA) Val,
                0 Val_Val,
                0 CodCont,
                0 adaos,
                SUM(E1.CANT * E1.PRET - E1.TVA) valachiz,
                AG.NUME||'' ''||AG.PRENUME AGENT,
                E.CodAgent,
                C.SUBUNITATEA
              FROM EMULARE E
                   INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                   INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
                   LEFT JOIN NPERS AG ON AG.CODPERS = E.CODAGENT
              WHERE E.DATABON '||vCondData||'
                    AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                    AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
              GROUP BY E.CODPART, E1.CODOBIECT, E.CODAGENT, C.SUBUNITATEA, AG.NUME, AG.PRENUME  ';
        end if;
        sselect := sselect||'
              ) V
              INNER JOIN NSUBUNIT SUB ON SUB.CODSUBUNIT = V.SUBUNITATEA
              LEFT JOIN TMP_TOPCLI_VALCLIENT VALCLIENT ON V.CodPart = ValClient.CodPart and v.subunitatea = ValClient.Subunitatea
              LEFT JOIN TMP_TOPCLI_VALAGENT VALAGENT ON V.CodAgent = ValAgent.Agent and v.subunitatea = ValAgent.Subunitatea
              LEFT JOIN TMP_TOPCLI_VALAGENTART VALAGENTART ON V.CodAgent = ValAgentArt.Agent and v.subunitatea = ValAgentArt.Subunitatea and v.codobiect = ValAgentArt.codobiect
              LEFT JOIN NARTOBJ NAO ON NAO.CODOBIECT = V.CODOBIECT
              LEFT JOIN NCONT C ON V.CODCONT = C.CODCONT
              LEFT JOIN NART ART ON NAO.CodArticol = ART.CodArticol
              LEFT JOIN NCLASEA CLSA ON ART.Clasa = CLSA.CodClaseA
              LEFT JOIN NUM ON ART.UM = NUM.CODUM
              LEFT JOIN NPART P ON V.CodPart = P.CodPart
              LEFT JOIN NPARTCODFISC CF ON P.CodPart = CF.CodPart AND CF.Principal = 1
              LEFT JOIN NCLASEP CLSP ON P.CodClasa = CLSP.CodClaseP
              LEFT JOIN NAGENDA AG ON AG.CodPart = V.CodPart AND AG.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(AG.INACTIV, 0) = 0
              LEFT JOIN NPERS AGENT ON AG.CodAgent = AGENT.CodPers
              LEFT JOIN NLOCALIT LOC ON AG.CodLocalit = LOC.CodLOcalit
              LEFT JOIN NJUDET JUD ON LOC.CodJudet = JUD.CodJudet
              LEFT JOIN NLOCALIT LOCL ON 0 = LOCL.CodLOcalit
              LEFT JOIN NJUDET JUDL ON LOCL.CodJudet = JUDL.CodJudet'||
              gSuplJoins||'
            WHERE V.CANT &lt;&gt; 0
            ';
        end if;
      end if;
    else
      if vOrder in (1,3) then
      if vAvize = 1 then
        sSelect :=
        'SELECT coalesce(NAO.Denumire, C.Den_Cont),
               NUM.Den_UM DenUM,
               V.Cant Cant,
               V.Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret,
               V.Val Valoare,
               0 Pret_Val,
               0 Valoare_Val,
               ''Lei'' Valuta,
               P.Den_Part,
               ValClient.ValTot ValTot,
               0 ValTot_Val,
               ValAgent.ValTotAgent ValTotAgent,
               0 ValTotAgent_Val,
               case when coalesce(NAO.CodObiect, -1) &lt;&gt; -1 then
               pkg_list_base_topclientiold_GetNrFact_Art(NAO.CodObiect, P.CodPart, 1, V.CodLocatie)
               else
               pkg_list_base_topclientiold_GetNrFact_Art(C.CodCont, P.CodPart, -1, V.CodLocatie)
               end,
               pkg_list_base_topclientiold_GetNrFact_Part(P.CodPart, V.CodLocatie),
               coalesce(V.adaos, 0),
               coalesce(v.adaos * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end), 0),
               0,
               0,
               V.ValAchiz/(case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) PretAchiz, V.agent,
               AGL.Obs, SUB.Den_Subunit,
               coalesce(ValAgentArt.ValTotAgent,0),
               0,
               coalesce(ValAgentArt.Cant,0) '||gUserAlias||'
        FROM
            (
              SELECT S.CodPart,
                     S.CodObiect,
                     SUM(S.Cant) Cant,
                     SUM(S.Val) Val,
                     0 Val_Val,
                     null CodCont,
                     SUM(S.Adaos) adaos,
                     sum(coalesce(S.ValAchiz, 0)) valachiz,
                     S.Agent,
                     S.CodAgent,
                     S.CodLocatie,
                     S.Subunitatea
              FROM
              (
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) Adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (21, 26)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0 '||sCust||'
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                SUM(Adaosuri.Adaos) Adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (21, 26)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0 '||sCust||'
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1=adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                   LEFT JOIN NAGENDA AGL ON AGL.CodAgenda = I.CodLocatie
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21 AND I1.TipLinie &lt;&gt; ''G''
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                SUM(adaosuri.adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1=adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                   LEFT JOIN NAGENDA AGL ON AGL.CodAgenda = I.CodLocatie
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21 AND I1.TipLinie &lt;&gt; ''G''
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, I.Subunitatea, AG.CODPERS
            ) S
              GROUP BY S.CodObiect, S.CodPart, S.Semn, S.agent,S.CodLocatie, S.Subunitatea, S.CodAgent
              UNION ALL
              SELECT S.CodPart,
                     null CodObiect,
                     SUM(S.Cant) Cant,
                     SUM(S.Val) Val,
                     0 Val_Val,
                     S.CodCont,
                     sum(s.adaos) adaos,
                     sum(coalesce(S.ValAchiz, 0)) valachiz,
                     S.Agent,
                     S.CodAgent,
                     S.CodLocatie,
                     S.Subunitatea
              FROM
              (
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact * coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT JOIN TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (26, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0 '||sCust||'
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                sum(Adaosuri.Adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact * coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   LEFT JOIN TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (26, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0 '||sCust||'
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)* coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                sum(adaosuri.adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)* coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, I.Subunitatea, AG.CODPERS
            ) S
              GROUP BY S.CodCOnt, S.CodPart, S.Semn, S.agent, S.CodLocatie, S.Subunitatea, S.CodAgent';
        if vWithEmul then
           sSelect := sSelect||'
            UNION ALL
              SELECT
                E.CodPart,
                E1.CodObiect,
                SUM(E1.Cant) Cant,
                SUM(E1.CANT * E1.PRET - E1.TVA) Val,
                0 Val_Val,
                0 CodCont,
                0 adaos,
                SUM(E1.CANT * E1.PRET - E1.TVA) valachiz,
                AG.NUME||'' ''||AG.PRENUME AGENT,
                E.CodAgent,
                E.CodLocatie,
                C.SUBUNITATEA
              FROM EMULARE E
                   INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                   INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
                   LEFT JOIN NPERS AG ON AG.CODPERS = E.CODAGENT
              WHERE E.DATABON '||vCondData||'
                    AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                    AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
              GROUP BY E.CODPART, E1.CODOBIECT, E.CODAGENT, E.CODLOCATIE, AG.NUME, AG.PRENUME, C.SUBUNITATEA  ';
        end if;
        sselect := sselect||'
            ) V
            INNER JOIN NSUBUNIT SUB ON SUB.CODSUBUNIT = V.SUBUNITATEA
            LEFT JOIN TMP_TOPCLI_VALCLIENT VALCLIENT ON V.CodPart = ValClient.CodPart and V.CodLocatie = ValClient.CodLocatie and v.subunitatea = ValClient.Subunitatea
            LEFT JOIN TMP_TOPCLI_VALAGENT VALAGENT ON V.CodAgent = ValAgent.Agent and V.CodLocatie = ValAgent.CodLocatie and v.subunitatea = ValAgent.Subunitatea
            LEFT JOIN TMP_TOPCLI_VALAGENTART VALAGENTART ON V.CodAgent = ValAgentArt.Agent and V.CodLocatie = ValAgentArt.CodLocatie and v.subunitatea = ValAgentArt.Subunitatea and v.codobiect = ValAgentArt.codobiect
            LEFT JOIN NARTOBJ NAO ON NAO.CODOBIECT = V.CODOBIECT
            LEFT JOIN NCONT C ON V.CODCONT = C.CODCONT
            LEFT JOIN NART ART ON NAO.CodArticol = ART.CodArticol
            LEFT JOIN NCLASEA CLSA ON ART.Clasa = CLSA.CodClaseA
            LEFT JOIN NUM ON ART.UM = NUM.CODUM
            LEFT JOIN NPART P ON V.CodPart = P.CodPart
            LEFT JOIN NPARTCODFISC CF ON P.CodPart = CF.CodPart AND CF.Principal = 1
            LEFT JOIN NCLASEP CLSP ON P.CodClasa = CLSP.CodClaseP
            LEFT JOIN NAGENDA AG ON AG.CodPart = V.CodPart AND AG.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(AG.INACTIV, 0) = 0
            LEFT JOIN NPERS AGENT ON AG.CodAgent = AGENT.CodPers
            LEFT JOIN NLOCALIT LOC ON AG.CodLocalit = LOC.CodLOcalit
            LEFT JOIN NJUDET JUD ON LOC.CodJudet = JUD.CodJudet
            LEFT JOIN NAGENDA AGL ON AGL.CodAgenda = V.CodLocatie
            LEFT JOIN NLOCALIT LOCL ON AGL.CodLocalit = LOCL.CodLOcalit
            LEFT JOIN NJUDET JUDL ON LOCL.CodJudet = JUDL.CodJudet'||
            gSuplJoins||'
          WHERE V.CANT &lt;&gt; 0
          ';
      else
        sSelect :=
        'SELECT coalesce(NAO.Denumire, C.Den_Cont),
               NUM.Den_UM DenUM,
               V.Cant Cant,
               V.Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret,
               V.Val Valoare,
               0 Pret_Val,
               0 Valoare_Val,
               ''Lei'' Valuta,
               P.Den_Part,
               ValClient.ValTot ValTot,
               0 ValTot_Val,
               ValAgent.ValTotAgent ValTotAgent,
               0 ValTotAgent_Val,
               case when coalesce(NAO.CodObiect, -1) &lt;&gt; -1 then
               pkg_list_base_topclientiold_GetNrFact_Art(NAO.CodObiect, P.CodPart, 1, V.CodLocatie)
               else
               pkg_list_base_topclientiold_GetNrFact_Art(C.CodCont, P.CodPart, -1, V.CodLocatie)
               end,
               pkg_list_base_topclientiold_GetNrFact_Part(P.CodPart, V.CodLocatie),
               coalesce(V.adaos, 0),
               coalesce(v.adaos * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end), 0),
               0,
               0,
               V.ValAchiz/(case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) PretAchiz,
               V.Agent,
               AGL.Obs, SUB.Den_Subunit,
               coalesce(ValAgentArt.ValTotAgent,0),
               0,
               coalesce(ValAgentArt.Cant,0) '||gUserAlias||'
        FROM
            (
              SELECT S.CodPart,
                     S.CodObiect,
                     SUM(S.Cant) Cant,
                     SUM(S.Val) Val,
                     0 Val_Val,
                     null CodCont,
                     SUM(S.Adaos) adaos,
                     sum(coalesce(S.ValAchiz, 0)) valachiz,
                     S.agent,
                     S.CodAgent,
                     S.CodLocatie,
                     S.Subunitatea
              FROM
              (
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) Adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                SUM(Adaosuri.Adaos) Adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1=adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21 AND I1.TipLinie &lt;&gt; ''G''
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                SUM(adaosuri.adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1=adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21 AND I1.TipLinie &lt;&gt; ''G''
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, I.Subunitatea, AG.CODPERS
            ) S
              GROUP BY S.CodObiect, S.CodPart, S.Semn, S.agent, S.CodLocatie, S.Subunitatea, S.CodAgent
              UNION ALL
              SELECT S.CodPart,
                     null CodObiect,
                     SUM(S.Cant) Cant,
                     SUM(S.Val) Val,
                     0 Val_Val,
                     S.CodCont,
                     sum(s.adaos) adaos,
                     sum(coalesce(S.ValAchiz, 0)) valachiz,
                     S.agent,
                     S.CodAgent,
                     S.CodLocatie,
                     S.Subunitatea
              FROM
              (
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact * coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT JOIN TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (20, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                sum(Adaosuri.Adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact * coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   LEFT JOIN TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (20, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos,AG.nume, AG.prenume,
                       I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                sum(adaosuri.adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos,AG.nume, AG.prenume,
                       I.CodLocatie, I.Subunitatea, AG.CODPERS
            ) S
              GROUP BY S.CodCOnt, S.CodPart, S.Semn, S.Agent, S.CodLocatie, S.Subunitatea, S.CodAgent';
        if vWithEmul then
           sSelect := sSelect||'
            UNION ALL
              SELECT
                E.CodPart,
                E1.CodObiect,
                SUM(E1.Cant) Cant,
                SUM(E1.CANT * E1.PRET - E1.TVA) Val,
                0 Val_Val,
                0 CodCont,
                0 adaos,
                SUM(E1.CANT * E1.PRET - E1.TVA) valachiz,
                AG.NUME||'' ''||AG.PRENUME AGENT,
                E.CodAgent,
                E.CodLocatie,
                C.SUBUNITATEA
              FROM EMULARE E
                   INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                   INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
                   LEFT JOIN NPERS AG ON AG.CODPERS = E.CODAGENT
              WHERE E.DATABON '||vCondData||'
                    AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                    AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
              GROUP BY E.CODPART, E1.CODOBIECT, E.CODAGENT, E.CODLOCATIE, AG.NUME, AG.PRENUME,C.SUBUNITATEA  ';
         end if;
         sselect := sselect||'
            ) V
            INNER JOIN NSUBUNIT SUB ON SUB.CODSUBUNIT = V.SUBUNITATEA
            LEFT JOIN TMP_TOPCLI_VALCLIENT VALCLIENT ON V.CodPart = ValClient.CodPart and V.CodLocatie = ValClient.CodLocatie and v.subunitatea = ValClient.Subunitatea
            LEFT JOIN TMP_TOPCLI_VALAGENT VALAGENT ON V.CodAgent = ValAgent.Agent and V.CodLocatie = ValAgent.CodLocatie and v.subunitatea = ValAgent.Subunitatea
            LEFT JOIN TMP_TOPCLI_VALAGENTART VALAGENTART ON V.CodAgent = ValAgentArt.Agent and V.CodLocatie = ValAgentArt.CodLocatie and v.subunitatea = ValAgentArt.Subunitatea and v.codobiect = ValAgentArt.codobiect
            LEFT JOIN NARTOBJ NAO ON NAO.CODOBIECT = V.CODOBIECT
            LEFT JOIN NCONT C ON V.CODCONT = C.CODCONT
            LEFT JOIN NART ART ON NAO.CodArticol = ART.CodArticol
            LEFT JOIN NCLASEA CLSA ON ART.Clasa = CLSA.CodClaseA
            LEFT JOIN NUM ON ART.UM = NUM.CODUM
            LEFT JOIN NPART P ON V.CodPart = P.CodPart
            LEFT JOIN NPARTCODFISC CF ON P.CodPart = CF.CodPart AND CF.Principal = 1
            LEFT JOIN NCLASEP CLSP ON P.CodClasa = CLSP.CodClaseP
            LEFT JOIN NAGENDA AG ON AG.CodPart = V.CodPart AND AG.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(AG.INACTIV, 0) = 0
            LEFT JOIN NPERS AGENT ON AG.CodAgent = AGENT.CodPers
            LEFT JOIN NLOCALIT LOC ON AG.CodLocalit = LOC.CodLOcalit
            LEFT JOIN NJUDET JUD ON LOC.CodJudet = JUD.CodJudet
            LEFT JOIN NAGENDA AGL ON AGL.CodAgenda = V.CodLocatie
            LEFT JOIN NLOCALIT LOCL ON AGL.CodLocalit = LOCL.CodLOcalit
            LEFT JOIN NJUDET JUDL ON LOCL.CodJudet = JUDL.CodJudet'||
            gSuplJoins||'
          WHERE V.CANT &lt;&gt; 0
          ';
      end if;
    else
      if vAvize = 1 then
        sSelect :=
        'SELECT coalesce(NAO.Denumire, C.Den_Cont),
               NUM.Den_UM DenUM,
               V.Cant Cant,
               V.Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret,
               V.Val Valoare,
               V.Val_Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret_Val,
               V.Val_Val Valoare_Val,
               pkg_monede.get_simbol_moneda(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU())) Valuta,
               P.Den_Part,
               ValClient.ValTot ValTot,
               ValClient.ValTot_Val ValTot_Val,
               ValAgent.ValTotAgent ValTotAgent,
               ValAgent.ValTotAgent_Val ValTotAgent_Val,
               case when coalesce(NAO.CodObiect, -1) &lt;&gt; -1 then
               pkg_list_base_topclientiold_GetNrFact_Art(NAO.CodObiect, P.CodPart, 1, V.CodLocatie)
               else
               pkg_list_base_topclientiold_GetNrFact_Art(C.CodCont, P.CodPart, -1, V.CodLocatie)
               end,
               pkg_list_base_topclientiold_GetNrFact_Part(P.CodPart, V.CodLocatie),
               coalesce(v.adaos, 0),
               coalesce(v.adaos * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end), 0),
               V.adaos_val,
               v.adaos_val * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end),
               V.ValAchiz/(case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) PretAchiz,
               V.Agent,
               AGL.Obs, SUB.Den_Subunit,
               coalesce(ValAgentArt.ValTotAgent,0),
               coalesce(ValAgentArt.ValTotAgent_Val,0),
               coalesce(ValAgentArt.Cant,0) '||gUserAlias||'
        FROM
            (
              SELECT S.CodPart,
                     S.CodObiect,
                     SUM(S.Cant) Cant,
                     SUM(S.Val) Val,
                     SUM(S.Val_Val) Val_Val,
                     null CodCont,
                     SUM(S.Adaos) adaos,
                     SUM(S.Adaos_Val) adaos_val,
                     SUM(coalesce(S.ValAchiz, 0)) ValAchiz,
                     S.Agent,
                     S.CodAgent,
                     S.CodLocatie,
                     S.Subunitatea
              FROM
              (
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                sum(l1.cant/i1.cant*adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                coalesce(I.CodLocatie,0) CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (26, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0 '||sCust||'
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(adaosuri.adaos) adaos,
                sum(adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                coalesce(I.CodLocatie,0) CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (26, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0 '||sCust||'
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                sum(l1.cant/i1.cant*adaosuri.adaos /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.PU - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                coalesce(I.CodLocatie,0) CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(adaosuri.adaos) adaos,
                sum(adaosuri.adaos /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.PU - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                coalesce(I.CodLocatie,0) CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, I.Subunitatea, AG.CODPERS
            ) S
              GROUP BY S.CodObiect, S.CodPart, S.Semn, S.agent, S.CodLocatie, S.Subunitatea, S.CodAgent
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                sum(l1.cant/i1.cant*adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                coalesce(I.CodLocatie,0) CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (26, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0 '||sCust||'
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(adaosuri.adaos) adaos,
                sum(adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                coalesce(I.CodLocatie,0) CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (26, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0 '||sCust||'
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT S.CodPart,
                     null CodObiect,
                     SUM(S.Cant) Cant,
                     SUM(S.Val) Val,
                     SUM(S.Val_Val) Val_Val,
                     S.CodCont,
                     SUM(S.Adaos) adaos,
                     SUM(S.Adaos_val) adaos_val,
                     SUM(coalesce(S.ValAchiz, 0)) ValAchiz,
                     S.Agent,
                     S.CodAgent,
                     S.CodLocatie,
                     S.Subunitatea
              FROM
              (
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                sum(l1.cant/i1.cant*adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                coalesce(I.CodLocatie,0) CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(adaosuri.adaos) adaos,
                sum(adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                coalesce(I.CodLocatie,0) CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, I.Subunitatea, AG.CODPERS
            ) S
              GROUP BY S.CodCont, S.CodPart, S.Semn, S.agent, S.CodLocatie, S.Subunitatea, S.CodAgent';
        if vWithEmul then
           sSelect := sSelect||'
            UNION ALL
              SELECT
                E.CodPart,
                E1.CodObiect,
                SUM(E1.Cant) Cant,
                SUM(E1.CANT * E1.PRET - E1.TVA) Val,
                0 Val_Val,
                0 CodCont,
                0 adaos,
                SUM(E1.CANT * E1.PRET - E1.TVA) valachiz,
                AG.NUME||'' ''||AG.PRENUME AGENT,
                E.CodAgent,
                E.CodLocatie,
                C.SUBUNITATEA
              FROM EMULARE E
                   INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                   INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
                   LEFT JOIN NPERS AG ON AG.CODPERS = E.CODAGENT
              WHERE E.DATABON '||vCondData||'
                    AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                    AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
              GROUP BY E.CODPART, E1.CODOBIECT, E.CODAGENT, E.CODLOCATIE, AG.NUME, AG.PRENUME,C.SUBUNITATEA  ';
         end if;
         sselect := sselect||'
            ) V
            INNER JOIN NSUBUNIT SUB ON SUB.CODSUBUNIT = V.SUBUNITATEA
            LEFT JOIN TMP_TOPCLI_VALCLIENT VALCLIENT ON V.CodPart = ValClient.CodPart and V.CodLocatie = ValClient.CodLocatie and v.subunitatea = ValClient.Subunitatea
            LEFT JOIN TMP_TOPCLI_VALAGENT VALAGENT ON V.CodAgent = ValAgent.Agent and V.CodLocatie = ValAgent.CodLocatie and v.subunitatea = ValAgent.Subunitatea
            LEFT JOIN TMP_TOPCLI_VALAGENTART VALAGENTART ON V.CodAgent = ValAgentArt.Agent and V.CodLocatie = ValAgentArt.CodLocatie and v.subunitatea = ValAgentArt.Subunitatea and v.codobiect = ValAgentArt.codobiect
            LEFT JOIN NARTOBJ NAO ON NAO.CODOBIECT = V.CODOBIECT
            LEFT JOIN NCONT C ON V.CODCONT = C.CODCONT
            LEFT JOIN NART ART ON NAO.CodArticol = ART.CodArticol
            LEFT JOIN NCLASEA CLSA ON ART.Clasa = CLSA.CodClaseA
            LEFT JOIN NUM ON ART.UM = NUM.CODUM
            LEFT JOIN NPART P ON V.CodPart = P.CodPart
            LEFT JOIN NPARTCODFISC CF ON P.CodPart = CF.CodPart AND CF.Principal = 1
            LEFT JOIN NCLASEP CLSP ON P.CodClasa = CLSP.CodClaseP
            LEFT JOIN NAGENDA AG ON AG.CodPart = V.CodPart AND AG.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(AG.INACTIV, 0) = 0
            LEFT JOIN NPERS AGENT ON AG.CodAgent = AGENT.CodPers
            LEFT JOIN NLOCALIT LOC ON AG.CodLocalit = LOC.CodLOcalit
            LEFT JOIN NJUDET JUD ON LOC.CodJudet = JUD.CodJudet
            LEFT JOIN NAGENDA AGL ON AGL.CodAgenda = V.CodLocatie
            LEFT JOIN NLOCALIT LOCL ON AGL.CodLocalit = LOCL.CodLOcalit
            LEFT JOIN NJUDET JUDL ON LOCL.CodJudet = JUDL.CodJudet'||
            gSuplJoins||'
          WHERE V.CANT &lt;&gt; 0
          ';
      else
        sSelect :=
        'SELECT coalesce(NAO.Denumire, C.Den_Cont),
               NUM.Den_UM DenUM,
               V.Cant Cant,
               V.Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret,
               V.Val Valoare,
               V.Val_Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret_Val,
               V.Val_Val Valoare_Val,
               pkg_monede.get_simbol_moneda(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU())) Valuta,
               P.Den_Part,
               ValClient.ValTot ValTot,
               ValClient.ValTot_Val ValTot_Val,
               ValAgent.ValTotAgent ValTotAgent,
               ValAgent.ValTotAgent_Val ValTotAgent_Val,
               case when coalesce(NAO.CodObiect, -1) &lt;&gt; -1 then
               pkg_list_base_topclientiold_GetNrFact_Art(NAO.CodObiect, P.CodPart, 1, V.CodLocatie)
               else
               pkg_list_base_topclientiold_GetNrFact_Art(C.CodCont, P.CodPart, -1, V.CodLocatie)
               end,
               pkg_list_base_topclientiold_GetNrFact_Part(P.CodPart, V.CodLocatie),
               coalesce(v.adaos, 0),
               coalesce(v.adaos * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end), 0),
               V.adaos_val,
               v.adaos_val * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end),
               V.ValAchiz/(case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) PretAchiz, V.agent,
               AGL.Obs, SUB.Den_Subunit,
               coalesce(ValAgentArt.ValTotAgent,0),
               coalesce(ValAgentArt.ValTotAgent_Val,0),
               coalesce(ValAgentArt.Cant,0) '||gUserAlias||'
        FROM
            (
              SELECT S.CodPart,
                     S.CodObiect,
                     SUM(S.Cant) Cant,
                     SUM(S.Val) Val,
                     SUM(S.Val_Val) Val_Val,
                     null CodCont,
                     SUM(S.Adaos) adaos,
                     SUM(S.Adaos_Val) adaos_val,
                     SUM(coalesce(S.ValAchiz, 0)) ValAchiz,
                     S.agent,
                     S.CodAgent,
                     S.CodLocatie,
                     S.Subunitatea
              FROM
              (
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                sum(l1.cant/i1.cant*adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.PU * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz ,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (20, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(adaosuri.adaos) adaos,
                sum(adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.PU * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz ,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (20, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                sum(l1.cant/i1.cant*adaosuri.adaos /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.PU - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(adaosuri.adaos) adaos,
                sum(adaosuri.adaos /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.PU - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, I.Subunitatea, AG.CODPERS
            ) S
              GROUP BY S.CodObiect, S.CodPart, S.Semn, S.Agent, S.CodLocatie, S.Subunitatea, S.CodAgent
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                sum(l1.cant/i1.cant*adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                Ag.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (20, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(adaosuri.adaos) adaos,
                sum(adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                Ag.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (20, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT S.CodPart,
                     null CodObiect,
                     SUM(S.Cant) Cant,
                     SUM(S.Val) Val,
                     SUM(S.Val_Val) Val_Val,
                     S.CodCont,
                     SUM(S.Adaos) adaos,
                     SUM(S.Adaos_val) adaos_val,
                     SUM(coalesce(S.ValAchiz, 0)) ValAchiz,
                     S.agent,
                     S.CodAgent,
                     S.CodLocatie,
                     S.Subunitatea
              FROM
              (
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                sum(l1.cant/i1.cant*adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   LEFT  JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   LEFT  JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, I.Subunitatea, AG.CODPERS
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(adaosuri.adaos) adaos,
                sum(adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CODPERS CODAGENT,
                I.CodLocatie, I.Subunitatea
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, I.Subunitatea, AG.CODPERS
            ) S
              GROUP BY S.CodCont, S.CodPart, S.Semn, S.agent, S.CodLocatie, S.Subunitatea, S.CodAgent';
        if vWithEmul then
           sSelect := sSelect||'
            UNION ALL
              SELECT
                E.CodPart,
                E1.CodObiect,
                SUM(E1.Cant) Cant,
                SUM(E1.CANT * E1.PRET - E1.TVA) Val,
                0 Val_Val,
                0 CodCont,
                0 adaos,
                SUM(E1.CANT * E1.PRET - E1.TVA) valachiz,
                AG.NUME||'' ''||AG.PRENUME AGENT,
                E.CodAgent,
                E.CodLocatie,
                C.SUBUNITATEA
              FROM EMULARE E
                   INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                   INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
                   LEFT JOIN NPERS AG ON AG.CODPERS = E.CODAGENT
              WHERE E.DATABON '||vCondData||'
                    AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                    AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
              GROUP BY E.CODPART, E1.CODOBIECT, E.CODAGENT, E.CODLOCATIE, AG.NUME, AG.PRENUME,C.SUBUNITATEA  ';
        end if;
        sselect := sselect||'
            ) V
            INNER JOIN NSUBUNIT SUB ON SUB.CODSUBUNIT = V.SUBUNITATEA
            LEFT JOIN TMP_TOPCLI_VALCLIENT VALCLIENT ON V.CodPart = ValClient.CodPart and V.CodLocatie = ValClient.CodLocatie and v.subunitatea = ValClient.Subunitatea
            LEFT JOIN TMP_TOPCLI_VALAGENT VALAGENT ON V.CodAgent = ValAgent.Agent and V.CodLocatie = ValAgent.CodLocatie and v.subunitatea = ValAgent.Subunitatea
            LEFT JOIN TMP_TOPCLI_VALAGENTART VALAGENTART ON V.CodAgent = ValAgentArt.Agent and V.CodLocatie = ValAgentArt.CodLocatie and v.subunitatea = ValAgentArt.Subunitatea and v.codobiect = ValAgentArt.codobiect
            LEFT JOIN NARTOBJ NAO ON NAO.CODOBIECT = V.CODOBIECT
            LEFT JOIN NCONT C ON V.CODCONT = C.CODCONT
            LEFT JOIN NART ART ON NAO.CodArticol = ART.CodArticol
            LEFT JOIN NCLASEA CLSA ON ART.Clasa = CLSA.CodClaseA
            LEFT JOIN NUM ON ART.UM = NUM.CODUM
            LEFT JOIN NPART P ON V.CodPart = P.CodPart
            LEFT JOIN NPARTCODFISC CF ON P.CodPart = CF.CodPart AND CF.Principal = 1
            LEFT JOIN NCLASEP CLSP ON P.CodClasa = CLSP.CodClaseP
            LEFT JOIN NAGENDA AG ON AG.CodPart = V.CodPart AND AG.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(AG.INACTIV, 0) = 0
            LEFT JOIN NPERS AGENT ON AG.CodAgent = AGENT.CodPers
            LEFT JOIN NLOCALIT LOC ON AG.CodLocalit = LOC.CodLOcalit
            LEFT JOIN NJUDET JUD ON LOC.CodJudet = JUD.CodJudet
            LEFT JOIN NAGENDA AGL ON AGL.CodAgenda = V.CodLocatie
            LEFT JOIN NLOCALIT LOCL ON AGL.CodLocalit = LOCL.CodLOcalit
            LEFT JOIN NJUDET JUDL ON LOCL.CodJudet = JUDL.CodJudet'||
            gSuplJoins||'
          WHERE V.CANT &lt;&gt; 0
          ';
        end if;
      end if;
    end if;
  else
    if vSediiL = 0 then
      if vOrder in (1,3) then
        if vAvize = 1 then
          sSelect :=
          'SELECT coalesce(NAO.Denumire, C.Den_Cont),
                 NUM.Den_UM DenUM,
                 V.Cant Cant,
                 V.Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret,
                 V.Val Valoare,
                 0 Pret_Val,
                 0 Valoare_Val,
                 ''Lei'' Valuta,
                 P.Den_Part,
                 ValClient.ValTot ValTot,
                 0 ValTot_Val,
                 ValAgent.ValTotAgent ValTotAgent,
                 0 ValTotAgent_Val,
                 case when coalesce(NAO.CodObiect, -1) &lt;&gt; -1 then
                 pkg_list_base_topclientiold_GetNrFact_Art(NAO.CodObiect, P.CodPart, 1,0)
                 else
                 pkg_list_base_topclientiold_GetNrFact_Art(C.CodCont, P.CodPart, -1,0)
                 end,
                 pkg_list_base_topclientiold_GetNrFact_Part(P.CodPart, 0),
                 coalesce(V.adaos, 0),
                 coalesce(v.adaos * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end), 0),
                 0,
                 0,
                 V.ValAchiz/(case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) PretAchiz, V.agent, '''',
                 coalesce(ValAgentArt.ValTotAgent,0),
                 0,
                 coalesce(ValAgentArt.Cant,0) '||gUserAlias||'
          FROM
              (
                SELECT S.CodPart,
                       S.CodObiect,
                       SUM(S.Cant) Cant,
                       SUM(S.Val) Val,
                       0 Val_Val,
                       null CodCont,
                       SUM(S.Adaos) adaos,
                       sum(coalesce(S.ValAchiz, 0)) valachiz,
                       S.Agent,
                       S.CodAgent
                FROM
                (
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) Adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (21, 26)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  SUM(Adaosuri.Adaos) Adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (21, 26)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1=ADAOSURI.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21 AND I1.TipLinie &lt;&gt; ''G''
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), ADAOSURI.adaos, AG.nume, AG.prenume, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  SUM(adaosuri.adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1=ADAOSURI.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21 AND I1.TipLinie &lt;&gt; ''G''
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), ADAOSURI.adaos, AG.nume, AG.prenume, AG.CODPERS
              ) S
                GROUP BY S.CodObiect, S.CodPart, S.Semn, S.agent, S.CodAgent
                UNION ALL
                SELECT S.CodPart,
                       null CodObiect,
                       SUM(S.Cant) Cant,
                       SUM(S.Val) Val,
                       0 Val_Val,
                       S.CodCont,
                       sum(s.adaos) adaos,
                       sum(coalesce(S.ValAchiz, 0)) valachiz,
                       S.Agent,
                       S.CodAgent
                FROM
                (
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact * coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT JOIN TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  sum(Adaosuri.Adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact * coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT JOIN TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)* coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  sum(adaosuri.adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)* coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume, AG.CODPERS
              ) S
                GROUP BY S.CodCOnt, S.CodPart, S.Semn, S.agent, S.CodAgent';
        if vWithEmul then
           sSelect := sSelect||'
              UNION ALL
              SELECT
                E.CodPart,
                E1.CodObiect,
                SUM(E1.Cant) Cant,
                SUM(E1.CANT * E1.PRET - E1.TVA) Val,
                0 Val_Val,
                0 CodCont,
                0 adaos,
                SUM(E1.CANT * E1.PRET - E1.TVA) valachiz,
                AG.NUME||'' ''||AG.PRENUME AGENT,
                E.CodAgent
              FROM EMULARE E
                   INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                   INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
                   LEFT JOIN NPERS AG ON AG.CODPERS = E.CODAGENT
              WHERE E.DATABON '||vCondData||'
                    AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                    AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
              GROUP BY E.CODPART, E1.CODOBIECT, E.CODAGENT, AG.NUME, AG.PRENUME  ';
         end if;
         sselect := sselect||'
              ) V
              LEFT JOIN TMP_TOPCLI_VALCLIENT VALCLIENT ON V.CodPart = ValClient.CodPart
              LEFT JOIN TMP_TOPCLI_VALAGENT VALAGENT ON V.CodAgent = ValAgent.Agent
              LEFT JOIN TMP_TOPCLI_VALAGENTART VALAGENTART ON V.CodAgent = ValAgentArt.Agent and V.CodObiect = ValAgentArt.COdObiect
              LEFT JOIN NARTOBJ NAO ON NAO.CODOBIECT = V.CODOBIECT
              LEFT JOIN NCONT C ON V.CODCONT = C.CODCONT
              LEFT JOIN NART ART ON NAO.CodArticol = ART.CodArticol
              LEFT JOIN NCLASEA CLSA ON ART.Clasa = CLSA.CodClaseA
              LEFT JOIN NUM ON ART.UM = NUM.CODUM
              LEFT JOIN NPART P ON V.CodPart = P.CodPart
              LEFT JOIN NPARTCODFISC CF ON P.CodPart = CF.CodPart AND CF.Principal = 1
              LEFT JOIN NCLASEP CLSP ON P.CodClasa = CLSP.CodClaseP
              LEFT JOIN NAGENDA AG ON AG.CodPart = V.CodPart AND AG.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(AG.INACTIV, 0) = 0
              LEFT JOIN NPERS AGENT ON AG.CodAgent = AGENT.CodPers
              LEFT JOIN NLOCALIT LOC ON AG.CodLocalit = LOC.CodLOcalit
              LEFT JOIN NJUDET JUD ON LOC.CodJudet = JUD.CodJudet
              LEFT JOIN NLOCALIT LOCL ON 0 = LOCL.CodLOcalit
              LEFT JOIN NJUDET JUDL ON LOCL.CodJudet = JUDL.CodJudet'||
              gSuplJoins||'
            WHERE V.CANT &lt;&gt; 0
            ';
        else
          sSelect :=
          'SELECT coalesce(NAO.Denumire, C.Den_Cont),
                 NUM.Den_UM DenUM,
                 V.Cant Cant,
                 V.Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret,
                 V.Val Valoare,
                 0 Pret_Val,
                 0 Valoare_Val,
                 ''Lei'' Valuta,
                 P.Den_Part,
                 ValClient.ValTot ValTot,
                 0 ValTot_Val,
                 ValAgent.ValTotAgent ValTotAgent,
                 0 ValTotAgent_Val,
                 case when coalesce(NAO.CodObiect, -1) &lt;&gt; -1 then
                 pkg_list_base_topclientiold_GetNrFact_Art(NAO.CodObiect, P.CodPart, 1, 0)
                 else
                 pkg_list_base_topclientiold_GetNrFact_Art(C.CodCont, P.CodPart, -1, 0)
                 end,
                 pkg_list_base_topclientiold_GetNrFact_Part(P.CodPart, 0),
                 coalesce(V.adaos, 0),
                 coalesce(v.adaos * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end), 0),
                 0,
                 0,
                 V.ValAchiz/(case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) PretAchiz,
                 V.Agent, '''',
                 coalesce(ValAgentArt.ValTotAgent,0),
                 0,
                 coalesce(ValAgentArt.Cant,0) '||gUserAlias||'
          FROM
              (
                SELECT S.CodPart,
                       S.CodObiect,
                       SUM(S.Cant) Cant,
                       SUM(S.Val) Val,
                       0 Val_Val,
                       null CodCont,
                       SUM(S.Adaos) adaos,
                       sum(coalesce(S.ValAchiz, 0)) valachiz,
                       S.agent,
                       S.CodAgent
                FROM
                (
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) Adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (21, 20)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  SUM(Adaosuri.Adaos) Adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (21, 20)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1=adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21 AND I1.TipLinie &lt;&gt; ''G''
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  SUM(adaosuri.adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1=adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21 AND I1.TipLinie &lt;&gt; ''G''
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume, AG.CODPERS
              ) S
                GROUP BY S.CodObiect, S.CodPart, S.Semn, S.agent, S.CodAgent
                UNION ALL
                SELECT S.CodPart,
                       null CodObiect,
                       SUM(S.Cant) Cant,
                       SUM(S.Val) Val,
                       0 Val_Val,
                       S.CodCont,
                       sum(s.adaos) adaos,
                       sum(coalesce(S.ValAchiz, 0)) valachiz,
                       S.agent,
                       S.CodAgent
                FROM
                (
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact * coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT JOIN TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  sum(Adaosuri.Adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact * coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     LEFT JOIN TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos,AG.nume, AG.prenume, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  sum(adaosuri.adaos) adaos,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos,AG.nume, AG.prenume, AG.CODPERS
              ) S
                GROUP BY S.CodCOnt, S.CodPart, S.Semn, S.Agent, S.CodAgent';
        if vWithEmul then
           sSelect := sSelect||'
              UNION ALL
              SELECT
                E.CodPart,
                E1.CodObiect,
                SUM(E1.Cant) Cant,
                SUM(E1.CANT * E1.PRET - E1.TVA) Val,
                0 Val_Val,
                0 CodCont,
                0 adaos,
                SUM(E1.CANT * E1.PRET - E1.TVA) valachiz,
                AG.NUME||'' ''||AG.PRENUME AGENT,
                E.CodAgent
              FROM EMULARE E
                   INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                   INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
                   LEFT JOIN NPERS AG ON AG.CODPERS = E.CODAGENT
              WHERE E.DATABON '||vCondData||'
                    AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                    AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
              GROUP BY E.CODPART, E1.CODOBIECT, E.CODAGENT, AG.NUME, AG.PRENUME  ';
         end if;
         sselect := sselect||'
              ) V
              LEFT JOIN TMP_TOPCLI_VALCLIENT VALCLIENT ON V.CodPart = ValClient.CodPart
              LEFT JOIN TMP_TOPCLI_VALAGENT VALAGENT ON V.CodAgent = ValAgent.Agent
              LEFT JOIN TMP_TOPCLI_VALAGENTART VALAGENTART ON V.CodAgent = ValAgentArt.Agent and V.CodObiect = ValAgentArt.CodObiect
              LEFT JOIN NARTOBJ NAO ON NAO.CODOBIECT = V.CODOBIECT
              LEFT JOIN NCONT C ON V.CODCONT = C.CODCONT
              LEFT JOIN NART ART ON NAO.CodArticol = ART.CodArticol
              LEFT JOIN NCLASEA CLSA ON ART.Clasa = CLSA.CodClaseA
              LEFT JOIN NUM ON ART.UM = NUM.CODUM
              LEFT JOIN NPART P ON V.CodPart = P.CodPart
              LEFT JOIN NPARTCODFISC CF ON P.CodPart = CF.CodPart AND CF.Principal = 1
              LEFT JOIN NCLASEP CLSP ON P.CodClasa = CLSP.CodClaseP
              LEFT JOIN NAGENDA AG ON AG.CodPart = V.CodPart AND AG.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(AG.INACTIV, 0) = 0
              LEFT JOIN NPERS AGENT ON AG.CodAgent = AGENT.CodPers
              LEFT JOIN NLOCALIT LOC ON AG.CodLocalit = LOC.CodLOcalit
              LEFT JOIN NJUDET JUD ON LOC.CodJudet = JUD.CodJudet
              LEFT JOIN NLOCALIT LOCL ON 0 = LOCL.CodLOcalit
              LEFT JOIN NJUDET JUDL ON LOCL.CodJudet = JUDL.CodJudet'||
              gSuplJoins||'
            WHERE V.CANT &lt;&gt; 0
            ';
        end if;
      else
        if vAvize = 1 then
          sSelect :=
          'SELECT coalesce(NAO.Denumire, C.Den_Cont),
                 NUM.Den_UM DenUM,
                 V.Cant Cant,
                 V.Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret,
                 V.Val Valoare,
                 V.Val_Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret_Val,
                 V.Val_Val Valoare_Val,
                 pkg_monede.get_simbol_moneda(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU())) Valuta,
                 P.Den_Part,
                 ValClient.ValTot ValTot,
                 ValClient.ValTot_Val ValTot_Val,
                 ValAgent.ValTotAgent ValTotAgent,
                 ValAgent.ValTotAgent_Val ValTotAgent_Val,
                 case when coalesce(NAO.CodObiect, -1) &lt;&gt; -1 then
                 pkg_list_base_topclientiold_GetNrFact_Art(NAO.CodObiect, P.CodPart, 1, 0)
                 else
                 pkg_list_base_topclientiold_GetNrFact_Art(C.CodCont, P.CodPart, -1, 0)
                 end,
                 pkg_list_base_topclientiold_GetNrFact_Part(P.CodPart, 0),
                 coalesce(v.adaos, 0),
                 coalesce(v.adaos * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end), 0),
                 V.adaos_val,
                 v.adaos_val * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end),
                 V.ValAchiz/(case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) PretAchiz,
                 V.Agent, '''',
                 coalesce(ValAgentArt.ValTotAgent,0),
                 coalesce(ValAgentArt.ValTotAgent_Val,0),
                 coalesce(ValAgentArt.Cant,0) '||gUserAlias||'
          FROM
              (
                SELECT S.CodPart,
                       S.CodObiect,
                       SUM(S.Cant) Cant,
                       SUM(S.Val) Val,
                       SUM(S.Val_Val) Val_Val,
                       null CodCont,
                       SUM(S.Adaos) adaos,
                       SUM(S.Adaos_Val) adaos_val,
                       SUM(coalesce(S.ValAchiz, 0)) ValAchiz,
                       S.Agent,
                       S.CodAgent
                FROM
                (
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  sum(l1.cant/i1.cant*adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(adaosuri.adaos) adaos,
                  sum(adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  sum(l1.cant/i1.cant*adaosuri.adaos /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.PU - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(adaosuri.adaos) adaos,
                  sum(adaosuri.adaos /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.PU - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, AG.CODPERS
              ) S
                GROUP BY S.CodObiect, S.CodPart, S.Semn, S.agent, S.CodAgent
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  sum(l1.cant/i1.cant*adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(adaosuri.adaos) adaos,
                  sum(adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (26, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0 '||sCust||'
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, AG.CODPERS
                UNION ALL
                SELECT S.CodPart,
                       null CodObiect,
                       SUM(S.Cant) Cant,
                       SUM(S.Val) Val,
                       SUM(S.Val_Val) Val_Val,
                       S.CodCont,
                       SUM(S.Adaos) adaos,
                       SUM(S.Adaos_val) adaos_val,
                       SUM(coalesce(S.ValAchiz, 0)) ValAchiz,
                       S.Agent,
                       S.CodAgent
                FROM
                (
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  sum(l1.cant/i1.cant*adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, AG.CODPERS
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(adaosuri.adaos) adaos,
                  sum(adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CODPERS CODAGENT
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, AG.CODPERS
              ) S
                GROUP BY S.CodCont, S.CodPart, S.Semn, S.agent, S.CodAgent';
        if vWithEmul then
           sSelect := sSelect||'
              UNION ALL
              SELECT
                E.CodPart,
                E1.CodObiect,
                SUM(E1.Cant) Cant,
                SUM(E1.CANT * E1.PRET - E1.TVA) Val,
                0 Val_Val,
                0 CodCont,
                0 adaos,
                SUM(E1.CANT * E1.PRET - E1.TVA) valachiz,
                AG.NUME||'' ''||AG.PRENUME AGENT,
                E.CodAgent
              FROM EMULARE E
                   INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                   INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
                   LEFT JOIN NPERS AG ON AG.CODPERS = E.CODAGENT
              WHERE E.DATABON '||vCondData||'
                    AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                    AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
              GROUP BY E.CODPART, E1.CODOBIECT, E.CODAGENT, AG.NUME, AG.PRENUME  ';
         end if;
         sselect := sselect||'
              ) V
              LEFT JOIN TMP_TOPCLI_VALCLIENT VALCLIENT ON V.CodPart = ValClient.CodPart
              LEFT JOIN TMP_TOPCLI_VALAGENT VALAGENT ON V.CodAgent = ValAgent.Agent
              LEFT JOIN TMP_TOPCLI_VALAGENTART VALAGENTART ON V.CodAgent = ValAgentArt.Agent and V.CodObiect = ValAgentArt.CodObiect
              LEFT JOIN NARTOBJ NAO ON NAO.CODOBIECT = V.CODOBIECT
              LEFT JOIN NCONT C ON V.CODCONT = C.CODCONT
              LEFT JOIN NART ART ON NAO.CodArticol = ART.CodArticol
              LEFT JOIN NCLASEA CLSA ON ART.Clasa = CLSA.CodClaseA
              LEFT JOIN NUM ON ART.UM = NUM.CODUM
              LEFT JOIN NPART P ON V.CodPart = P.CodPart
              LEFT JOIN NPARTCODFISC CF ON P.CodPart = CF.CodPart AND CF.Principal = 1
              LEFT JOIN NCLASEP CLSP ON P.CodClasa = CLSP.CodClaseP
              LEFT JOIN NAGENDA AG ON AG.CodPart = V.CodPart AND AG.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(AG.INACTIV, 0) = 0
              LEFT JOIN NPERS AGENT ON AG.CodAgent = AGENT.CodPers
              LEFT JOIN NLOCALIT LOC ON AG.CodLocalit = LOC.CodLOcalit
              LEFT JOIN NJUDET JUD ON LOC.CodJudet = JUD.CodJudet
              LEFT JOIN NLOCALIT LOCL ON 0 = LOCL.CodLOcalit
              LEFT JOIN NJUDET JUDL ON LOCL.CodJudet = JUDL.CodJudet'||
              gSuplJoins||'
            WHERE V.CANT &lt;&gt; 0
            ';
        else
          sSelect :=
          'SELECT coalesce(NAO.Denumire, C.Den_Cont),
                 NUM.Den_UM DenUM,
                 V.Cant Cant,
                 V.Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret,
                 V.Val Valoare,
                 V.Val_Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret_Val,
                 V.Val_Val Valoare_Val,
                 pkg_monede.get_simbol_moneda(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU())) Valuta,
                 P.Den_Part,
                 ValClient.ValTot ValTot,
                 ValClient.ValTot_Val ValTot_Val,
                 ValAgent.ValTotAgent ValTotAgent,
                 ValAgent.ValTotAgent_Val ValTotAgent_Val,
                 case when coalesce(NAO.CodObiect, -1) &lt;&gt; -1 then
                 pkg_list_base_topclientiold_GetNrFact_Art(NAO.CodObiect, P.CodPart, 1, 0)
                 else
                 pkg_list_base_topclientiold_GetNrFact_Art(C.CodCont, P.CodPart, -1, 0)
                 end,
                 pkg_list_base_topclientiold_GetNrFact_Part(P.CodPart, 0),
                 coalesce(v.adaos, 0),
                 coalesce(v.adaos * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end), 0),
                 V.adaos_val,
                 v.adaos_val * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end),
                 V.ValAchiz/(case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) PretAchiz, V.agent, '''',
                 coalesce(ValAgentArt.ValTotAgent,0),
                 coalesce(ValAgentArt.ValTotAgent_Val,0),
                 coalesce(ValAgentArt.Cant,0) '||gUserAlias||'
          FROM
              (
                SELECT S.CodPart,
                       S.CodObiect,
                       SUM(S.Cant) Cant,
                       SUM(S.Val) Val,
                       SUM(S.Val_Val) Val_Val,
                       null CodCont,
                       SUM(S.Adaos) adaos,
                       SUM(S.Adaos_Val) adaos_val,
                       SUM(coalesce(S.ValAchiz, 0)) ValAchiz,
                       S.agent,
                       S.CodAgent
                FROM
                (
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  sum(l1.cant/i1.cant*adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.PU * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz ,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CodPers CodAgent
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, AG.CodPers
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(adaosuri.adaos) adaos,
                  sum(adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.PU * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz ,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CodPers CodAgent
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, AG.CodPers
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  sum(l1.cant/i1.cant*adaosuri.adaos /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy'')c)) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.PU - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CodPers CodAgent
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, AG.CodPers
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.CodObiect,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(adaosuri.adaos) adaos,
                  sum(adaosuri.adaos /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.PU - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CodPers CodAgent
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, AG.CodPers
              ) S
                GROUP BY S.CodObiect, S.CodPart, S.Semn, S.Agent, S.CodAgent
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  sum(l1.cant/i1.cant*adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  Ag.nume||'' ''||AG.prenume agent,
                  AG.CodPers CodAgent
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, AG.CodPers
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                  SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(adaosuri.adaos) adaos,
                  sum(adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  Ag.nume||'' ''||AG.prenume agent,
                  AG.CodPers CodAgent
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc NOT IN (20, 21)
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, AG.CodPers
                UNION ALL
                SELECT S.CodPart,
                       null CodObiect,
                       SUM(S.Cant) Cant,
                       SUM(S.Val) Val,
                       SUM(S.Val_Val) Val_Val,
                       S.CodCont,
                       SUM(S.Adaos) adaos,
                       SUM(S.Adaos_val) adaos_val,
                       SUM(coalesce(S.ValAchiz, 0)) ValAchiz,
                       S.agent,
                       S.CodAgent
                FROM
                (
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                  sum(l1.cant/i1.cant*adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CodPers CodAgent
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                     INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                     LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                     LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
                AND I.Operat = 1
                AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, AG.CodPers
                UNION ALL
                SELECT
                  Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                  I.Partener CodPart,
                  I1.ContDiscount CodCont,
                  SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                  SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                  sum(adaosuri.adaos) adaos,
                  sum(adaosuri.adaos/
                  PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                  SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                  AG.nume||'' ''||AG.prenume agent,
                  AG.CodPers CodAgent
                FROM IESIRI I
                     INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                     INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                     INNER JOIN NPART P ON I.PARTENER = P.CODPART
                     left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                     LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                WHERE I.DATADOC '||vCondData||
                PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
                AND I.TipDoc = 21
                AND coalesce(I.Anulat, 0) = 0
                AND coalesce(I.Initializari, 0) = 0
                AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
                AND I.Operat = 1
                AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
                GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
                AG.nume, AG.prenume, AG.CodPers
              ) S
                GROUP BY S.CodCont, S.CodPart, S.Semn, S.agent, S.CodAgent';
        if vWithEmul then
           sSelect := sSelect||'
              UNION ALL
              SELECT
                E.CodPart,
                E1.CodObiect,
                SUM(E1.Cant) Cant,
                SUM(E1.CANT * E1.PRET - E1.TVA) Val,
                0 Val_Val,
                0 CodCont,
                0 adaos,
                SUM(E1.CANT * E1.PRET - E1.TVA) valachiz,
                AG.NUME||'' ''||AG.PRENUME AGENT,
                E.CodAgent
              FROM EMULARE E
                   INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                   INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
                   LEFT JOIN NPERS AG ON AG.CODPERS = E.CODAGENT
              WHERE E.DATABON '||vCondData||'
                    AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                    AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
              GROUP BY E.CODPART, E1.CODOBIECT, E.CODAGENT, AG.NUME, AG.PRENUME  ';
        end if;
        sSelect := sSelect||'
              ) V
              LEFT JOIN TMP_TOPCLI_VALCLIENT VALCLIENT ON V.CodPart = ValClient.CodPart
              LEFT JOIN TMP_TOPCLI_VALAGENT VALAGENT ON V.CodAgent = ValAgent.Agent
              LEFT JOIN TMP_TOPCLI_VALAGENTART VALAGENTART ON V.CodAgent = ValAgentArt.Agent and V.CodObiect = ValAgentArt.CodObiect
              LEFT JOIN NARTOBJ NAO ON NAO.CODOBIECT = V.CODOBIECT
              LEFT JOIN NCONT C ON V.CODCONT = C.CODCONT
              LEFT JOIN NART ART ON NAO.CodArticol = ART.CodArticol
              LEFT JOIN NCLASEA CLSA ON ART.Clasa = CLSA.CodClaseA
              LEFT JOIN NUM ON ART.UM = NUM.CODUM
              LEFT JOIN NPART P ON V.CodPart = P.CodPart
              LEFT JOIN NPARTCODFISC CF ON P.CodPart = CF.CodPart AND CF.Principal = 1
              LEFT JOIN NCLASEP CLSP ON P.CodClasa = CLSP.CodClaseP
              LEFT JOIN NAGENDA AG ON AG.CodPart = V.CodPart AND AG.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(AG.INACTIV, 0) = 0
              LEFT JOIN NPERS AGENT ON AG.CodAgent = AGENT.CodPers
              LEFT JOIN NLOCALIT LOC ON AG.CodLocalit = LOC.CodLOcalit
              LEFT JOIN NJUDET JUD ON LOC.CodJudet = JUD.CodJudet
              LEFT JOIN NLOCALIT LOCL ON 0 = LOCL.CodLOcalit
              LEFT JOIN NJUDET JUDL ON LOCL.CodJudet = JUDL.CodJudet'||
              gSuplJoins||'
            WHERE V.CANT &lt;&gt; 0
            ';
        end if;
      end if;
    else
      if vOrder in (1,3) then
      if vAvize = 1 then
        sSelect :=
        'SELECT coalesce(NAO.Denumire, C.Den_Cont),
               NUM.Den_UM DenUM,
               V.Cant Cant,
               V.Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret,
               V.Val Valoare,
               0 Pret_Val,
               0 Valoare_Val,
               ''Lei'' Valuta,
               P.Den_Part,
               ValClient.ValTot ValTot,
               0 ValTot_Val,
               ValAgent.ValTotAgent ValTotAgent,
               0 ValTotAgent_Val,
               case when coalesce(NAO.CodObiect, -1) &lt;&gt; -1 then
               pkg_list_base_topclientiold_GetNrFact_Art(NAO.CodObiect, P.CodPart, 1, V.CodLocatie)
               else
               pkg_list_base_topclientiold_GetNrFact_Art(C.CodCont, P.CodPart, -1, V.CodLocatie)
               end,
               pkg_list_base_topclientiold_GetNrFact_Part(P.CodPart, V.CodLocatie),
               coalesce(V.adaos, 0),
               coalesce(v.adaos * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end), 0),
               0,
               0,
               V.ValAchiz/(case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) PretAchiz, V.agent,
               AGL.Obs,
               coalesce(ValAgentArt.ValTotAgent,0),
               0,
               coalesce(ValAgentArt.Cant,0) '||gUserAlias||'
        FROM
            (
              SELECT S.CodPart,
                     S.CodObiect,
                     SUM(S.Cant) Cant,
                     SUM(S.Val) Val,
                     0 Val_Val,
                     null CodCont,
                     SUM(S.Adaos) adaos,
                     sum(coalesce(S.ValAchiz, 0)) valachiz,
                     S.Agent,
                     S.CodAgent,
                     S.CodLocatie
              FROM
              (
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) Adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (21, 26)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0 '||sCust||'
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                sum(adaosuri.adaos) Adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (21, 26)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0 '||sCust||'
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1=adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                   LEFT JOIN NAGENDA AGL ON AGL.CodAgenda = I.CodLocatie
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21 AND I1.TipLinie &lt;&gt; ''G''
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                SUM(adaosuri.adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1=adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                   LEFT JOIN NAGENDA AGL ON AGL.CodAgenda = I.CodLocatie
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21 AND I1.TipLinie &lt;&gt; ''G''
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, AG.CodPers
            ) S
              GROUP BY S.CodObiect, S.CodPart, S.Semn, S.agent,S.CodLocatie, S.CodAgent
              UNION ALL
              SELECT S.CodPart,
                     null CodObiect,
                     SUM(S.Cant) Cant,
                     SUM(S.Val) Val,
                     0 Val_Val,
                     S.CodCont,
                     sum(s.adaos) adaos,
                     sum(coalesce(S.ValAchiz, 0)) valachiz,
                     S.Agent,
                     S.CodAgent,
                     S.CodLocatie
              FROM
              (
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact * coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT JOIN TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (26, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0 '||sCust||'
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                sum(Adaosuri.Adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact * coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   LEFT JOIN TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (26, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0 '||sCust||'
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)* coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                sum(adaosuri.adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)* coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, AG.CodPers
            ) S
              GROUP BY S.CodCOnt, S.CodPart, S.Semn, S.agent, S.CodLocatie, S.CodAgent';
        if vWithEmul then
           sSelect := sSelect||'
            UNION ALL
              SELECT
                E.CodPart,
                E1.CodObiect,
                SUM(E1.Cant) Cant,
                SUM(E1.CANT * E1.PRET - E1.TVA) Val,
                0 Val_Val,
                0 CodCont,
                0 adaos,
                SUM(E1.CANT * E1.PRET - E1.TVA) valachiz,
                AG.NUME||'' ''||AG.PRENUME AGENT,
                E.CodAgent,
                E.CodLocatie
              FROM EMULARE E
                   INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                   INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
                   LEFT JOIN NPERS AG ON AG.CODPERS = E.CODAGENT
              WHERE E.DATABON '||vCondData||'
                    AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                    AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
              GROUP BY E.CODPART, E1.CODOBIECT, E.CODAGENT, E.CODLOCATIE, AG.NUME, AG.PRENUME ';
        END IF;
        sSelect := sSelect||'
            ) V
            LEFT JOIN TMP_TOPCLI_VALCLIENT VALCLIENT ON V.CodPart = ValClient.CodPart and V.CodLocatie = ValClient.CodLocatie
            LEFT JOIN TMP_TOPCLI_VALAGENT VALAGENT ON V.CodAgent = ValAgent.Agent and V.CodLocatie = ValAgent.CodLocatie
            LEFT JOIN TMP_TOPCLI_VALAGENTART VALAGENTART ON V.CodAgent = ValAgentArt.Agent and V.CodLocatie = ValAgentArt.CodLocatie and V.CodObiect = ValAgentArt.CodObiect
            LEFT JOIN NARTOBJ NAO ON NAO.CODOBIECT = V.CODOBIECT
            LEFT JOIN NCONT C ON V.CODCONT = C.CODCONT
            LEFT JOIN NART ART ON NAO.CodArticol = ART.CodArticol
            LEFT JOIN NCLASEA CLSA ON ART.Clasa = CLSA.CodClaseA
            LEFT JOIN NUM ON ART.UM = NUM.CODUM
            LEFT JOIN NPART P ON V.CodPart = P.CodPart
            LEFT JOIN NPARTCODFISC CF ON P.CodPart = CF.CodPart AND CF.Principal = 1
            LEFT JOIN NCLASEP CLSP ON P.CodClasa = CLSP.CodClaseP
            LEFT JOIN NAGENDA AG ON AG.CodPart = V.CodPart AND AG.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(AG.INACTIV, 0) = 0
            LEFT JOIN NPERS AGENT ON AG.CodAgent = AGENT.CodPers
            LEFT JOIN NLOCALIT LOC ON AG.CodLocalit = LOC.CodLOcalit
            LEFT JOIN NJUDET JUD ON LOC.CodJudet = JUD.CodJudet
            LEFT JOIN NAGENDA AGL ON AGL.CodAgenda = V.CodLocatie
            LEFT JOIN NLOCALIT LOCL ON AGL.CodLocalit = LOCL.CodLOcalit
            LEFT JOIN NJUDET JUDL ON LOCL.CodJudet = JUDL.CodJudet'||
            gSuplJoins||'
          WHERE V.CANT &lt;&gt; 0
          ';
      else
        sSelect :=
        'SELECT coalesce(NAO.Denumire, C.Den_Cont),
               NUM.Den_UM DenUM,
               V.Cant Cant,
               V.Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret,
               V.Val Valoare,
               0 Pret_Val,
               0 Valoare_Val,
               ''Lei'' Valuta,
               P.Den_Part,
               ValClient.ValTot ValTot,
               0 ValTot_Val,
               ValAgent.ValTotAgent ValTotAgent,
               0 ValTotAgent_Val,
               case when coalesce(NAO.CodObiect, -1) &lt;&gt; -1 then
               pkg_list_base_topclientiold_GetNrFact_Art(NAO.CodObiect, P.CodPart, 1, V.CodLocatie)
               else
               pkg_list_base_topclientiold_GetNrFact_Art(C.CodCont, P.CodPart, -1, V.CodLocatie)
               end,
               pkg_list_base_topclientiold_GetNrFact_Part(P.CodPart, V.CodLocatie),
               coalesce(V.adaos, 0),
               coalesce(v.adaos * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end), 0),
               0,
               0,
               V.ValAchiz/(case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) PretAchiz,
               V.Agent,
               AGL.Obs,
               coalesce(ValAgentArt.ValTotAgent,0),
               0,
               coalesce(ValAgentArt.Cant,0) '||gUserAlias||'
        FROM
            (
              SELECT S.CodPart,
                     S.CodObiect,
                     SUM(S.Cant) Cant,
                     SUM(S.Val) Val,
                     0 Val_Val,
                     null CodCont,
                     SUM(S.Adaos) adaos,
                     sum(coalesce(S.ValAchiz, 0)) valachiz,
                     S.agent,
                     S.CodAgent,
                     S.CodLocatie
              FROM
              (
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) Adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                SUM(Adaosuri.Adaos) Adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   LEFT  JOIN TMP_TOPCLI_ADAOSURI ADAOSURI ON i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (21, 20)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1=adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21 AND I1.TipLinie &lt;&gt; ''G''
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                SUM(adaosuri.adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1=adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21 AND I1.TipLinie &lt;&gt; ''G''
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, AG.CodPers
            ) S
              GROUP BY S.CodObiect, S.CodPart, S.Semn, S.agent, S.CodLocatie, S.CodAgent
            UNION ALL
              SELECT S.CodPart,
                     null CodObiect,
                     SUM(S.Cant) Cant,
                     SUM(S.Val) Val,
                     0 Val_Val,
                     S.CodCont,
                     sum(s.adaos) adaos,
                     sum(coalesce(S.ValAchiz, 0)) valachiz,
                     S.agent,
                     S.CodAgent,
                     S.CodLocatie
              FROM
              (
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact * coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   LEFT JOIN TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (20, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                sum(Adaosuri.Adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact * coalesce(I1.COEFDISCMAJ,1)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   LEFT JOIN TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (20, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, AG.nume, AG.prenume,
                       I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos,AG.nume, AG.prenume,
                       I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                sum(adaosuri.adaos) adaos,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CONTDISCOUNT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos,AG.nume, AG.prenume,
                       I.CodLocatie, AG.CodPers
            ) S
              GROUP BY S.CodCOnt, S.CodPart, S.Semn, S.Agent, S.CodLocatie, S.CodAgent';
        if vWithEmul then
           sSelect := sSelect||'
            UNION ALL
            SELECT
              E.CodPart,
              E1.CodObiect,
              SUM(E1.Cant) Cant,
              SUM(E1.CANT * E1.PRET - E1.TVA) Val,
              0 Val_Val,
              0 CodCont,
              0 adaos,
              SUM(E1.CANT * E1.PRET - E1.TVA) valachiz,
              AG.NUME||'' ''||AG.PRENUME AGENT,
              E.CodAgent,
              E.CodLocatie
            FROM EMULARE E
                 INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                 INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
                 LEFT JOIN NPERS AG ON AG.CODPERS = E.CODAGENT
            WHERE E.DATABON '||vCondData||'
                  AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                  AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
            GROUP BY E.CODPART, E1.CODOBIECT, E.CODAGENT, E.CODLOCATIE, AG.NUME, AG.PRENUME';
        END IF;
           sSelect := sSelect||'
            ) V
            LEFT JOIN TMP_TOPCLI_VALCLIENT VALCLIENT ON V.CodPart = ValClient.CodPart and V.CodLocatie = ValClient.CodLocatie
            LEFT JOIN TMP_TOPCLI_VALAGENT VALAGENT ON V.CodAgent = ValAgent.Agent and V.CodLocatie = ValAgent.CodLocatie
            LEFT JOIN TMP_TOPCLI_VALAGENTART VALAGENTART ON V.CodAgent = ValAgentArt.Agent and V.CodLocatie = ValAgentArt.CodLocatie and V.CodObiect = ValAgentArt.CodObiect
            LEFT JOIN NARTOBJ NAO ON NAO.CODOBIECT = V.CODOBIECT
            LEFT JOIN NCONT C ON V.CODCONT = C.CODCONT
            LEFT JOIN NART ART ON NAO.CodArticol = ART.CodArticol
            LEFT JOIN NCLASEA CLSA ON ART.Clasa = CLSA.CodClaseA
            LEFT JOIN NUM ON ART.UM = NUM.CODUM
            LEFT JOIN NPART P ON V.CodPart = P.CodPart
            LEFT JOIN NPARTCODFISC CF ON P.CodPart = CF.CodPart AND CF.Principal = 1
            LEFT JOIN NCLASEP CLSP ON P.CodClasa = CLSP.CodClaseP
            LEFT JOIN NAGENDA AG ON AG.CodPart = V.CodPart AND AG.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(AG.INACTIV, 0) = 0
            LEFT JOIN NPERS AGENT ON AG.CodAgent = AGENT.CodPers
            LEFT JOIN NLOCALIT LOC ON AG.CodLocalit = LOC.CodLOcalit
            LEFT JOIN NJUDET JUD ON LOC.CodJudet = JUD.CodJudet
            LEFT JOIN NAGENDA AGL ON AGL.CodAgenda = V.CodLocatie
            LEFT JOIN NLOCALIT LOCL ON AGL.CodLocalit = LOCL.CodLOcalit
            LEFT JOIN NJUDET JUDL ON LOCL.CodJudet = JUDL.CodJudet'||
            gSuplJoins||'
          WHERE V.CANT &lt;&gt; 0
          ';
      end if;
    else
      if vAvize = 1 then
        sSelect :=
        'SELECT coalesce(NAO.Denumire, C.Den_Cont),
               NUM.Den_UM DenUM,
               V.Cant Cant,
               V.Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret,
               V.Val Valoare,
               V.Val_Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret_Val,
               V.Val_Val Valoare_Val,
               pkg_monede.get_simbol_moneda(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU())) Valuta,
               P.Den_Part,
               ValClient.ValTot ValTot,
               ValClient.ValTot_Val ValTot_Val,
               ValAgent.ValTotAgent ValTotAgent,
               ValAgent.ValTotAgent_Val ValTotAgent_Val,
               case when coalesce(NAO.CodObiect, -1) &lt;&gt; -1 then
               pkg_list_base_topclientiold_GetNrFact_Art(NAO.CodObiect, P.CodPart, 1, V.CodLocatie)
               else
               pkg_list_base_topclientiold_GetNrFact_Art(C.CodCont, P.CodPart, -1, V.CodLocatie)
               end,
               pkg_list_base_topclientiold_GetNrFact_Part(P.CodPart, V.CodLocatie),
               coalesce(v.adaos, 0),
               coalesce(v.adaos * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end), 0),
               V.adaos_val,
               v.adaos_val * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end),
               V.ValAchiz/(case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) PretAchiz,
               V.Agent,
               AGL.Obs,
               coalesce(ValAgentArt.ValTotAgent,0),
               coalesce(ValAgentArt.ValTotAgent_Val,0),
               coalesce(ValAgentArt.Cant,0) '||gUserAlias||'
        FROM
            (
              SELECT S.CodPart,
                     S.CodObiect,
                     SUM(S.Cant) Cant,
                     SUM(S.Val) Val,
                     SUM(S.Val_Val) Val_Val,
                     null CodCont,
                     SUM(S.Adaos) adaos,
                     SUM(S.Adaos_Val) adaos_val,
                     SUM(coalesce(S.ValAchiz, 0)) ValAchiz,
                     S.Agent,
                     S.CodAgent,
                     S.CodLocatie
              FROM
              (
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                sum(l1.cant/i1.cant*adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                coalesce(I.CodLocatie,0) CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (26, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0 '||sCust||'
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(adaosuri.adaos) adaos,
                sum(adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                coalesce(I.CodLocatie,0) CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (26, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0 '||sCust||'
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                sum(l1.cant/i1.cant*adaosuri.adaos /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.PU - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                coalesce(I.CodLocatie,0) CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(adaosuri.adaos) adaos,
                sum(adaosuri.adaos /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.PU - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                coalesce(I.CodLocatie,0) CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, AG.CodPers
            ) S
              GROUP BY S.CodObiect, S.CodPart, S.Semn, S.agent, S.CodLocatie, S.CodAgent
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                sum(l1.cant/i1.cant*adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                coalesce(I.CodLocatie,0) CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (26, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0 '||sCust||'
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(adaosuri.adaos) adaos,
                sum(adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                coalesce(I.CodLocatie,0) CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (26, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0 '||sCust||'
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT S.CodPart,
                     null CodObiect,
                     SUM(S.Cant) Cant,
                     SUM(S.Val) Val,
                     SUM(S.Val_Val) Val_Val,
                     S.CodCont,
                     SUM(S.Adaos) adaos,
                     SUM(S.Adaos_val) adaos_val,
                     SUM(coalesce(S.ValAchiz, 0)) ValAchiz,
                     S.Agent,
                     S.CodAgent,
                     S.CodLocatie
              FROM
              (
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                sum(l1.cant/i1.cant*adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                coalesce(I.CodLocatie,0) CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(adaosuri.adaos) adaos,
                sum(adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                coalesce(I.CodLocatie,0) CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, AG.CodPers
            ) S
              GROUP BY S.CodCont, S.CodPart, S.Semn, S.agent, S.CodLocatie, S.CodAgent';
        if vWithEmul then
           sSelect := sSelect||'
            UNION ALL
              SELECT
                E.CodPart,
                E1.CodObiect,
                SUM(E1.Cant) Cant,
                SUM(E1.CANT * E1.PRET - E1.TVA) Val,
                0 Val_Val,
                0 CodCont,
                0 adaos,
                SUM(E1.CANT * E1.PRET - E1.TVA) valachiz,
                AG.NUME||'' ''||AG.PRENUME AGENT,
                E.CodAgent,
                E.CodLocatie
              FROM EMULARE E
                   INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                   INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
                   LEFT JOIN NPERS AG ON AG.CODPERS = E.CODAGENT
              WHERE E.DATABON '||vCondData||'
                    AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                    AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
              GROUP BY E.CODPART, E1.CODOBIECT, E.CODAGENT, E.CODLOCATIE, AG.NUME, AG.PRENUME  ';
        END IF;
           sSelect := sSelect||'
            ) V
            LEFT JOIN TMP_TOPCLI_VALCLIENT VALCLIENT ON V.CodPart = ValClient.CodPart and V.CodLocatie = ValClient.CodLocatie
            LEFT JOIN TMP_TOPCLI_VALAGENT VALAGENT ON V.CodAgent = ValAgent.Agent and V.CodLocatie = ValAgent.CodLocatie
            LEFT JOIN TMP_TOPCLI_VALAGENTART VALAGENTART ON V.CodAgent = ValAgentArt.Agent and V.CodLocatie = ValAgentArt.CodLocatie and V.CodObiect = ValAgentArt.CodObiect
            LEFT JOIN NARTOBJ NAO ON NAO.CODOBIECT = V.CODOBIECT
            LEFT JOIN NCONT C ON V.CODCONT = C.CODCONT
            LEFT JOIN NART ART ON NAO.CodArticol = ART.CodArticol
            LEFT JOIN NCLASEA CLSA ON ART.Clasa = CLSA.CodClaseA
            LEFT JOIN NUM ON ART.UM = NUM.CODUM
            LEFT JOIN NPART P ON V.CodPart = P.CodPart
            LEFT JOIN NPARTCODFISC CF ON P.CodPart = CF.CodPart AND CF.Principal = 1
            LEFT JOIN NCLASEP CLSP ON P.CodClasa = CLSP.CodClaseP
            LEFT JOIN NAGENDA AG ON AG.CodPart = V.CodPart AND AG.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(AG.INACTIV, 0) = 0
            LEFT JOIN NPERS AGENT ON AG.CodAgent = AGENT.CodPers
            LEFT JOIN NLOCALIT LOC ON AG.CodLocalit = LOC.CodLOcalit
            LEFT JOIN NJUDET JUD ON LOC.CodJudet = JUD.CodJudet
            LEFT JOIN NAGENDA AGL ON AGL.CodAgenda = V.CodLocatie
            LEFT JOIN NLOCALIT LOCL ON AGL.CodLocalit = LOCL.CodLOcalit
            LEFT JOIN NJUDET JUDL ON LOCL.CodJudet = JUDL.CodJudet'||
            gSuplJoins||'
          WHERE V.CANT &lt;&gt; 0
          ';
      else
        sSelect :=
        'SELECT coalesce(NAO.Denumire, C.Den_Cont),
               NUM.Den_UM DenUM,
               V.Cant Cant,
               V.Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret,
               V.Val Valoare,
               V.Val_Val / (case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) Pret_Val,
               V.Val_Val Valoare_Val,
               pkg_monede.get_simbol_moneda(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU())) Valuta,
               P.Den_Part,
               ValClient.ValTot ValTot,
               ValClient.ValTot_Val ValTot_Val,
               ValAgent.ValTotAgent ValTotAgent,
               ValAgent.ValTotAgent_Val ValTotAgent_Val,
               case when coalesce(NAO.CodObiect, -1) &lt;&gt; -1 then
               pkg_list_base_topclientiold_GetNrFact_Art(NAO.CodObiect, P.CodPart, 1, V.CodLocatie)
               else
               pkg_list_base_topclientiold_GetNrFact_Art(C.CodCont, P.CodPart, -1, V.CodLocatie)
               end,
               pkg_list_base_topclientiold_GetNrFact_Part(P.CodPart, V.CodLocatie),
               coalesce(v.adaos, 0),
               coalesce(v.adaos * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end), 0),
               V.adaos_val,
               v.adaos_val * 100 / (case when coalesce(v.valachiz, 0)= 0 then  1 else  v.valachiz end),
               V.ValAchiz/(case when coalesce(V.Cant, 0)= 0 then  1 else  V.Cant end) PretAchiz, V.agent,
               AGL.Obs,
               coalesce(ValAgentArt.ValTotAgent,0),
               coalesce(ValAgentArt.ValTotAgent_Val,0),
               coalesce(ValAgentArt.Cant,0) '||gUserAlias||'
        FROM
            (
              SELECT S.CodPart,
                     S.CodObiect,
                     SUM(S.Cant) Cant,
                     SUM(S.Val) Val,
                     SUM(S.Val_Val) Val_Val,
                     null CodCont,
                     SUM(S.Adaos) adaos,
                     SUM(S.Adaos_Val) adaos_val,
                     SUM(coalesce(S.ValAchiz, 0)) ValAchiz,
                     S.agent,
                     S.CodAgent,
                     S.CodLocatie
              FROM
              (
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                sum(l1.cant/i1.cant*adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.PU * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz ,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (20, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                SUM((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(adaosuri.adaos) adaos,
                sum(adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.PU * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz ,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (20, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                sum(l1.cant/i1.cant*adaosuri.adaos /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.PU - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end) END)) * (case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.CodObiect,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                SUM(((i1.pu/(case when 1+coalesce(i1.addim/100,0)= 0 then  1 else  1+coalesce(i1.addim/100,0) end) * coalesce(i1.coefdiscmaj,1) - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(adaosuri.adaos) adaos,
                sum(adaosuri.adaos /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.PU - I1.TVA/(CASE WHEN coalesce((case when i1.tiplinie=''S'' then I1.cant else I1.CANT), 0)= 0 THEN  1 ELSE (case when i1.tiplinie=''S'' then I1.cant else I1.CANT) END)) * (case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NARTOBJ OBJ ON I1.Codobiect = OBJ.CodObiect
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.CODOBIECT, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, AG.CodPers
            ) S
              GROUP BY S.CodObiect, S.CodPart, S.Semn, S.Agent, S.CodLocatie, S.CodAgent
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Cant,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                sum(l1.cant/i1.cant*adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                Ag.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (20, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Cant,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) Val,
                SUM((I1.RestFact) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(adaosuri.adaos) adaos,
                sum(adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then (I1.RestFact) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                Ag.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc NOT IN (20, 21)
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT S.CodPart,
                     null CodObiect,
                     SUM(S.Cant) Cant,
                     SUM(S.Val) Val,
                     SUM(S.Val_Val) Val_Val,
                     S.CodCont,
                     SUM(S.Adaos) adaos,
                     SUM(S.Adaos_val) adaos_val,
                     SUM(coalesce(S.ValAchiz, 0)) ValAchiz,
                     S.agent,
                     S.CodAgent,
                     S.CodLocatie
              FROM
              (
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)) CANT,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(l1.cant/i1.cant*adaosuri.adaos) adaos,
                sum(l1.cant/i1.cant*adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   INNER JOIN LIVR1 L1 ON I1.CodIes1 = L1.CodIes1
                   INNER JOIN LIVR L ON I.CodIes = L.CodIes AND L.CODLIVR = L1.CODLIVR
                   LEFT  JOIN NIRSTOC NS ON L1.CodNirStoc = NS.CodNirSToc
                   LEFT  JOIN LIVRVAL LV ON L1.CodLivr1 = LV.CodLivr1
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T''
              AND I.Operat = 1
              AND (pkg_list_base_topclientiold_ConditieIncludereIOArt(coalesce(ns.codioart,lv.codioart)) &gt; 0 OR L1.CODLIVR1 IS NULL OR I.INFOCM = 1)
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else coalesce(L1.Cant,I1.CANT) end)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, AG.CodPers
              UNION ALL
              SELECT
                Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) Semn,
                I.Partener CodPart,
                I1.ContDiscount CodCont,
                SUM((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)) CANT,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end)) VAL,
                SUM(((I1.RestFact - I1.TVA)) * (case when coalesce(I.MONEDA, 0)=0 then 1 else I.CURS end) /
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) Val_Val,
                sum(adaosuri.adaos) adaos,
                sum(adaosuri.adaos/
                PKG_LIST_BASE_UTILS_GETCURSREFERINTA(fnc_GetValConstanta(''MonedaSitV'',GETANLUCRU(), GETLUNALUCRU()), fnc_GetValConstanta(''BancaSitV'',GETANLUCRU(), GETLUNALUCRU()), to_char(I.DataDoc,''dd.mm.yyyy''))) adaos_val,
                SUM(case when i1.tiplinie &lt;&gt; ''='' then ((I1.RestFact - I1.TVA)) else pkg_list_base_topclientiold_GetValAchiz(I1.CodIes1) end) ValAchiz,
                AG.nume||'' ''||AG.prenume agent,
                AG.CodPers CodAgent,
                I.CodLocatie
              FROM IESIRI I
                   INNER JOIN IESIRI1 I1 ON I1.CODIES=I.CODIES
                   INNER JOIN NCONT C ON I1.ContDiscount = C.CodCont
                   INNER JOIN NPART P ON I.PARTENER = P.CODPART
                   left  join TMP_TOPCLI_ADAOSURI ADAOSURI on i1.codies1 = adaosuri.codies1
                   LEFT  JOIN NPERS AG ON i.agent = AG.codpers
              WHERE I.DATADOC '||vCondData||
              PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',null,null,null) ||'
              AND I.TipDoc = 21
              AND coalesce(I.Anulat, 0) = 0
              AND coalesce(I.Initializari, 0) = 0
              AND I1.TipLinie &lt;&gt; ''G'' AND I1.TipLinie &lt;&gt; ''T'' AND I1.TIPLINIE = ''S''
              AND I.Operat = 1
              AND pkg_list_base_topfurn_conditieclasa(pkg_list_base_topclientiold_getallcls_n, I1.CODOBIECT) &gt; 0
              GROUP BY I1.ContDiscount, I.Partener, Sign((case when i1.tiplinie=''S'' then I1.cant else I1.CANT)), adaosuri.adaos, I.MONEDA, I.CURS, I.DataDoc,
              AG.nume, AG.prenume, I.CodLocatie, AG.CodPers
            ) S
              GROUP BY S.CodCont, S.CodPart, S.Semn, S.agent, S.CodLocatie, S.CodAgent';
        if vWithEmul then
           sSelect := sSelect||'
            UNION ALL
              SELECT
                E.CodPart,
                E1.CodObiect,
                SUM(E1.Cant) Cant,
                SUM(E1.CANT * E1.PRET - E1.TVA) Val,
                0 Val_Val,
                0 CodCont,
                0 adaos,
                SUM(E1.CANT * E1.PRET - E1.TVA) valachiz,
                AG.NUME||'' ''||AG.PRENUME AGENT,
                E.CodAgent,
                E.CodLocatie
              FROM EMULARE E
                   INNER JOIN EMULARE1 E1 ON E.CODEMULARE = E1.CODEMULARE
                   INNER JOIN NCASEMARCAT C ON E.CODCASAMARCAT = C.CODCASEMARCAT
                   LEFT JOIN NPERS AG ON AG.CODPERS = E.CODAGENT
              WHERE E.DATABON '||vCondData||'
                    AND coalesce(E.CODIES,0) = 0 AND coalesce(E.CODPART,0) &gt; 0
                    AND pkg_list_base_topclientiold_ConditieIncludereE(E1.CODEMULARE1) &gt; 0
              GROUP BY E.CODPART, E1.CODOBIECT, E.CODAGENT, E.CODLOCATIE, AG.NUME, AG.PRENUME  ';
        END IF;
           sSelect := sSelect||'
            ) V
            LEFT JOIN TMP_TOPCLI_VALCLIENT VALCLIENT ON V.CodPart = ValClient.CodPart and V.CodLocatie = ValClient.CodLocatie
            LEFT JOIN TMP_TOPCLI_VALAGENT VALAGENT ON V.CodAgent = ValAgent.Agent and V.CodLocatie = ValAgent.CodLocatie
            LEFT JOIN TMP_TOPCLI_VALAGENTART VALAGENTART ON V.CodAgent = ValAgentArt.Agent and V.CodLocatie = ValAgentArt.CodLocatie and V.CodObiect = ValAgentArt.CodObiect
            LEFT JOIN NARTOBJ NAO ON NAO.CODOBIECT = V.CODOBIECT
            LEFT JOIN NCONT C ON V.CODCONT = C.CODCONT
            LEFT JOIN NART ART ON NAO.CodArticol = ART.CodArticol
            LEFT JOIN NCLASEA CLSA ON ART.Clasa = CLSA.CodClaseA
            LEFT JOIN NUM ON ART.UM = NUM.CODUM
            LEFT JOIN NPART P ON V.CodPart = P.CodPart
            LEFT JOIN NPARTCODFISC CF ON P.CodPart = CF.CodPart AND CF.Principal = 1
            LEFT JOIN NCLASEP CLSP ON P.CodClasa = CLSP.CodClaseP
            LEFT JOIN NAGENDA AG ON AG.CodPart = V.CodPart AND AG.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(AG.INACTIV, 0) = 0
            LEFT JOIN NPERS AGENT ON AG.CodAgent = AGENT.CodPers
            LEFT JOIN NLOCALIT LOC ON AG.CodLocalit = LOC.CodLOcalit
            LEFT JOIN NJUDET JUD ON LOC.CodJudet = JUD.CodJudet
            LEFT JOIN NAGENDA AGL ON AGL.CodAgenda = V.CodLocatie
            LEFT JOIN NLOCALIT LOCL ON AGL.CodLocalit = LOCL.CodLOcalit
            LEFT JOIN NJUDET JUDL ON LOCL.CodJudet = JUDL.CodJudet'||
            gSuplJoins||'
          WHERE V.CANT &lt;&gt; 0
          ';
        end if;
      end if;
    end if;
  end if;

  if vOrder = 1 then
    sSelect := sSelect||' ORDER BY ValClient.ValTot DESC';
  end if;
  if vOrder = 2 then
    sSelect := sSelect||' ORDER BY ValClient.ValTot DESC';
  end if;
  if vOrder = 3 then
    sSelect := sSelect||' ORDER BY ValClient.AdaosTot DESC';
  end if;
  if vOrder = 4 then
    sSelect := sSelect||' ORDER BY ValClient.AdaosTot DESC';
  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_incfact_processlist</obj_name>
  <obj_hashval>5eddc0ca997ee45b95f2d01ddb19d0bb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_incfact_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 := '';

  sFAdaosDoc     varchar ;
  sInsert        varchar ;
  sSelI          varchar ;
  sSel           varchar ;
  sSelect        varchar ;
  sSelectI       varchar ;
  sSelect_ini    varchar ;
  sSelect_Tip7   varchar ;
  sSelect_Mon    varchar ;
  sSelect_Doc0   varchar ;
  sSelect_fact   varchar ;
  sSelect_InfoCM varchar ;
  sSelectFN      VARCHAR;

   an             numeric(4);
  luna           numeric(2);
  vAnp           numeric(4,0);
  vLunaP         numeric(2,0);
  sAnP           VARCHAR(4);
  sLunaP         VARCHAR(4);
  sFiltruAG      VARCHAR(  500) := '';
  sFiltruPart    VARCHAR(  500) := '';
  sTrezorData     varchar;

  gOpt1           BOOLEAN;
  gOpt2           BOOLEAN;
  gOpt3           BOOLEAN;
  gOpt4           BOOLEAN;
  gAllAg         BOOLEAN;
  gAllPart       BOOLEAN;
  gSumarIncFact   BOOLEAN;
  gTotfact       BOOLEAN;
  gCriteriu       numeric;
  gDataS         VARCHAR(10);
  gDataF         VARCHAR(10);
  gDataRef       VARCHAR(10);

BEGIN
  --Florin 14.12.2022 - fixat 56540
  --Adina 23.04.2021 - tuning - mergea fff.greu - inlocuit PKG_LIST_BASE_UTILS_decode_iCont
  --Adina 16.04.2021 - sinc.Oracle din 15.04.2021
  --Adina 19.12.2020 tichet 41736 si 41737
  --Adina 16.12.2020 tichet 41646
  --Bogdan 04.09.2020
  gDataS        := current_setting('pkg_list_base_incfact.gDataS'       ,true);
  gDataF        := current_setting('pkg_list_base_incfact.gDataF'       ,true);
  gOpt1         := current_setting('pkg_list_base_incfact.gOpt1'        ,true)::numeric = 1;
  gOpt2         := current_setting('pkg_list_base_incfact.gOpt2'        ,true)::numeric = 1;
  gOpt3         := current_setting('pkg_list_base_incfact.gOpt3'        ,true)::numeric = 1;
  gOpt4         := current_setting('pkg_list_base_incfact.gOpt4'        ,true)::numeric = 1;
  gAllAg        := current_setting('pkg_list_base_incfact.gAllAg'       ,true)::numeric = 1;
  gAllPart      := current_setting('pkg_list_base_incfact.gAllPart'     ,true)::numeric = 1;
  gSumarIncFact := current_setting('pkg_list_base_incfact.gSumarIncFact',true)::numeric = 1;
  gTotfact      := current_setting('pkg_list_base_incfact.gTotfact'     ,true)::numeric = 1;
  gCriteriu     := current_setting('pkg_list_base_incfact.gCriteriu'    ,true)::numeric;
  gDataRef      := current_setting('pkg_list_base_incfact.gDataRef'     ,true);

  gSuplCols := 'npers ag, nagenda sed, npart p, npart1 p1, nmonede mon, centrecost cc, ngest g, nclaseg cg, nclasep cp, nlocalit sedloc, '||
               'njudet sedjud, ntipsedii sedtip, nsubunit ssting, nsubunit sstins, nsubunit scec, trezor1 t1';


  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'  , 'PD'      , 'PD.CODPART = P.CODPART'          ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'IESIRI'    , 'ISTINS'  , 'ISTINS.CODIES = X.CODDOCS'       , 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'OBLIGPIF'  , 'OSTINS'  , 'OSTINS.CODOBLIGPIF = X.CODOBLIGS', 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NBANKCONT' , 'BC'      , 'BC.CODBANKCONT = X.CODBANKCONT'  , 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NBANK'     , 'B'       , 'B.CODBANK = BC.CODBANK'          ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'DOCCARNETE', 'STINS_CC', 'STINS_CC.CODCARNET = X.CDSTINS'  , 1);
  call pkg_list_struct_addsupltabs(gSuplCols, 'DOCCARNETE', 'STING_DC', 'STING_DC.CODCARNET = X.CDSTING'  , 1);
  CALL pkg_list_struct_getsuplcols( aLISTID, aLISTVER, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config('pkg_list_base_incfact.gSuplCols',gSuplCols,false);

  perform set_config('pkg_list_base_incfact.gUserFields',gUserFields,false);
  perform set_config('pkg_list_base_incfact.gUserAlias' ,gUserAlias ,false);
  perform set_config('pkg_list_base_incfact.gNullAlias' ,gNullAlias ,false);
  perform set_config('pkg_list_base_incfact.gSuplJoins' ,gSuplJoins ,false);
  perform set_config('pkg_list_base_incfact.gSuplCols'  ,gSuplCols  ,false);

  select  pkg_setluni_GetLunaInitiala.an , pkg_setluni_GetLunaInitiala.luna
  from pkg_setluni_GetLunaInitiala(an, luna) into an,luna;

  perform set_config('pkg_list_base_incfact.an',an::varchar,false);
  perform set_config('pkg_list_base_incfact.luna',luna::varchar,false);

  select  PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA.newan , PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA.newluna
  from PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA(current_setting('PKG_GLOBALS.ANINITIAL', true)::numeric,
                                               current_setting('PKG_GLOBALS.LUNAINITIALA', true)::numeric,
                                               vAnP, vLunaP) into vAnP, vLunaP;

  sAnP   := vAnP::varchar;
  sLunaP := vLunaP::varchar;
  perform set_config('pkg_list_base_incfact.sAnP'  ,sAnP::varchar  ,false);
  perform set_config('pkg_list_base_incfact.sLunaP',sLunaP::varchar,false);

  IF gOpt2 THEN
    sTrezorData := 't1.datadoc';
  ELSE
    sTrezorData := 'CASE WHEN t.tipdoc = 31 THEN t1c.datadoc ELSE t1.datadoc END';
  END IF;
  perform set_config('pkg_list_base_incfact.sTrezorData',sTrezorData,false);

  sFiltruAG := '';
    IF NOT gAllAg THEN
      sFiltruAG :='
          AND EXISTS (SELECT VALOARE::NUMERIC FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPERS'' and I.AGENT = VALOARE::NUMERIC)';
    END IF;
  perform set_config('pkg_list_base_incfact.sFiltruAG',sFiltruAG,false);

  sFiltruPart := '';
  IF NOT gAllPart THEN
      sFiltruPart :='
        AND EXISTS (SELECT VALOARE::NUMERIC FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPART'' and I.PARTENER = VALOARE::NUMERIC)';
  END IF;

  perform set_config('pkg_list_base_incfact.sFiltruPart',sFiltruPart,false);

  IF gCriteriu = 0  THEN

    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()||'
            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 '||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, X.CEC_SCADENTA, 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 '||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 '||
      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, X.CEC_SCADENTA, 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 '||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 '||
      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()||' 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 and abs(i.valdoc) &gt; 0.01 '||
        PKG_LIST_BASE_UTILS_COND_SUBUNIT('I')||
        sFiltruAG||sFiltruPart||'
        AND i.DATADOC &lt;= 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::DATE END CEC_Data, CASE WHEN t.tipdoc = 31 THEN t1.datadecont ELSE NULL::DATE 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,
        t.codbanca codbankcont, 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
        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 t1.DATADOC &lt;= 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::DATE CEC_DATA, NULL::DATE CEC_SCADENTA, NULL TREZOR_Doc, 0 CEC_VALNED, 0 CEC_Sub, 0 codbankcont, 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 c.DATADOC &lt;= 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::DATE CEC_DATA, NULL::DATE CEC_SCADENTA, NULL TREZOR_Doc, 0 CEC_VALNED, 0 CEC_Sub, 0 codbankcont, 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 E.DATABON &lt;= 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::DATE CEC_DATA, NULL::DATE CEC_SCADENTA, NULL TREZOR_Doc, 0 CEC_VALNED, 0 CEC_Sub, 0 codbankcont, 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 E.DATABON  &lt;= 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.DATAV 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.codbankcont,
        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,
        ox.valoare,
        ox.valoare 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 (
        SELECT codobligpif, SUM(valoare) valoare
        FROM (
          SELECT
            obstins.codobligpif, obstins.valoare
          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
          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 i.DATADOC &lt;= TO_DATE('''||gDataF||''', ''dd.mm.yyyy'')
            AND Coalesce(i.valdoc, 0) &lt;&gt; 0
          /*UNION ALL
          SELECT
            obstins.codobligpif, osting.valoare
          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
            INNER JOIN stingere s       ON s.codstinspif = obstins.codobligpif
            INNER JOIN obligpif osting  ON osting.codobligpif = s.codstingatorpif
            INNER JOIN general gsting   ON gsting.codgeneral  = osting.codgeneral
            INNER JOIN general gcec     ON gcec.coddoc = gsting.coddoc AND gcec.tipdoc = gsting.tipdoc AND gcec.semnificatie &lt;&gt; gsting.semnificatie
            INNER JOIN obligpif ocec    ON ocec.codgeneral = gcec.codgeneral
            LEFT  JOIN obligpifluna ol  ON ol.codobligpif  = ocec.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 i.DATADOC &lt;= TO_DATE('''||gDataF||''', ''dd.mm.yyyy'') */
        ) A1_PG GROUP BY codobligpif
      ) ox
        LEFT JOIN obligpif       obstins ON obstins.codobligpif = ox.codobligpif
        LEFT JOIN general        g       ON g.codgeneral        = obstins.codgeneral
        LEFT JOIN iesiri         i       ON i.codies            = g.coddoc
        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||'
    ),
    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.initializari = 1 THEN o.valoare  ELSE s.valoare end valstins,
        --case when t1.initializari = 1 THEN OFCT.VALOARE ELSE s.valoare end valstins,
        coalesce(g.tva,0) 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::DATE END CEC_Data, CASE WHEN t.tipdoc = 31 THEN t1.datadecont ELSE NULL::DATE 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,
        t.codbanca codbankcont, 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
        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
        LEFT  JOIN OBLIGPIF OFCT ON OFCT.CODOBLIGPIF  = S.CODSTINSPIF
      WHERE t.tipdoc IN (29, 30, 31, 33)
        AND t1.DATADOC &lt;= 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,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::DATE CEC_DATA, NULL::DATE CEC_SCADENTA, NULL TREZOR_Doc, 0 CEC_VALNED, 0 CEC_Sub, 0 codbankcont, 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 c.DATADOC &lt;= 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::DATE CEC_DATA, NULL::DATE CEC_SCADENTA, NULL TREZOR_Doc, 0 CEC_VALNED, 0 CEC_Sub, 0 codbankcont, 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 E.DATABON &lt;= 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::DATE CEC_DATA, NULL::DATE CEC_SCADENTA, NULL TREZOR_Doc, 0 CEC_VALNED, 0 CEC_Sub, 0 codbankcont, 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 E.DATABON  &lt;= 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.DATAV 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.valdoc - 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.codbankcont,
        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 i.DATADOC &lt;= 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::DATE END CEC_Data, CASE WHEN t.tipdoc = 31 THEN t1.datadecont ELSE NULL::DATE 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 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,
        t.codbanca codbankcont, 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
        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 T1.DATADOC 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.CEL_valned,stingatori.CEC_Sub, 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.codbankcont,
        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 i.DATADOC 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::DATE CEC_DATA, NULL::DATE 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 codbankcont,
        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 i.DATADOC &lt;= 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 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 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 i.DATADOC &lt;= 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
        LEFT  JOIN emulare  e ON e.codies     = i.codies
      WHERE i.DATADOC 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::DATE CEC_DATA, NULL::DATE 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, 0 codbankcont,
        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 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
                                             AND g.semnificatie &lt;&gt; 240
        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.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 i.DATADOC &lt;= 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.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::DATE CEC_DATA, NULL::DATE 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,
        null 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 codbankcont,
        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 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 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 i.DATADOC 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 and abs(i.valdoc) &gt; 0.01
      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 i.DATADOC 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 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::DATE CEC_DATA, NULL::DATE 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 codbankcont,
        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;

    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 &lt;= 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, 0 codtrezor1
      FROM emulare e INNER JOIN iesiri i on e.codies = i.codies
      WHERE e.DATABON 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.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::DATE CEC_DATA, NULL::DATE CEC_SCADENTA, 0 CEC_Sub, 0 CEC_VALNED, null TREZOR_Doc, stinsi.Agent, stingatori.DATAV TREZOR_DATA,
        case when coalesce(stinsi.valdoc,0) = 0 then 0 else PKG_LIST_BASE_SCADENTARCL_CalcAdaosDoc(Stinsi.CodDoc, stinsi.valoare)*stinsi.valoare/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,
        stingatori.codcentru, stingatori.codgest,
        stinsi.subunitatea substing, stinsi.subunitatea substins,rpart.restpart, 0 codbankcont,
        stingatori.carnetdoc cdsting, stinsi.carnetdoc cdstins, stingatori.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;

  ELSE
    select
        PKG_LIST_BASE_INCFACT_AduStringuriCriteriu1.sInsert, PKG_LIST_BASE_INCFACT_AduStringuriCriteriu1.sSelect ,
        PKG_LIST_BASE_INCFACT_AduStringuriCriteriu1.sSelecti ,
        PKG_LIST_BASE_INCFACT_AduStringuriCriteriu1.sSelect_tip7 ,PKG_LIST_BASE_INCFACT_AduStringuriCriteriu1.sSelect_doc0 ,
        PKG_LIST_BASE_INCFACT_AduStringuriCriteriu1.sSelect_infocm ,PKG_LIST_BASE_INCFACT_AduStringuriCriteriu1.sSelect_fact,
        PKG_LIST_BASE_INCFACT_AduStringuriCriteriu1.sSel
    from PKG_LIST_BASE_INCFACT_AduStringuriCriteriu1(TmpName)
    into sInsert, sSelect, sSelecti, sSelect_tip7,sSelect_doc0,sSelect_infocm,sSelect_fact, sSel;
  END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert||sSelect,      aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert||sSelecti,     aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert||sSelect_tip7, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert||sSelect_doc0, aListID, aListVer);
  IF gOpt4 THEN
      PERFORM LIST_EXECUTE_IMMEDIATE(sInsert||sSelect_infocm, aListID, aListVer);
  END IF;

  IF gOpt1 THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert||sSelect_fact, aListID, aListVer);
  END IF;

-------------------- primul update
/* --23.04.2021
   sSelect :=
      'DO $$ DECLARE v_rec record;
      begin
         for v_rec in (
           select tmp.codpart, coalesce(fact.SumF,0) - coalesce(inc.SumS,0) RestPart
           from '||tmpName||' tmp
             left join (select sum(fact_val) SumF, codpart
              from (select distinct codobligs, codpart, fact_val from '||tmpName||') a_pg group by codpart) fact on fact.codpart = tmp.codpart
             left join (select sum(inc_val)  SumS, codpart from '||tmpName||' group by codpart) inc on inc.codpart = tmp.codpart
         ) loop
           update '||tmpName||' set restpart = v_rec.restpart where codpart = v_rec.codpart;
         end loop;
         end $$;';
*/
  sSelect := 'with tt as
             (select tmp.codpart, coalesce(fact.SumF,0) - coalesce(inc.SumS,0) RestPart
              from '||tmpName||' tmp
                 left join (select sum(fact_val) SumF, codpart
                            from (select distinct codobligs, codpart, fact_val from '||tmpName||') a_pg group by codpart) fact on fact.codpart = tmp.codpart
                 left join (select sum(inc_val)  SumS, codpart from '||tmpName||' group by codpart) inc on inc.codpart = tmp.codpart
             )
             update '||tmpName||' a set restpart = tt.restpart FROM tt WHERE a.codpart=tt.codpart
            ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);

---------------------al 2-lea update
/*  --23.04.2021
  sSelect :=
      ' DO $$
      begin
         update '||tmpName||' tmp set rest1 = case
                                                when tmp.fact_val &gt; 0 then (select min(t.rest) from '||tmpName||' t where t.codobligs = tmp.codobligs)
                                                else (select max(t.rest) from '||tmpName||' t where t.codobligs = tmp.codobligs)
                                              end;
       end $$;';
*/
  sSelect := 'with tt AS (select codobligs, min(rest) restmin, max(rest) restmax from '||tmpName||' GROUP BY codobligs)
              update '||tmpName||' tmp set rest1 = case when tmp.fact_val &gt; 0 then tt.restmin else tt.restmax end
                  FROM tt WHERE tmp.codobligs=tt.codobligs
             ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);

  IF  NOT gSumarIncFact THEN
/*  --23.04.2021
    sSelect :=
        'DO $$ DECLARE v_rec record;
        begin
             for v_rec in (
               select distinct tmp.codobligs, tmp.fact_val, tmp.rest1
               from '||tmpName||' tmp
             ) loop
               update '||tmpName||' set fact_val = 0, rest1 = 0 where codobligs = v_rec.codobligs;
               update '||tmpName||' set fact_val = v_rec.fact_val, rest1 = v_rec.rest1 where codobligs = v_rec.codobligs and Ordine = (select max(ordine) from '||tmpName||' where codobligs = v_rec.codobligs);
             end loop;
           end $$;';
*/
    sSelect := 'with tt as
                (select distinct tmpw.codobligs, tmpw.fact_val, tmpw.rest1, tmpw.ordine
                 from '||tmpName||' tmpw
                 where ordine = (select max(ordine) from '||tmpName||' where codobligs = tmpw.codobligs)
                )
                update '||tmpName||' tmp
                set fact_val = case when tmp.ordine=tt.ordine then tt.fact_val else 0 end,
                    rest1    = case when tmp.ordine=tt.ordine then tt.rest1    else 0 end
                FROM tt WHERE tmp.codobligs=tt.codobligs
               ';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
  END IF;

  IF gSumarIncFact THEN
/*
    sSelect :=
          'DO $$
         begin
             update '||tmpName||' tmp set rest = case
                                                   when tmp.fact_val &gt; 0 then (select min(t.rest) from '||tmpName||' t where t.codobligs = tmp.codobligs group by t.codobligs)
                                                   else (select max(t.rest) from '||tmpName||' t where t.codobligs = tmp.codobligs group by t.codobligs)
                                                 end;
           end $$;';
*/
    sSelect := 'with tt AS (select codobligs, min(rest) restmin, max(rest) restmax from '||tmpName||' GROUP BY codobligs)
                update '||tmpName||' tmp set rest = case when tmp.fact_val &gt; 0 then tt.restmin else tt.restmax end
                  FROM tt WHERE tmp.codobligs=tt.codobligs
                ';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
-------------
/*
    sSelect :=
          ' DO $$
          begin
               delete from '||tmpName||' tmp where rest = 0.0;
             end $$;';
*/
    sSelect := 'delete from '||tmpName||' tmp where rest = 0.0 ';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
--------------

    sSelect :=
        'DO $$
           begin
             update '||tmpName||' tmp
             set
               INC_DOC = null,
               INC_DATA = null,
               INC_VAL = null,
               INC_VALFTVA = null,
               DIFZILE = null,
               INC_VAL1 = null,
               INC_VAL2 = null,
               INC_VAL3 = null,
               INC_VAL4 = null,
               INC_VAL5 = null,
               INC_VAL_0_7 = null,
               INC_VAL_8_21 = null,
               INC_VAL_22_40 = null,
               INC_VAL_61_70 = null,
               INC_VAL_61_75 = null,
               INC_VAL_71_85 = null,
               INC_VAL_40p = null,
               INC_VAL_75p = null,
               INC_VAL_85p = null
             where CEC_Doc is null;
           end $$;';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
    sSelect :=
          'DO $$
             begin
               update '||tmpName||' tmp
               set
                 INC_DOC = null,
                 INC_DATA = null,
                 INC_VAL = null,
                 INC_VALFTVA = null,
                 DIFZILE = null,
                 INC_VAL1 = null,
                 INC_VAL2 = null,
                 INC_VAL3 = null,
                 INC_VAL4 = null,
                 INC_VAL5 = null,
                 INC_VAL_0_7 = null,
                 INC_VAL_8_21 = null,
                 INC_VAL_22_40 = null,
                 INC_VAL_61_70 = null,
                 INC_VAL_61_75 = null,
                 INC_VAL_71_85 = null,
                 INC_VAL_40p = null,
                 INC_VAL_75p = null,
                 INC_VAL_85p = null,
                 CEC_Doc = null,
                 CEC_DATA = null,
                 CEC_SCADENTA = null,
                 CEC_VALNED = null
               where CEC_VALNED = 0.0 and not CEC_Doc is null and rest &lt;&gt; 0.0;
             end $$;';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);

    sSelect :=
          'DO $$
             declare i numeric;
               v_rec record;
             begin
               for v_rec in (select distinct count(*) nr, tmp.codobligs, max(ordine) ordine
                             from '||tmpName||' tmp
                             group by tmp.codobligs) loop
                 if v_rec.nr &gt; 1 then '
--                   for i in 1..v_rec.nr - 1 loop
--                     with a as
--                     (select ctid from '||tmpName||' tmpi
--                      where tmpi.codobligs = v_rec.codobligs
--                            and tmpi.INC_DOC is null
--                            and tmpi.CEC_Doc is null limit 1 offset 0
--                     )
--                     delete from ' ||tmpName|| ' tmp where tmp.ctid = (select a.ctid from a);
--                   end loop;
--Adina: 19.12.2020 - nu stergea ce trebuie folosind ctid
                   ||'delete from '||tmpName||' tmp
                    where codobligs = v_rec.codobligs and INC_DOC is null
                         and CEC_Doc is null
                         and ordine &lt; v_rec.nr;
                 end if;
               end loop;
             end $$;';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);

    sSelect :=
        'DO $$
           declare v_rec record;
           begin
             for v_rec in (select distinct count(*) nr, tmp.codobligs, max(ordine) ordine
                           from '||tmpName||' tmp
                           group by tmp.codobligs) loop
               if v_rec.nr &gt; 1 then
                 update '||tmpName||' tmp set fact_val = 0 where codobligs = v_rec.codobligs;
                 update '||tmpName||' tmp set fact_val = (select valoare from obligpif where codobligpif = v_rec.codobligs) where codobligs = v_rec.codobligs and tmp.ordine = v_rec.ordine;
               end if;
             end loop;
           end $$;';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
    sSelect :=
          'DO $$
             declare v_rec record;
             begin
               for v_rec in (select distinct tmp.coddocs, tmp.rest1
                             from '||tmpName||' tmp) loop
                 update '||tmpName||' set rest1 = 0 where coddocs = v_rec.coddocs;
                 update '||tmpName||' set rest1 = v_rec.rest1
                 where coddocs = v_rec.coddocs
                       and Ordine = (select max(ordine) from '||tmpName||' where coddocs = v_rec.coddocs);
               end loop;
             end $$;';
    PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);
  END IF;

  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) val_AA,  --19.12.2020 - botezat val_AA
            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::date CEC_DATA, NULL::DATE 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 stinsi.CODDOC = TMP.NAV_CODDOC AND stinsi.TIPDOC = TMP.NAV_TIPDOC)
          ) '||sSel;
    PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelectfn,''), aListID, aListVer);
  END IF;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_intrari_insertintrari</obj_name>
  <obj_hashval>23b2779354302a0e1f862e3b67adfb0c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_intrari_insertintrari(tmpname character varying, puserfields character varying, puseralias character varying, pnullalias character varying, pjoinext character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert    varchar;
  sInsertTMP varchar;
  sUpdateTMP varchar;
  sJoinUM    varchar;
  sInsertDC  varchar;
  sWithDc    varchar;
  sSelectDC  varchar;
  sJoinDC    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 disct, 0 discc, 0 discv, NULL ArtCadou, 0 CantCadou';
  sDiscNC    varchar := ', 0 discnct, 0 discncc, 0 discvcc, NULL ArtCadouNC, NULL UMCadouNC, 0 CantCadouNC, 0 PretCadouNC';
  vMax       NUMERIC := (SELECT PKG_LIST_BASE_UTILS_NIVELE_NCLASEA.WME_RESULT FROM PKG_LIST_BASE_UTILS_NIVELE_NCLASEA(NULL,NULL))::NUMERIC;
  sDataS     Date := fnc_current_setting_date('PKG_LIST_SELINTIES.vDataS');
  sDataF     Date := fnc_current_setting_date('PKG_LIST_SELINTIES.vDataF');
begin
  --Florin 12.01.2022 - sinc. Oracle (11.01.2022)
  --Adina 09.03.2021 - prc_al_check
  --Adina 15.01.2021 - pus la linia 126 pkg_contract_SIMCADOU_CANT in loc de pkg_contract_SIMCADOU_DEN!!
  --Florin 13.08.2020
  --Florin 19.12.2020 - CIF_VALID cu un singur parametru
  PERFORM pkg_globals_SetSeparator(',');
  --PERFORM PKG_LIST_BASE_UTILS_UMA_UTILS('i1.cant', 'i1.codobiect', sInsertDC, sSelectDC, sJoinDC,NULL);
  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, sJoinDC
  FROM PKG_LIST_BASE_UTILS_UMA_UTILS('i1.cant', 'i1.codobiect', sInsertDC, sSelectDC, sJoinDC,NULL);

  sInsertDC := coalesce(sInsertDC,'');
  sSelectDC := coalesce(sSelectDC,'');
  sJoinDC   := coalesce(sJoinDC,'');

  IF current_setting('PKG_LIST_BASE_INTRARI.vUM', true)::NUMERIC = current_setting('PKG_LIST_BASE_INTRARI.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 i.operat      = 0 THEN 0
        WHEN i.valdoc      = 0 THEN 0
        WHEN i1.cant*i1.pu = 0 THEN 0
        ELSE i1.cant*(i1.pu+i1.tvau) / i.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 = 1353
                                                   WHERE g.tipdoc = i.tipdoc AND g.coddoc = i.codintr AND g.semnificatie = 100
                                                  )
      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, I.TipDoc, I1.CodObiect, I.Partener, I.CodLocatie, I.Subunitatea, I.DataDoc)) contrpret,
      (SELECT Tip     FROM pkg_contract_GETTERMEN(I.TipDoc, I1.CodObiect, I.Partener, I.CodLocatie, I.Subunitatea, I.DataDoc)) ContrTermTip,
      (SELECT Termen1 FROM pkg_contract_GETTERMEN(I.TipDoc, I1.CodObiect, I.Partener, I.CodLocatie, I.Subunitatea, I.DataDoc)) ContrTerm1,
      (SELECT Termen2 FROM pkg_contract_GETTERMEN(I.TipDoc, I1.CodObiect, I.Partener, I.CodLocatie, I.Subunitatea, I.DataDoc)) ContrTerm2,
      (SELECT Termen3 FROM pkg_contract_GETTERMEN(I.TipDoc, I1.CodObiect, I.Partener, I.CodLocatie, I.Subunitatea, I.DataDoc)) ContrTerm3,
      (SELECT Disc1   FROM pkg_contract_GETTERMEN(I.TipDoc, I1.CodObiect, I.Partener, I.CodLocatie, I.Subunitatea, I.DataDoc)) ContrTerm1Disc,
      (SELECT Disc2   FROM pkg_contract_GETTERMEN(I.TipDoc, I1.CodObiect, I.Partener, I.CodLocatie, I.Subunitatea, I.DataDoc)) ContrTerm2Disc,
      (SELECT Disc3   FROM pkg_contract_GETTERMEN(I.TipDoc, I1.CodObiect, I.Partener, I.CodLocatie, I.Subunitatea, I.DataDoc)) ContrTerm3Disc,
      (SELECT pkg_contract_GETADDIM.WME_RESULT FROM pkg_contract_GETADDIM(NULL, I.TipDoc, I1.CodObiect, I.Partener, I.CodLocatie, I.Subunitatea, I.DataDoc)) contraddim,
      --pkg_contract_CALCULEAZA_DISCT_LINIE(I.TipDoc, I1.CodIntr1, I.DataDoc) disct,
      CASE
        WHEN I.operat = 0      THEN 0
        WHEN I1.Cant  = 0      THEN 0
        WHEN I1.PU    = 0      THEN 0
        WHEN I.TipDoc IN (1,9) THEN (SELECT pkg_contract_DISCMAXTERMEN.wme_Result from pkg_contract_DISCMAXTERMEN(NULL, I.TipDoc, I1.CodObiect, I.Partener, I.CodLocatie, I.Subunitatea, I.DataDoc, I1.Cant, I1.PU))::numeric
        ELSE 0
      END disct,
      CASE
        WHEN I.operat = 0      THEN 0
        WHEN I1.Cant  = 0      THEN 0
        WHEN I.TipDoc IN (1,9) THEN (SELECT Coalesce(MAX(CASE WHEN T.DISCUNITAR &lt;&gt; 0 THEN i1.cant * t.discunitar
                                                              ELSE i1.cant * i1.pu * t.pjdisc / 100
                                                         END
                                                        ),0
                                                    )
                                     FROM TMP_INTRDISCC T
                                     WHERE T.PARTENER = I.PARTENER
                                           AND (T.LOCATIE    = 0             OR T.LOCATIE   = I.CODLOCATIE)
                                           AND T.SUBUNITATEA = I.SUBUNITATEA
                                           AND T.CODOBIECT   = I1.CODOBIECT
                                           AND T.DATASTART  &lt;= I.DATADOC     AND T.DATASTOP &gt;= I.DATADOC
                                    )
        ELSE 0
      END discc,
      CASE
        WHEN I.operat = 0      THEN 0
        WHEN I1.Cant  = 0      THEN 0
        WHEN i.TipDoc IN (1,9) THEN (SELECT Coalesce(MAX(i1.cant*i1.pu*t.disc/t.baza),0)
                                     FROM TMP_INTRDISCV T
                                     WHERE T.PARTENER = I.PARTENER
                                           AND (T.LOCATIE    = 0             OR T.LOCATIE   = I.CODLOCATIE)
                                           AND T.SUBUNITATEA = I.SUBUNITATEA
                                           AND (T.CODOBIECT  = 0             OR T.CODOBIECT = I1.CODOBIECT)
                                           AND T.DATASTART  &lt;= I.DATADOC     AND T.DATASTOP &gt;= I.DATADOC
                                           AND Coalesce(T.BAZA,0) &lt;&gt; 0
                                    )
        ELSE 0
      END discv,
      CASE
        WHEN I.operat = 0      THEN NULL
        WHEN I1.Cant  = 0      THEN NULL
        WHEN I.TipDoc IN (1,9) THEN (CASE WHEN (SELECT pkg_contract_SIMCADOU_DEN.wme_result FROM pkg_contract_SIMCADOU_DEN(NULL, 1, I1.CodObiect, I.Partener, I.CodLocatie, I.Subunitatea, I.DataDoc)) = '''' THEN NULL
                                          ELSE (SELECT pkg_contract_SIMCADOU_DEN.wme_result FROM pkg_contract_SIMCADOU_DEN(NULL, 1, I1.CodObiect, I.Partener, I.CodLocatie, I.Subunitatea, I.DataDoc))
                                     END
                                    )
        ELSE NULL
      END ArtCadou,
      CASE
        WHEN I.operat = 0      THEN 0
        WHEN I1.Cant  = 0      THEN 0
        WHEN I.TipDoc IN (1,9) THEN (SELECT pkg_contract_SIMCADOU_CANT.wme_result FROM pkg_contract_SIMCADOU_CANT(NULL, 1, I1.CodObiect, I.Partener, I.CodLocatie, I.Subunitatea, I.DataDoc, 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.codintr1, 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 INTRARI1    I1  ON NC1.CODDOC     = I1.CODINTR1   AND I1.CODOBIECT = NCC.CODOBIECTASOC
             INNER JOIN INTRARI     I   ON I.CODINTR      = I1.CODINTR    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 = 59 AND NC1.TIPOPER = ''C''
      ) Cad ON cad.codintr1 = i1.codintr1';
    sDiscNC := ',
      Coalesce((SELECT SUM(NC1.VALOARE) FROM NOTECREDIT NC INNER JOIN NOTECREDIT1 NC1 ON NC.CODNCREDIT = NC1.CODNCREDIT
                WHERE NC.TIPDOC = 59 AND NC1.TIPOPER = ''T'' AND NC1.CODDOC = I1.CodIntr1 AND NC1.TIPDOC = I1.TipDoc ),0) disctnc,
      Coalesce((SELECT SUM(NC1.VALOARE) FROM NOTECREDIT NC INNER JOIN NOTECREDIT1 NC1 ON NC.CODNCREDIT = NC1.CODNCREDIT
                WHERE NC.TIPDOC = 59 AND NC1.TIPOPER = ''C'' AND NC1.CODDOC = I1.CodIntr1 AND NC1.TIPDOC = I1.TipDoc ),0) disccnc,
      CASE
        WHEN i1.cant*i1.pu = 0 THEN 0
        WHEN i.valdoc      = 0 THEN 0
        ELSE (SELECT PKG_NOTECREDIT_GetDiscVolLinie.wme_result FROM PKG_NOTECREDIT_GetDiscVolLinie(NULL, I1.CODINTR1, 59))::numeric
      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';
  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;

  sWithDC := '
    WITH';
  IF  Coalesce(vMax, 0) &gt; 0 THEN
    sWithDC := coalesce(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 := coalesce(sWithDC,'') || '
      FROM TMP_PROFIT_NCLASEA
      GROUP BY codclasea)';
    sJoinDC := coalesce(sJoinDC,'') || '
      LEFT JOIN CLASE CLSC ON CLSC.CodClasea = na.clasa ';
  ELSE
    sWithDC := '';
  END IF;

  sInsertTMP := PKG_LIST_BASE_INTRARI_Sql_tmp_lst_intrari(current_setting('PKG_LIST_BASE_INTRARI.vFiltru', TRUE));
  sUpdateTMP := 'UPDATE tmp_lst_intrari t
    SET codcontract = CASE
                          WHEN t.codcontract1 = 0 THEN t.codcontract
                          ELSE Coalesce ((SELECT c1.codcontract FROM contract1 c1 WHERE c1.codcontract1 = t.codcontract1), t.codcontract)
                        END,
        codcomanda  = CASE
                          WHEN t.codcomanda1 = 0 THEN t.codcomanda
                          ELSE Coalesce ((SELECT c1.codcomanda FROM comanda1 c1 WHERE c1.codcomanda1 = t.codcomanda1), t.codcomanda)
                        END,
        codoferta   = CASE
                          WHEN t.codoferta1 = 0 THEN t.codoferta
                          ELSE Coalesce ((SELECT o1.codoferta FROM oferta1 o1 WHERE o1.codoferta1 = t.codoferta1), t.codoferta)
                        END';
  sInsert := '
    INSERT INTO ' || tmpName || '(
      NAV_CodDoc, NAV_TipDoc, CODOBIECT, TIPART, DEN_ARTICOL,
      IOART, SIMBOL, DEN_CONT, DEN_UM1, CANT,
      PU, PU_CU_TVA, PU_CU_TVAN, ADDIM,
      PROC_TVA, PROC_TVA_NART, DISCTOTAL, DISCTOT_TVA, DISCTOTCUTVA,
      VALOARE, VAL_TVA, VAL_CU_TVA, VAL_TVAN, VAL_CU_TVAN,
      DEN_PART, DATADOC, TIPDOC, NRDOC,
      DOCUMENT, NRAVIZ, SERDOC,
      BLOCAT, MONEDA, CURS, MASA, VOLUM, CODVAMAL, OBSLINIE, DEN_CLASEA,
      CODINTERNA, CODEXTERNA, DEN_PROD, UMALT1, UMALT2,
      CANTUM1, CANTUM2,
      PRETMAXIMAL,
      DEN_LOCALIT, DEN_JUDET, DEN_ZONA,
      TIPTVA, TIPTRANZ,
      DEN_CLASEP, CODFISCAL, CODEXTERNP, CODINTERNP, GESTACT, TIPSERIE, SERIE,
      ZILESCADENTE, TERMEN, MAJORARI, OBSDOC, INDEXLINIE,
      ANDOC, LUNADOC, LUNA, SUBUNITATEA, PRETINREG,
      CUICorect, clasas, nrinreg, datanir, EXCLUSPLATA,
      TRANSPORT, CONTRACT, ZILEDISCT,
      TaxaStopajU, TaxaStopajV, TAXCODE_SAFT,
      SOLD, CONTRPRET,
      CONTRTERMTIP, CONTRTERM1, CONTRTERM2, CONTRTERM3, CONTRTERM1DISC, CONTRTERM2DISC, CONTRTERM3DISC,
      CONTRADDIM, DISCT, DISCC, DISCV, ARTCADOU, CANTCADOU,
      DISCTNC, DISCCNC, DISCVNC, ARTCADOUNC, UMCADOUNC, CANTCADOUNC, PRETCADOUNC,
      curs_ref ' || coalesce(sInsertDC,'') || coalesce(pUserFields,'') || ')' || coalesce(sWithDC,'') || '
    SELECT
      i1.codintr, i1.tipdoc , i1.codobiect, i1.tipart,
      (Case  When i1.tiplinie= ''T'' then ''Majorare direct pe cont (de total)''  When i1.tiplinie=''G'' then ''Majorare direct pe cont (de grup)'' else nao.denumire end),
      ioa.den_ioart, nc.simbol, Coalesce(nc.den_cont,''-''),
      (Case  When i1.tiplinie=''T'' then ''%'' When i1.tiplinie=''G'' then ''%'' else um.den_um1 end), i1.cantrec/Coalesce(um.paritate,1),
      i1.pu*Coalesce(um.paritate,1), (i1.pu+i1.tvau)*Coalesce(um.paritate,1), (i1.pu+i1.tvau*i1.coeftned)*Coalesce(um.paritate,1), i1.addim,
      i1.coef_tva * 100, nt1.procent,i1.cantrec*i1.discu, i1.cantrec*i1.discu*i1.coef_tva, i1.cantrec*i1.discu*(1+i1.coef_tva),
      i1.cantrec*i1.pu, i1.cantrec*i1.tvau, i1.cantrec*(i1.pu+i1.tvau), i1.cantrec*i1.tvau*i1.coeftned, i1.cantrec*(i1.pu+i1.tvau*i1.coeftned),
      (Case When i1.tipdoc=6 then ns.den_subunit When i1.tipdoc=7 then ng.den_gest else np.den_part end), i.datadoc,
      (Case When i1.tipdoc=9 then ''FA'' else i.prefixdoc end), i.nrdoc,
      i.prefixdoc||i.nrdoc||''/''||TO_CHAR(i.Datadoc,''dd.mm.yyyy''), i1.nraviz, i.seriadoc,
      (Case When i.blocat=1 then ''Da'' else ''Nu'' end), mon.simbol,
      (Case When i.curs IS NULL then 1 When i.curs=0 then 1 else i.curs end), nao.masa, nao.volum, nao.codvamal, i1.obsart, nca.den_clasea,
      nao.codintern, nao.codextern, prod.den_part, um1.den_um, um2.den_um,
      (Case  When i1.cantrec=0 then 0 When i1.cantrec=i1.cant then i1.cantum1 else i1.cantum1*i1.cant/i1.cantrec end),
      (Case  When i1.cantrec=0 then 0 When i1.cantrec=i1.cant then i1.cantum2 else i1.cantum2*i1.cant/i1.cantrec end),
      CASE WHEN Coalesce(nao1.tippretmax,0) IN (1,2,3) THEN i1.pumaximal WHEN Coalesce(nao1.tippretmax,0) IN (4,5,6) THEN nao1.pretmaximal ELSE NULL END,
      locsoc.den_localit,judsoc.den_judet, zonasoc.den_zona,
      (Case  When i.tiptva=1 then ''Taxare normala'' When i.tiptva=2 then ''Taxare inversa'' When i.tiptva=3 then ''Tranzactie triunghiulara'' When i.tiptva=4 then ''Suspendare temporara'' end),
      CASE
        WHEN i.tiptranzactie = 2 THEN ''Achizitie intracomunitara''
        WHEN i.tiptranzactie = 3 THEN ''Import servicii''
        WHEN i1.tipdoc = 5 THEN ''Import''
        WHEN i.tiptranzactie = 1 THEN ''Tranzactie interna''
      END,
      ncp.den_clasep, fisc.codfiscal, np.codextern, np.codintern,ngserv.den_gest,i1.tipserie,substr(i1.serii,1,500) serii,
      t.termen - i.datadoc,t.termen,t.majorari,i.obs, i1.indexlocal,
      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,
      nsub.den_subunit, i1.valinreg / (Case  When i1.cantrec=0 then 1 else i1.cantrec end),
      (Case When cif_valid(FISC.CodFiscal::varchar) = 0 then ''NU'' else ''DA'' end), NCLS.DEN_CLASEAS, I.NRI, substr(I1.datanir,1,200) datanir, (Case  When i.exclusplata=1 then ''DA'' else ''NU'' end),
      paut.nrinreg, coalesce(contr.seriadoc,'''')||contr.nrdoc||''/''||to_char(contr.datadoc,''dd.mm.yyyy''), null::numeric ziledisct,
      i1.TaxaStopajU*Coalesce(um.paritate,1) TaxaStopajU, i1.TaxaStopajU*i1.cantrec TaxaStopajV, TXDCL.TAXCODE AS TAXCODE_SAFT '||
      coalesce(sSold,'') || coalesce(sDiscContr,'') || coalesce(sDiscNc,'') || coalesce(current_setting('PKG_LIST_BASE_INTRARI.sCursRef', true),'') || coalesce(sSelectDC,'') || coalesce(pUserAlias,'') || '
    FROM tmp_lst_intrari I1
      LEFT JOIN COMANDA          C       ON C.CODCOMANDA  = I1.CODCOMANDA
      LEFT JOIN INTRARI          I       ON I.CodIntr     = I1.CodIntr
      LEFT JOIN NARTOBJ          NAO     ON nao.codobiect = i1.codobiect
      LEFT JOIN NART             NA      ON na.codarticol = nao.codarticol
      LEFT JOIN NCLASEA          NCA     ON nca.codclasea = na.clasa ' || coalesce(sJoinUM,'') || coalesce(sJoinDC,'') || coalesce(sJoinCadou,'') || '
      LEFT JOIN NUM              UM1     ON um1.codum     = na.um1
      LEFT JOIN NUM              UM2     ON um2.codum     = na.um2
      LEFT JOIN NPART            NP      ON np.codpart    = i.partener
      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         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 NPARTCODFISC     FISC    ON fisc.codpart      = i.partener AND fisc.principal = 1
      LEFT JOIN NCLASEP          NCP     ON ncp.codclasep     = np.codclasa
      LEFT JOIN NGEST            NG      ON ng.codgest      = i.codgestprod
      LEFT JOIN NGEST            NGSERV  ON ngserv.codgest  = i1.gestact
      LEFT JOIN NSUBUNIT         NS      ON ns.codsubunit   = i.codsubunit
      LEFT JOIN NSUBUNIT         NSUB    ON nsub.codsubunit = i.subunitatea
      LEFT JOIN NMONEDE          MON     ON mon.codmoneda   = i.moneda
      LEFT JOIN NPART            PROD    ON prod.codpart    = nao.codproducator
      LEFT JOIN NCLASEAS         NCLS    ON NCLS.CODCLASEAS = NA.CLASASTATIST
      LEFT JOIN (SELECT g.coddoc, g.tipdoc, MAX(o.termen) termen, MAX(o.majorari) majorari
                 FROM obligpif o INNER JOIN general g ON g.codgeneral = o.codgeneral
                 WHERE o.termen IS NOT NULL AND o.semnificatie = 100
                 GROUP BY g.coddoc, g.tipdoc
                )                T       on t.coddoc       = i1.codintr AND t.tipdoc = i1.tipdoc
      LEFT JOIN NARTOBJ1         NAO1    ON nao1.codobiect = i1.codobiect AND (i.an*12+i.luna) BETWEEN nao1.alstart AND nao1.alstop
      LEFT JOIN NART1            NA1     ON na1.codarticol = nao.codarticol AND (i.an*12+i.luna) BETWEEN na1.alstart AND na1.alstop
      LEFT JOIN NTVA1            NT1     ON nt1.codtva     = na1.codtva AND (i.an*12+i.luna) BETWEEN nt1.alstart AND nt1.alstop
      LEFT JOIN NPART1           NP1     ON np1.codpart1   = i1.codpart1
      LEFT JOIN IOART1           IOA1    ON IOA1.CodIOArt1 = I1.CodIOArt1
      LEFT JOIN IOART            IOA     ON IOA.CodIOArt   = IOA1.CodIOArt
      LEFT JOIN IOPART           IOP     ON IOP.CodIOPart  = NP1.CodIOPart
      LEFT JOIN NCONT            NC      ON nc.codcont     = COALESCE(ioa1.cont,i1.codcont,0)
      LEFT JOIN NPARCAUT         PAUT    ON PAUT.CODNPARCAUT  = I1.CODAUTO
      LEFT JOIN OFERTA           O       ON O.CODOFERTA       = I1.CODOFERTA
      LEFT JOIN TAXDECL      TXDCL   ON TXDCL.TIPDOC = I.TIPDOC AND TXDCL.CODDOC = I.CODINTR AND TXDCL.CODDOC1 = I1.CODINTR1
      LEFT JOIN CONTRACT         CONTR   ON contr.codcontract = i1.codcontract' || coalesce(pJoinExt,'');

  CALL PRC_AL_CHECK('nartobj1');
  CALL PRC_AL_CHECK('nart1');
  CALL PRC_AL_CHECK('ntva1');
  CALL PRC_AL_CHECK('ntaxe1');

  DELETE FROM tmp_lst_intrari;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsertTMP, current_setting('PKG_LIST_BASE_INTRARI.pLISTID', true)::numeric, current_setting('PKG_LIST_BASE_INTRARI.pLISTVER', true)::numeric);
  PERFORM LIST_EXECUTE_IMMEDIATE(sUpdateTMP, current_setting('PKG_LIST_BASE_INTRARI.pLISTID', true)::numeric, current_setting('PKG_LIST_BASE_INTRARI.pLISTVER', true)::numeric);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert   , current_setting('PKG_LIST_BASE_INTRARI.pLISTID', true)::numeric, current_setting('PKG_LIST_BASE_INTRARI.pLISTVER', true)::numeric);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_intrari_insertsinteza</obj_name>
  <obj_hashval>98840257c817918e186c037eb6cc31e7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_intrari_insertsinteza(tmpname character varying, puserfields character varying, puseralias character varying, pnullalias character varying, pjoinext character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert    varchar;
  sInsertTMP varchar;
  sSold      varchar := ', 0 sold';
BEGIN
  --Florin 23.11.2022 - sinc. Oracle
  --Florin 07.08.2020
  --Florin 19.12.2020 - CIF_VALID cu un singur parametru
  IF current_setting('PKG_LIST_SELINTIES.vExtra2', true)::NUMERIC = 1 THEN
    sSold := ',
      CASE
        WHEN i.operat = 0 THEN 0
        WHEN i.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 = 1353
          WHERE g.tipdoc = i.tipdoc AND g.coddoc = i.codintr AND g.semnificatie = 100 )
      END sold';
  END IF;
  sInsertTMP := '
    INSERT INTO tmp_lst_intrsint
    SELECT
      i.codintr,
      SUM((CASE WHEN i.tipdoc IN (3) THEN (i1.pu - Coalesce(i1.tva,0) / i1.cant) ELSE i1.pu END)* i1.cant) val,
      SUM(Coalesce(i1.tva,0)) tva,
      SUM(i1.cant*i1.pretorig * Coalesce(i1.coefdiscmaj,1) * (CASE WHEN i.tipdoc IN (3) THEN (1 - CASE WHEN COALESCE(I1.PU,0) = 0 THEN 0 ELSE Coalesce(i1.tva,0) / (i1.cant * i1.pu) END) ELSE 1 END)) valint
     FROM intrari i INNER JOIN intrari1 i1 ON i1.codintr = i.codintr ' || COALESCE(current_setting('PKG_LIST_BASE_INTRARI.vFiltru', true),'') || '
    GROUP BY i.codintr';
  sInsert := '
    INSERT INTO ' || tmpName || '(
      NAV_CodDoc,NAV_TipDoc,
      PARTENER,DEN_LOCALIT,DEN_JUDET,DEN_ZONA,DEN_CLASEP,
      TIPDOC, TIPTVA, TIPTRANZ,
      PREFIXDOC,NRDOC,DATADOC,DOCUMENT,NRAVIZ,SERDOC,
      MARFA,DISCMAJ,PJ_DISC,
      VALOARE,VAL_TVA,VAL_CU_TVA,
      BLOCAT,DEN_MONEDA,CURS,TERMEN,OBS,
      ANDOC,LUNADOC,LUNA,
      SUBUNITATEA,CODFISC,CUICorect,NRINREG,
      EXCLUSPLATA,
      TRANSPORT,CONTRACT,
      SOLD,CURS_REF' || COALESCE(pUserFields,'') || ')
    SELECT
      i.codintr, i.tipdoc ,
      (Case When i.tipdoc=6 then ns.den_subunit When i.tipdoc=7 then ng.den_gest else np.den_part end), locsoc.den_localit, judsoc.den_judet, zonasoc.den_zona,ncp.den_clasep,
      (Case When i.tipdoc= 1 then ''Facturi'' When i.tipdoc=2 then ''Avize exped.'' When i.tipdoc= 3 then ''Chit. fisc.'' When i.tipdoc=   4 then ''Pers. fiz.'' When i.tipdoc= 5 then ''Importuri'' When i.tipdoc= 6 then ''Subunit.'' When i.tipdoc= 7 then ''Note predare'' When i.tipdoc= 9 then ''Fact. la avize'' end),
      (Case When i.tiptva=1 then ''Taxare normala'' When i.tiptva=2 then ''Taxare inversa'' When i.tiptva=3 then ''Tranzactie triunghiulara'' When i.tiptva=4 then ''Suspendare temporara'' end),
      (case when i.tipdoc = 5 then ''Import'' else (Case  When i.tiptranzactie=1 then ''Tranzactie interna'' When i.tiptranzactie=2 then ''Achizitie intracomunitara'' When i.tiptranzactie=3 then ''Import servicii'' end) end),
      i.prefixdoc, i.nrdoc, i.datadoc, i.prefixdoc||i.nrdoc||''/''||TO_CHAR(i.Datadoc,''dd.mm.yyyy''), i.nraviz, i.seriadoc,
      i1.val, (i.valdoc - i.tvadoc) - i1.val, (case when i1.val = i.valdoc - i.tvadoc then 0 when i1.val = 0 then 0 else ((i.valdoc - i.tvadoc)/i1.val - 1)*100 end),
      i.valdoc - i.tvadoc, i.tvadoc, i.valdoc,
      (Case  When i.blocat=1 then ''Da'' else ''Nu'' end), mon.simbol, (Case  When i.curs=NULL then 1 When i.curs=0 then 1 else i.curs end), t.termen, i.obs,
      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,
      nsub.den_subunit, fisc.codfiscal,
      (Case When cif_valid(FISC.CodFiscal::varchar) = 0 then ''NU'' else ''DA'' end), I.NRI,
      (Case When i.exclusplata=1 then ''DA'' else ''NU'' end),
      paut.nrinreg, contr.seriadoc||contr.nrdoc||''/''||to_char(contr.datadoc,''dd.mm.yyyy'')' || COALESCE(sSold,'') || COALESCE(current_setting('PKG_LIST_BASE_INTRARI.sCursRef', true),'') || coalesce(pUserAlias,'') || '
    FROM tmp_lst_intrsint I1
      LEFT JOIN INTRARI        I          ON I.CodIntr = I1.CodIntr
      LEFT JOIN TMP_UTILIZATOR UTILIZATOR ON utilizator.codutilizator = i.userid
      LEFT JOIN NPART          NP         ON np.codpart        = i.partener
      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       LOCSOC     ON locsoc.codlocalit = ssoc.codlocalit
      LEFT JOIN NTARI          TARASOC    ON LOCSOC.codtara    = TARASOC.codtara
      LEFT JOIN NJUDET         JUDSOC     ON judsoc.codjudet   = locsoc.codjudet
      LEFT JOIN NZONE          ZONASOC    ON zonasoc.codzona   = locsoc.codzona
      LEFT JOIN NPARTCODFISC   FISC       ON fisc.codpart      = i.partener AND fisc.principal = 1
      LEFT JOIN NCLASEP        NCP        ON ncp.codclasep     = np.codclasa
      LEFT JOIN NGEST          NG         ON ng.codgest        = i.codgestprod
      LEFT JOIN NSUBUNIT       NS         ON ns.codsubunit     = i.codsubunit
      LEFT JOIN NSUBUNIT       NSUB       ON nsub.codsubunit   = i.subunitatea
      LEFT JOIN NMONEDE        MON        ON mon.codmoneda     = Coalesce(i.moneda,0)
      LEFT JOIN NPARTTR        NPTR       ON nptr.codparttr    = i.delegat
      LEFT JOIN NPARCAUT       PAUT       ON PAUT.CODNPARCAUT  = Coalesce(I.CODAUTO,0)
      LEFT JOIN CONTRACT       CONTR      ON CONTR.CODCONTRACT = I.CODCONTRACT
      LEFT JOIN (
        SELECT g.coddoc, g.tipdoc, MAX(o.termen) termen, MAX(o.majorari) majorari
        FROM obligpif o INNER JOIN general g ON g.codgeneral = o.codgeneral
        WHERE o.termen IS NOT NULL AND o.semnificatie = 100
        GROUP BY g.coddoc, g.tipdoc) T on t.coddoc = i.codintr AND t.tipdoc = i.tipdoc ' || coalesce(pJoinExt,'');
  DELETE FROM tmp_lst_intrsint;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsertTMP, current_setting('PKG_LIST_BASE_INTRARI.pLISTID', true)::numeric, current_setting('PKG_LIST_BASE_INTRARI.pLISTVER', true)::numeric);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert   , current_setting('PKG_LIST_BASE_INTRARI.pLISTID', true)::numeric, current_setting('PKG_LIST_BASE_INTRARI.pLISTVER', true)::numeric);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_intrari_sql_tmp_lst_intrari</obj_name>
  <obj_hashval>78d929b39f000d1e18f2879db415f947</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_intrari_sql_tmp_lst_intrari(pfiltru character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 29.10.2025 - fixat 67145
  --Florin 07.05.2024 - fixat 61862
  --Adina 22.06.2021 - tichet 50624 - pus virgula ca separator la string_agg
  --Adina 02.04.2021 - alstart,alstop la ioart1
  --Adina 09.03.2021 - NTAXE1 cu AlStart ALStop
  --Florin 13.08.2020; Adina 03.11.2020 inlocuit =null cu is null
RETURN 'INSERT INTO tmp_lst_intrari
  SELECT
    i.codintr, i.tipdoc, Coalesce(ae.nrdoc,i.nraviz) nraviz, Coalesce(ae.delegat,i.delegat) delegat,
    i1.codintr1, i1.indexlocal, i1.tiplinie, i1.codobiect, i1.umsec, i1.gestact, i1.obs obsart, i1.addim, i1.codcentru, i1.codanalizanod,
    CASE WHEN Coalesce(i1.codauto,0) &lt;&gt; 0 THEN i1.codauto WHEN Coalesce(i.codauto,0) &lt;&gt; 0 THEN i.codauto ELSE 0 END codauto,
    CASE
      WHEN (i1.tiplinie = ''='') OR (ae1.codintr1 IS NOT NULL) THEN 0
      WHEN i1.tiplinie IN (''S'',''V'') THEN i1.contserv
      ELSE i1.contdiscount
    END codcont,
    CASE
      WHEN i1.tiplinie IN (''G'',''T'') AND i.tipdoc = 3 THEN (i1.restfact - Coalesce(i1.tva,0)) / i1.cant
      WHEN i1.tiplinie IN (''G'',''T'') THEN i1.restfact / i1.cant
      WHEN i.tipdoc = 3 THEN (i1.pu - Coalesce(i1.tva,0) / i1.cant)
      ELSE i1.pu
    END pu,
    CASE
      WHEN i1.tiplinie IN (''G'',''T'') THEN 0
      WHEN i1.pu = i1.pretorig THEN 0
      WHEN i.tipdoc = 3 THEN (i1.pu - Coalesce(i1.tva,0) / i1.cant) * i1.pretorig / i1.pu
      ELSE i1.pu - i1.pretorig
    END discu,
    ROUND(CASE
      WHEN COALESCE(dvi1.tva,i1.tva,0) = 0 THEN 0
      WHEN i1.tiplinie IN (''G'',''T'') AND i1.restfact = 0 THEN 0
      WHEN i1.tiplinie IN (''G'',''T'') AND i.tipdoc = 3 THEN i1.tva / (i1.restfact-i1.tva)
      WHEN i1.tiplinie IN (''G'',''T'') THEN COALESCE(dvi1.tva/(Case  When i.curs is NULL then 1 When i.curs=0 then 1 else i.curs end),i1.tva,0) / i1.restfact
      WHEN dvi1.pretimport*i1.cant = 0 THEN 0
      WHEN i1.pu * i1.cant = 0 THEN 0
      WHEN i.tipdoc = 3 AND i1.pu * i1.cant = i1.tva THEN 0
      WHEN i.tipdoc = 3 THEN i1.tva / (i1.pu * i1.cant-i1.tva)
      ELSE COALESCE(dvi1.tva/(dvi1.pretimport*i1.cant),i1.tva/(i1.pu*i1.cant),0)
    END,2) coef_tva, Coalesce(ila.cant,i1.cant) cant,
    CASE
      WHEN Coalesce(i1.cant,0) = 0 THEN 0
      WHEN Coalesce(dvi1.tva,0) = 0 THEN Coalesce(i1.tva,0)/i1.cant
      WHEN dvi1.pretoriginal = dvi1.pretimport THEN dvi1.tva/(Case  When i.curs is NULL then 1 When i.curs=0 then 1 else i.curs end)/i1.cant
      WHEN dvi1.pretimport &lt;&gt; 0 THEN dvi1.tva*dvi1.pretoriginal/dvi1.pretimport/(Case  When i.curs is NULL then 1 When i.curs=0 then 1 else i.curs end)/i1.cant
      ELSE 0
    END tvau,
    (Case When i1.tvaneded=3 then 1/2 When i1.tvaneded=1 then 1 else 0 end) + CASE WHEN Coalesce(i.tiptva,0) &lt;&gt; 4 THEN 0 WHEN Coalesce(i1.tvaneded,0) = 0 THEN 1-Coalesce(i.prorata,0)/100 WHEN i1.tvaneded = 3 THEN 1/2*(1-Coalesce(i.prorata,0)/100) ELSE 0 END coeftned,
    (Case when i1.tiplinie = ''='' then Coalesce(SUM(Coalesce(-l1.cant,Coalesce(nser.cantnir *
    (Case When ns.cantnir=0 then 1 else Coalesce(ns.cantfurn, 0)/ns.cantnir end),ns.cantfurn)) *
    (Case When ae1.cant is NULL then 1 When ae1.cant=0 then 1 else Coalesce(ila.cant,i1.cant)/ae1.cant end)),Coalesce(ila.cant,i1.cant))
      else Coalesce(ila.cant,i1.cant) end) cantrec,
    (Case When i1.tiplinie=''='' then ''Stoc'' When i1.tiplinie=''V'' then ''Avans'' else ''Serviciu'' end) tipart,
    SUM(Coalesce(-l1.cant,Coalesce(nser.cantnir*(Case When ns.cantnir=0 then 1 else Coalesce(ns.cantfurn, 0)/ns.cantnir end),ns.cantfurn)) * Coalesce(ns.pret - ns.adaos,0) *
    (Case  When ae1.cant IS NULL then 1 When ae1.cant=0 then 1 else Coalesce(ila.cant,i1.cant)/ae1.cant end)) valachiz,
    SUM(Coalesce(-l1.cant,Coalesce(nser.cantnir*(Case When ns.cantnir=0 then 1 else Coalesce(ns.cantfurn, 0)/ns.cantnir end),ns.cantfurn)) * Coalesce(ns.pret,0) *
    (Case  When ae1.canT IS NULL then 1 When ae1.cant=0 then 1 else Coalesce(ila.cant,i1.cant)/ae1.cant end)) valinreg,
    MAX(Coalesce(ns.pumaximal,0)) pumaximal,
    CASE MAX(COALESCE(ns.tipserie, 0))
    WHEN 1 THEN string_agg(s.serie, '', '' ORDER BY s.serie)
    WHEN 2 THEN string_agg(s.serie || ''('' || round(COALESCE(l1.cant, nser.cantnir), 0)::text || '')'', ''| '' ORDER BY
    s.serie)
      ELSE NULL
    END AS SERII,
    string_agg(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(Coalesce(-l1.cantum1, Coalesce(nser.cantum1,ns.cantum1)) * (Case  When ae1.cant IS NULL then 1 When ae1.cant=0 then 1 else Coalesce(ila.cant,i1.cant)/ae1.cant end)) cantum1, SUM(Coalesce(-l1.cantum2, Coalesce(nser.cantum2,ns.cantum2)) *
    (Case When ae1.cant IS NULL then 1 When ae1.cant=0 then 1 else Coalesce(ila.cant,i1.cant)/ae1.cant end)) cantum2,
    string_agg(n.datanir::varchar, '','') datanir,
    (SELECT x.codioart1 FROM ioart1 x WHERE x.codioart = ns.codioart AND (i.an*12+i.luna) BETWEEN x.ALStart and x.ALStop ) codioart1,
    (SELECT x.codpart1  FROM npart1 x WHERE x.codpart  = i.partener  AND (i.an*12+i.luna) BETWEEN x.ALStart and x.ALStop ) codpart1,
    Coalesce(ae.codcontract, i.codcontract, 0) codcontract,
    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,
      0
    ) codcontract1,
    0 codoferta, Coalesce((select pkg_oferta_GetCodOferta1.wme_result from pkg_oferta_GetCodOferta1(NULL, I1.CODOBIECT, I.DATADOC, I.PARTENER, I.CODLOCATIE, I.SUBUNITATEA, 51, I1.cant)), 0) codoferta1,
    0 codcomanda, Coalesce((SELECT ilcom.codliniecomanda FROM intrlink ilcom WHERE ilcom.codintr1 = Coalesce(ae1.codintr1, i1.codintr1) AND ilcom.codliniecomanda IS NOT NULL), 0) codcomanda1,
    ( SELECT Coalesce(SUM(J1.VALOARE),0)
      FROM JURNAL1 J1 INNER JOIN NTAXE1 TT1 ON TT1.CODTAXA = J1.CODDESCRC
      WHERE J1.TIPCONTC = 900 AND J1.CODDOC = I.CODINTR AND J1.TIPDOC = I.TIPDOC AND J1.INDEXLOCAL = I1.CODINTR1
        AND TT1.ALSTART &lt;= I.AN *12+ I.LUNA
        AND TT1.ALSTOP  &gt;= I.AN *12+ I.LUNA
        AND Coalesce(TT1.STOPAJ,0) = 1
    ) / CASE WHEN i1.cant = 0 THEN 1 ELSE i1.cant END TaxaStopajU
  FROM intrari i
    INNER JOIN intrari1      i1   ON i1.codintr          = i.codintr
    LEFT JOIN intrlink       il   ON il.codintr1         = i1.codintr1 AND il.codlinieaviz IS NOT NULL
    LEFT JOIN intrasteptlink ila  ON ila.codliniefactura = i1.codintr1 AND Coalesce(i.tipfactura, 0) = 9
    LEFT JOIN intrari1       ae1  ON ae1.codintr1        = COALESCE(ila.codintr1, il.codlinieaviz)
    LEFT JOIN intrari        ae   ON ae.codintr          = ae1.codintr
    LEFT JOIN dvi                 ON dvi.codintr         = i.codintr
    LEFT JOIN dvi1                ON dvi1.coddvi         = dvi.coddvi AND dvi1.codintr1 = i1.codintr1
    LEFT JOIN livr1          l1   ON l1.codintr1         = i1.codintr1
    LEFT JOIN nirstoc        ns   ON ns.codobiect        = i1.codobiect
                                      AND (((l1.codlivr1 IS NOT NULL) AND (ns.codnirstoc = l1.codnirstoc)) OR
                                            ((l1.codlivr1 IS NULL) AND ((ns.codintr1 = Coalesce(ae1.codintr1,i1.codintr1)) OR (ns.coddvi1 = dvi1.coddvi1))))
    LEFT JOIN nir            n    ON n.codintr  = Coalesce(ae.codintr, i.codintr) AND n.codnir = ns.codnir
    LEFT JOIN nirser         nser ON (((l1.codlivr1 IS NOT NULL) AND (nser.codnirser = l1.codnirser)) OR ((l1.codlivr1 IS NULL)     AND (nser.codnirstoc = ns.codnirstoc)) )
    LEFT JOIN nserii         s    ON s.codserie = nser.codserie' || coalesce(pFiltru,'') || '
  GROUP BY
    i.codintr, i.tipdoc, i.delegat, ae.delegat, i.nraviz, ae.nrdoc, i.codauto, i.an, i.luna, i.curs, i.datadoc, i.partener, i.codlocatie, i.subunitatea, i.tiptva, i.prorata,
    i1.codintr1, i1.indexlocal, i1.tiplinie, i1.codobiect, i1.umsec, i1.tva, i1.pretorig, i1.pu, ila.cant, i1.cant, i1.coefdiscmaj,
    i1.gestact, i1.contserv, i1.contdiscount, i1.obs, i1.restfact, i1.codauto, i1.addim, i1.codcentru, i1.codanalizanod, i1.tvaneded,
    dvi1.tva, dvi1.pretimport, dvi1.pretoriginal, ae1.codintr1, ns.codioart, ae1.codcontract1, i1.codcontract1,ae.codcontract,i.codcontract';
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_jurnvanz_pregateste_tmp_lst_tvaincas</obj_name>
  <obj_hashval>3b6576eed2d9dc541e6748a670b93d85</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_jurnvanz_pregateste_tmp_lst_tvaincas(alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsAux1   TEXT;
  sInsAux2   TEXT;
  sDebug     TEXT;
  sAnLista   TEXT    := coalesce(current_setting('PKG_LIST_BASE_JURNVANZ.vAnLista',   true), '0');
  sLunaLista TEXT    := coalesce(current_setting('PKG_LIST_BASE_JURNVANZ.vLunaLista', true), '0');
  sTip       TEXT    := coalesce(current_setting('PKG_LIST_BASE_JURNVANZ.vTip',       true), '0');
  sSubunit   TEXT    := coalesce(current_setting('PKG_LIST_BASE_JURNVANZ.vSubunit',   true), '0');
  vSubunit   NUMERIC := case when sSubunit is null or sSubunit = '' then sSubunit::numeric else 0 end;
  sAnLunaIni TEXT    := coalesce(current_setting('PKG_LIST_BASE_JURNVANZ.vAnLunaIni', true), '0');
  sDRTVAInc  TEXT    := coalesce(current_setting('PKG_LIST_BASE_JURNVANZ.sDRTVAInc',  true), '');
  sCondSub   TEXT;
begin
  --Stef  25.01.2022
  sCondSub := PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', NULL, NULL, vSubunit);
  sDebug :=
    'DO $$'||Chr(10)||
    'BEGIN'||Chr(10)||
    '  perform pkg_list_base_jurnvanz_setperioada(' ||sAnLista|| ',' || sLunaLista || ',' || sTip || ',' || sSubunit || ');'||Chr(10)||
    'END$$;';
  PERFORM PKG_GLOBALS_CheckDebugMode(sDebug, aLISTID, aLISTVER);
  sInsAux1 :=
  'INSERT INTO TMP_LST_TVAINCAS(
      coddoc, tipdoc, nrdoc, prefixdoc, seriadoc, datadoc, datastingere, valstinsa, datastop, coeftva, tipstingere, prefixstingere, nrstingere,
      coefdoc, orddoc, countdoc, coefplata, restdoc)
    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
      FROM IESIRI I INNER JOIN IESIRI1 i1 ON I1.CODIES = I.CODIES
      WHERE I.INITIALIZARI = 1
      GROUP BY I.CODIES
    ),
    S AS (
      SELECT
        I.CODIES, I.TIPDOC, COALESCE(II.VALDOC,I.VALDOC) VALDOC,
        SUM(PKG_LIST_BASE_JURNVANZ_getStinsDoc(O.CODOBLIGPIF,'||sAnLunaIni||') * CASE WHEN O.VALOARE &lt; 0 THEN -1 ELSE 1 END ) STINSDOC
      FROM IESIRI I
        INNER JOIN GENERAL  G ON G.CODDOC     = I.CODIES AND G.TIPDOC = I.TIPDOC
        INNER JOIN OBLIGPIF O ON O.CODGENERAL = G.CODGENERAL
        LEFT  JOIN         II ON II.CODIES    = I.CODIES
      WHERE I.AN*12+I.LUNA &lt; '||sAnLunaIni||'
        AND I.TVAINCASARE = 1
        AND I.TIPDOC IN (19, 26)
        AND COALESCE(II.VALDOC, I.VALDOC) &lt;&gt; 0
        AND G.DataTVA &gt;= To_Date(''' || sDRTVAInc || ''',''dd.mm.yyyy'')
        AND NOT EXISTS (SELECT 1 FROM TMP_PER_TVAColectat T WHERE G.DataTVA BETWEEN T.Data1 AND T.Data2) '||sCondSub||'
      GROUP BY I.CODIES, I.TIPDOC, COALESCE(II.VALDOC,I.VALDOC)),
    TVAI AS (
      SELECT
        CODDOC, TIPDOC, NRDOC, PREFIXDOC, SERIADOC, DATADOC, DATASTINGERE, VALSTINSA, DATASTOP, COEFTVA, TIPSTINGERE, PREFIXSTINGERE, NRSTINGERE,
        Row_NUMBER() OVER (PARTITION BY CODDOC, TIPDOC ORDER BY DATASTINGERE) OrdDoc,
        COUNT(1) OVER (PARTITION BY CODDOC, TIPDOC) CountDoc,
        SUM(CoefTva) OVER (PARTITION BY CODDOC, TIPDOC ORDER BY DATASTINGERE ROWS UNBOUNDED PRECEDING) CoefPlata
      FROM TMP_TVAINCAS
      WHERE COEFTVA &lt;&gt; 0)
    SELECT
      S.CODIES, S.TIPDOC, TVAI.NRDOC, TVAI.PREFIXDOC, TVAI.SERIADOC, TVAI.DATADOC, TVAI.DATASTINGERE, TVAI.VALSTINSA, TVAI.DATASTOP, TVAI.COEFTVA, TVAI.TIPSTINGERE, TVAI.PREFIXSTINGERE, TVAI.NRSTINGERE,
      1 - (S.STINSDOC/S.VALDOC) COEFDOC, TVAI.ORDDOC, TVAI.COUNTDOC, COALESCE(TVAI.COEFPLATA,0), ABS(S.VALDOC-S.STINSDOC)
    FROM S LEFT JOIN TVAI ON TVAI.CODDOC = S.CODIES AND TVAI.TIPDOC = S.TIPDOC';
  sInsAux2 := 'INSERT INTO TMP_LST_TVAINCAS(
      CodDoc, TipDoc, NrDoc, PrefixDoc, SeriaDoc, DataDoc, DataStingere, ValStinsa, DataStop, CoefTVA, TipStingere, PrefixStingere, NrStingere,
      CoefDoc,
      OrdDoc,
      CountDoc,
      CoefPlata)
    SELECT
      CodDoc, TipDoc, NrDoc, PrefixDoc, SeriaDoc, DataDoc, DataStingere, ValStinsa, DataStop, CoefTVA, TipStingere, PrefixStingere, NrStingere,
      1 CoefDoc,
      Row_NUMBER() OVER (PARTITION BY CODDOC, TIPDOC ORDER BY DATASTINGERE) OrdDoc,
      COUNT(1) OVER (PARTITION BY CODDOC, TIPDOC) CountDoc,
      SUM(CoefTva) OVER (PARTITION BY CODDOC, TIPDOC ORDER BY DATASTINGERE ROWS UNBOUNDED PRECEDING) CoefPlata
    FROM TMP_TVAINCAS
    WHERE COEFTVA &lt;&gt; 0';
  sDebug :=
    'DO $$'||Chr(10)||
    'BEGIN'||Chr(10)||
    '  DELETE FROM TMP_LST_TVAINCAS;'||Chr(10)||
    '  DELETE FROM TMP_JURNAL1;'||Chr(10)||
    '  DELETE FROM TMP_TVAINCAS;';
  IF sAnLista &gt; '2012' THEN
    sDebug := sDebug||Chr(10)||
    '  PERFORM PKG_INCHIDERI_MAKE_TMP_StingereTVACole(1);'||Chr(10)||
    '  PERFORM PKG_INCHIDERI_MAKE_TMP_InchidereTVACole(1);'||Chr(10)||Chr(10)||

    '  DELETE FROM TMP_TVAINCAS T WHERE NOT EXISTS (SELECT J1.CODDOC FROM TMP_JURNAL1 J1 WHERE J1.TIPDOC = T.TIPDOC AND J1.CODDOC = T.CODDOC);'||Chr(10)||Chr(10)||

    '  UPDATE TMP_TVAINCAS SET TIPSTINGERE = -81 WHERE TIPSTINGERE = 81;'||Chr(10)||Chr(10)||

    '  INSERT INTO TMP_TVAINCAS(coddoc, tipdoc, nrdoc, prefixdoc, seriadoc, datadoc, datastingere, valstinsa, datastop, coeftva, tipstingere, prefixstingere, nrstingere)'||Chr(10)||
    '  SELECT coddoc, tipdoc, nrdoc, prefixdoc, seriadoc, datadoc, datastingere, Sum(valstinsa), datastop, Sum(coeftva), -tipstingere, prefixstingere, nrstingere'||Chr(10)||
    '  FROM TMP_TVAINCAS'||Chr(10)||
    '  WHERE TIPSTINGERE = -81'||Chr(10)||
    '  GROUP BY coddoc, tipdoc, nrdoc, prefixdoc, seriadoc, datadoc, datastingere, datastop, tipstingere, prefixstingere, nrstingere;'||Chr(10)||Chr(10)||

    '  DELETE FROM TMP_TVAINCAS WHERE TIPSTINGERE = -81;'||Chr(10)||Chr(10)||
    '  ' || sInsAux1 || ';'||Chr(10)||Chr(10)||

    '  DELETE FROM TMP_TVAINCAS     WHERE CODDOC IN (SELECT CODDOC FROM TMP_LST_TVAINCAS);'||Chr(10)||Chr(10)||

    '  DELETE FROM TMP_LST_TVAINCAS WHERE COEFPLATA = 0 AND RESTDOC &lt; 0.01;'||Chr(10)||Chr(10)||

    '  ' || sInsAux2 || ';';
  END IF;
  sDebug := sDebug||Chr(10)||
    'END$$;';
  PERFORM LIST_EXECUTE_IMMEDIATE(sDebug, aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_jurnvanz_setjoinuri</obj_name>
  <obj_hashval>765af7da5ba780cfdcf66444184e12bc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_jurnvanz_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 28.07.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_JURNVANZ.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_lansetichete_processlist</obj_name>
  <obj_hashval>ac81d32151860d20c184e87d7c5bed1f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_lansetichete_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 := '';
  sSelectDC1       varchar := '';
  gSuplCols        VARCHAR := 'comanda1 c1, nartobj nao, nart na, nartcli acli, nlocalit LocS, nlocalit LocL';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vNrAtrib        NUMERIC := current_setting('PKG_LIST_BASE_LANSETICHETE.vNrAtrib', true)::numeric;
BEGIN
  --Florin 10.04.2024 - getAdresa
  --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_LANSETICHETE.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 ||
               ', PKG_LIST_BASE_LANSETICHETE_DenAtrib(c1.codobiect,' || k::varchar ||'),
                  PKG_LIST_BASE_LANSETICHETE_ValAtrib(c1.codobiect,' || k::varchar ||'),
                  PKG_LIST_BASE_LANSETICHETE_CodAtrib(c1.codobiect,' || k::varchar ||')';


    sSelectDC1 := sSelectDC1 ||
               ', PKG_LIST_BASE_LANSETICHETE_DenAtrib(codobiect,' || k::varchar ||'),
                  PKG_LIST_BASE_LANSETICHETE_ValAtrib(codobiect,' || k::varchar ||'),
                  PKG_LIST_BASE_LANSETICHETE_CodAtrib(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,Cant,IndexLocal ' || sInsertDC || gUserFields || ')';

  sSelect :=
  ' WITH RECURSIVE aa AS
    (
      SELECT 1 NrColet
      UNION ALL
      SELECT aa.NrColet+1 FROM aa WHERE aa.NrColet&lt;10000
    )
    SELECT
      x.DENUMIRE, x.CODEXTERNART, x.INDEXLOCALCOL || ''/'' || (case when x.NRMAX= 0 then 1 else x.NRMAX end) AS NUMARCOLET,
      x.CLIENT, x.CODCLIENT,  x.IDCOLET, GETFIRMA_ID(),  x.NRCOMANDA, x.SediuClient, x.ObsComanda, x.PozaClient,
       x.NrComandaInt,x.CodIntern,x.An,x.Formatie,x.DataCmdInt,x.Gest,x.Sapt,x.Schimb,x.CodExtern,x.Nivel, X.AdresaClient,
      X.Adresalivrare, x.DenLaClient,x.Cant, x.nrcolet ' || sSelectDC1 || gUserAlias ||
  ' FROM  (SELECT
              C1.codcomanda CodComandaCI,
              c1.codcomanda1 CodComandaCI1,
              cc1.codcomanda CodComandaCC,
              cc1.codcomanda1 CodComandaCC1,
              O.CODOBIECT,
              O.DENUMIRE,
              CC.NRDOC AS NRCOMANDA,
              A.CODEXTERNART,
              coalesce(CO.INDEXLOCAL, 1) AS INDEXLOCALCOL,
              (SELECT COUNT(*) FROM NARTOBJCOLET WHERE CODOBIECT = O.CODOBIECT) AS NRMAX,
              P.DEN_PART AS CLIENT,
              P.CODEXTERN AS CODCLIENT,
              CO.IDCOLET,
              AG.OBS AS SEDIUCLIENT,
              CC.OBS AS OBSCOMANDA,
              P.POZA AS POZACLIENT,
              CC.NRDOC AS NRCOMANDAINT,
              O.CODINTERN,
              substr(C.An::varchar,3,2) an,
              FM.den_formatie formatie,
              C.DataDoc DataCmdInt,
              g.den_gest gest,
              to_char(c.datadoc, ''WW'')::numeric sapt,
              c.schimb,
              o.codextern,
              coalesce(pnod.nivel,0) nivel,
              fnc_GetAdresa(ASS.sector, ASS.strada, ASS.nr1, ASS.nr2, ASS.bloc, ASS.scara, ASS.etaj, ASS.apart, ASS.codpostal) AdresaClient,
              fnc_GetAdresa(AG.sector, AG.strada, AG.nr1, AG.nr2, AG.bloc, AG.scara, AG.etaj, AG.apart, AG.codpostal) AdresaLivrare,
              COALESCE(ac.denumire,ntrad.denumiretrad,nao.denumire) denlaclient,
              ASS.CodLocalit lags,
              AG.CodLocalit lagl,
              1 Cant, Y.NrColet
           FROM
                LANSARE L
                INNER JOIN LANSARE1 L1           ON L1.CODLANSARE = L.CODLANSARE
                INNER JOIN comanda1 c1           ON L1.CODCMD1    = c1.CODCOMANDA1
                INNER JOIN NARTOBJ O             ON O.CODOBIECT   = c1.codobiect
                INNER JOIN NART A                ON a.codarticol  = o.codarticol
                inner join comanda c             on c1.codcomanda = c.codcomanda
                INNER JOIN aa Y                  ON Y.NrColet &lt;= coalesce(c1.cantacceptat, 0)
                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 AND L.CODLANSARE = LANS1.CODLANSARE
                left  join proiectnod pnod       on lans1.codproiectnod = pnod.codproiectnod AND PNOD.NODORIGINAL = 0
                LEFT  OUTER JOIN CMDLINK K       ON K.CODCOMANDA1   = C1.CODCOMANDA1
                LEFT  OUTER JOIN COMANDA1 CC1    ON CC1.CODCOMANDA1 = K.CODLINIECOMANDA
                LEFT  OUTER JOIN COMANDA  CC     ON CC.CODCOMANDA   = CC1.CODCOMANDA
                LEFT  OUTER JOIN NPART    P      ON P.CODPART       = CC.PARTENER
                LEFT  OUTER JOIN NAGENDA ASS     ON ASS.CODPART     = CC.PARTENER AND ASS.SEDIUSOCIAL IN (4,5,6,7)
                LEFT  OUTER JOIN NAGENDA AG      ON AG.CODAGENDA    = CC.CODLOCATIE
                LEFT  JOIN nartcli ac            ON ac.codobiect    = c1.codobiect AND ac.codpart = cc.partener
                left  join nartobj nao           on nao.codobiect   = c1.codobiect
                LEFT  JOIN nagenda nag           ON nag.codagenda   = cc.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 = c1.codobiect
                LEFT  OUTER JOIN NARTOBJCOLET CO ON CO.CODOBIECT    =  O.CODOBIECT' || gSuplJoins || '
           WHERE L.CODLANSARE = ' || coalesce(current_setting('PKG_LIST_BASE_LANSETICHETE.vCodDoc', true),'') || '
           ORDER BY O.CODOBIECT, coalesce(CO.INDEXLOCAL, 1)
          ) x
            left join comanda1 c1   on x.codcomandaci1 = c1.codcomanda1
            left join nartobj nao   on x.codobiect     = nao.codobiect
            left join nart na       on nao.codarticol  = na.codarticol
            left join nlocalit LocS on x.lags = LocS.CodLocalit
            left join nlocalit LocL on x.lagl = LocL.CodLocalit    ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_lansz_processlist</obj_name>
  <obj_hashval>3517d93d96ecdb3d4c6dddbb92f8e390</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_lansz_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sString         varchar;
  vUserID         numeric;
  gSuplCols        VARCHAR := 'nartobj obj, prodcomp pc';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vSetimanaIni    NUMERIC := current_setting('PKG_LIST_BASE_LANSZ.vSetimanaIni', true)::NUMERIC;
  vSetimanaFin    NUMERIC := current_setting('PKG_LIST_BASE_LANSZ.vSetimanaFin', true)::NUMERIC;
  vAn              NUMERIC := current_setting('PKG_LIST_BASE_LANSZ.vAn'         , true)::NUMERIC;
BEGIN
  --Adina 17.03.2021 - sinc.Oracle
  --Adina 08.01.2021 tichet 42056 - modificat DataStart si DataStop
  --Adina 14 septembrie 2020
  vUserID := current_setting('PKG_GLOBALS.USERID', true)::numeric;
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_LANSZ.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  DELETE FROM tmp_lansz;
  INSERT INTO TMP_LANSZ (CODLANSZ, CODGEST, CODPLANIFPROD, SUBUNITATEA, OPERAT, ANULAT, BLOCAT, OBS, DATASTART, DATASTOP, AN, LUNA, SAPTAMANA, Finalizat)
  SELECT LZ.CODLANSZ, LZ.CODGEST, LZ.CODPLANIFPROD, LZ.SUBUNITATEA, LZ.OPERAT, LZ.ANULAT, LZ.BLOCAT, LZ.OBS,
         --trunc(trunc(to_date(LZ.AN,'yyyy'),'yyyy'),'iw') + (LZ.Saptamana - 1) * 7,  -- Oracle
         date_trunc('week',date_trunc('year', to_date(LZ.AN::varchar,'yyyy')))::date + (LZ.Saptamana - 1)::integer * 7,
         --trunc(trunc(to_date(LZ.AN,'yyyy'),'yyyy'),'iw') + LZ.Saptamana  * 7 - 1,  -- Oracle
         date_trunc('week',date_trunc('year', to_date(LZ.AN::varchar,'yyyy')))::date + (LZ.Saptamana * 7)::integer - 1,
         LZ.AN, LZ.LUNA, LZ.Saptamana, LZ.FINALIZAT
  FROM LANSZ LZ
  WHERE lZ.saptamana BETWEEN vSetimanaIni AND vSetimanaFin and  lZ.an = vAn;

  DELETE FROM lansz1_manevra1_l WHERE userid = vUSERID;
  INSERT INTO lansz1_manevra1_l(codlansz1, Userid)
  SELECT l1.codlansz1, vUserID
  FROM lansz1 l1
  WHERE EXISTS (SELECT tmp.codlansz FROM tmp_lansz tmp WHERE tmp.codlansz = l1.codlansz) and  l1.codformatie &gt; 0 and  l1.schimb &gt; 0;

  DELETE FROM lansz1_manevra_l WHERE userid = vUserID;
  INSERT INTO lansz1_manevra_l(
      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,
      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, UserID)
  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.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, vUserID
  FROM   lansz1_manevra1_l        m1
        INNER JOIN lansz1        l1   ON  l1.codlansz1       = m1.codlansz1
        INNER JOIN lansz         l    ON  l.codlansz         = l1.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 = l.subunitatea
        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
  WHERE m1.userid = vuserid;

  DELETE FROM lansz1_manevra_l ll1
  WHERE COALESCE(ll1.report, 0) + COALESCE(Ll1.LUNI, 0) + COALESCE(Ll1.MARTI, 0) + COALESCE(Ll1.MIERCURI, 0) + COALESCE(Ll1.JOI, 0) + COALESCE(Ll1.VINERI, 0)
        + COALESCE(Ll1.SAMBATA, 0) + COALESCE(Ll1.DUMINICA, 0) + COALESCE(LL1.CODCMD1_LUNI, 0) + COALESCE(LL1.CODCMD1_MARTI, 0)
        + COALESCE(LL1.CODCMD1_MIERCURI, 0) + COALESCE(LL1.CODCMD1_JOI, 0) + COALESCE(LL1.CODCMD1_VINERI, 0) + COALESCE(LL1.CODCMD1_SAMBATA, 0)
        + COALESCE(LL1.CODCMD1_DUMINICA, 0) = 0 AND ll1.userid = vuserid;

  DELETE FROM lansz1_manevra1_l WHERE USERID = VUSERID;
  INSERT INTO lansz1_manevra1_l(CODOBIECT, CODRETETA, TOTALLANSAT, USERID, CODLANSZ, REPORT)
  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, TMP.CODLANSZ, SUM(L1.REPORT)
  FROM   TMP_LANSZ TMP
        INNER JOIN LANSZ  L  ON  TMP.CODLANSZ &lt;&gt; L.CODLANSZ AND  TMP.SAPTAMANA = L.SAPTAMANA AND  TMP.AN = L.AN
        INNER JOIN LANSZ1 L1 ON  L1.CODLANSZ  = L.CODLANSZ
  WHERE L1.CODFORMATIE &gt; 0 AND  L1.SCHIMB &gt; 0
  GROUP BY L1.CODOBIECT, L1.CODRETETA, TMP.CODLANSZ;

  UPDATE lansz1_manevra_l TMP
  SET ALTE = (SELECT M.TOTALLANSAT
              FROM lansz1_manevra1_l M
              WHERE M.CODOBIECT = TMP.CODOBIECT and  M.CODRETETA = TMP.CODRETETA AND  M.CODLANSZ = TMP.CODLANSZ and  m.userid = vuserid
             )
  WHERE USERID = VUSERID;

  UPDATE lansz1_manevra_l TMP
  SET REPORTALTE = (SELECT M.REPORT
                    FROM lansz1_manevra1_l M
                    WHERE M.CODOBIECT = TMP.CODOBIECT and  M.CODRETETA = TMP.CODRETETA AND  M.CODLANSZ = TMP.CODLANSZ and  m.userid = vuserid
                   )
  WHERE USERID = VUSERID;

  UPDATE lansz1_manevra_l
  SET 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_l SET luni           = NULL WHERE luni          = 0;
  UPDATE lansz1_manevra_l SET lans_luni     = NULL WHERE lans_luni     = 0;
  UPDATE lansz1_manevra_l SET marti         = NULL WHERE marti         = 0;
  UPDATE lansz1_manevra_l SET lans_marti     = NULL WHERE lans_marti    = 0;
  UPDATE lansz1_manevra_l SET miercuri       = NULL WHERE miercuri      = 0;
  UPDATE lansz1_manevra_l SET lans_miercuri = NULL WHERE lans_miercuri = 0;
  UPDATE lansz1_manevra_l SET joi           = NULL WHERE joi           = 0;
  UPDATE lansz1_manevra_l SET lans_joi       = NULL WHERE lans_joi      = 0;
  UPDATE lansz1_manevra_l SET vineri         = NULL WHERE vineri        = 0;
  UPDATE lansz1_manevra_l SET lans_vineri   = NULL WHERE lans_vineri   = 0;
  UPDATE lansz1_manevra_l SET sambata       = NULL WHERE sambata       = 0;
  UPDATE lansz1_manevra_l SET lans_sambata   = NULL WHERE lans_sambata  = 0;
  UPDATE lansz1_manevra_l SET duminica       = NULL WHERE duminica      = 0;
  UPDATE lansz1_manevra_l SET lans_duminica = NULL WHERE lans_duminica = 0;
  UPDATE lansz1_manevra_l SET nextweek       = NULL WHERE nextweek      = 0;
  UPDATE lansz1_manevra_l SET total         = NULL WHERE total         = 0;
  UPDATE lansz1_manevra_l SET alte           = NULL WHERE alte          = 0;
  UPDATE lansz1_manevra_l SET lastweek       = NULL WHERE lastweek      = 0;
  UPDATE lansz1_manevra_l SET refweek       = NULL WHERE refweek       = 0;
  UPDATE lansz1_manevra_l SET report         = NULL WHERE report        = 0;
  UPDATE lansz1_manevra_l SET reportalte     = NULL WHERE reportalte    = 0;

  sString :=
  'insert into ' || tmpName || '(
     CODLANSZ,
     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
     L.CODLANSZ,
     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)::integer * 7, ''dd.mm.yyyy'') DataStart,
     to_char(date_trunc(''week'',date_trunc(''year'', to_date(l.AN::varchar,''yyyy'')))::date + (l.Saptamana * 7)::integer - 1, ''dd.mm.yyyy'') DataStop,
     g.den_gest SECTIE,
     L1.REPORT,
     L1.REPORTALTE ' || gUserAlias || '
  from lansz1_manevra_l  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 l1.userid = getuserid() ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sstring, aListID, aListVer);

  --DELETE FROM tmp_lansz;
  --DELETE FROM lansz1_manevra_l  WHERE userid = vuserid;
  --DELETE FROM lansz1_manevra1_l WHERE userid = vuserid;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_livrintrdoc_processlist</obj_name>
  <obj_hashval>7c45ac089936fde5155a99d9d2a4fee9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrintrdoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSelect         varchar := '';
  vWhere           varchar := '';
  sPMP             varchar := '';
  sInsertUMA       varchar := '';
  sSelectUMA       varchar := '';
  sJoinUMA         varchar := '';
  gSuplCols        VARCHAR := 'intrari i, nartobj nao, num1 um, ngest ng, nlocatii nl, doccarnete dc, num1 um1, num1 um2, npart prod, npart furn, nclasea ca, ioart io, ioart1 io1, ncont nc, nartobj1 nao1';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 05.04.2021 - alstart, alstop
  --Adina 13.10.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARI1'  , 'I1'  , 'I1.CODINTR1 = LG.CODINTR1'     , 1);
  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_LIVRINTRDOC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF  current_setting('PKG_LIST_BASE_LIVRINTRDOC.vCodGest', true)::numeric &gt;= 0 THEN
    vWhere := '
        AND coalesce(lv.gest,n.gest) = ' || coalesce(current_setting('PKG_LIST_BASE_LIVRINTRDOC.vCodGest', true),'');
  END IF;

  IF (getANCURENT() * 12 + getLUNACURENTA()) &lt; (getANLUCRU() * 12 + getLUNALUCRU()) THEN
    sPMP := ',
    (case when io1.mg=3 then pkg_PMP_GET_PMP_LEI(lg.codobiect,i.subunitatea,i.an,i.luna) else NULL end),
    (case when io1.mg=3 then pkg_PMP_GET_PMP_VALUTA_FROM_VAR() else NULL end), lg.pmpdoc, lg.pmpvalutadoc ';
  ELSE
    sPMP := ',
    lg.pmp, lg.pmpvaluta, lg.pmpdoc, lg.pmpvalutadoc ';
  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 sInsertUMA, sSelectUMA, sJoinUMA
  FROM PKG_LIST_BASE_UTILS_UMA_UTILS('lg.cant', 'lg.codobiect', sInsertUMA, sSelectUMA, sJoinUMA,NULL);

  sInsert :=
  'INSERT INTO ' || TMPNAME || ' (
    ART, UM, CANTDOC, CANTLIVR,
    PACH, PINREG, PVANZ,
    VALACH, VALINREG, VALVANZ,
    GESTIUNE, LOCATIE, NRLIVR, DATALIVR, DENCARNET, SIMBCARNET, SERCARNET, OBSLIVR, DATAEXP, DATAPROD, CODINTERN, CODEXTERN,
    DENCLASAA, SIMBCLASAA, MASA, VOLUM, PRODUCATOR, FURNIZOR, UM1, UM2, CANT1, CANT2,
    TIPSERIE, SERII, SER, DENIOART, SIMBCONT,
    PREFIXDOC, NRDOC, DATADOC, NRCERTIF, PUMAXIMAL, D1, D2, D3, DENCLASEAS, NRCOM, DATACOM, OBSDOC, CUSTODIE, CENTRUCOST,NIR,
    PMP, PMPVALUTA, PMPDOC, PMPVALUTADOC' || coalesce(sInsertUMA,'') || gUserFields || ' )';

  sSelect := '
  WITH
    LG AS (
      SELECT
        i.codintr, i1.codintr1, i1.indexlocal, i1.codobiect, coalesce(lv.gest, n.gest) gest, ns.codlocatie, l1.umsec,
        i1.pu, i1.cant canti, i1.obs obsdoc, l.carnetlivr, l.nrlivr, l.datalivr, l.obs obslivr, i1.codcentru,
        coalesce(ns.codioart,lv.codioart) codioart, ns.furn, ns.codgestprod gestfurn,
        SUM(coalesce(lv.pretinreg,ns.pret)*l1.cant) valinreg,
        SUM(coalesce(lv.pretachiz,ns.pret - ns.adaos)*l1.cant) valachiz,
        sum(l1.cant) cant, sum(l1.cantum1) cantum1, sum(l1.cantum2) cantum2, ns.d1, ns.d2, ns.d3,
        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||''(~#''||l1.cant::varchar||''#~)'' order by s.serie))
          ELSE NULL
        END SERII,
        fnc_array_to_vc3200(array_agg(DISTINCT s.serie)) ser,
        coalesce(i1.pumaximal,max(coalesce(ns.pumaximal,0))) pumaximal,
        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 to_char(nser.dataprod,''dd.mm.yyyy''),'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''') dp,
        i1.nrcertif,
        (case ns.tipserie when 1 then ''serie pe bucata'' when 2 then ''serie pe lot'' else ''fara serie'' end) tipserie,
        max(l1.pmp) pmp, max(l1.pmpvaluta) pmpvaluta, max(l1.pmpdoc) pmpdoc, max(l1.pmpvalutadoc) pmpvalutadoc,
        string_agg(DISTINCT N.NRNIR::varchar,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''') nir
      FROM   intrari i
            INNER JOIN intrari1 i1   ON i1.codintr     = i.codintr
            INNER JOIN nartobj  nao  ON nao.codobiect  = i1.codobiect
            INNER JOIN livr     l    ON l.codintr      = i1.codintr
            LEFT  JOIN dvi1          ON dvi1.codintr1  = i1.codintr1
            LEFT  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
            LEFT  JOIN nirser   nser ON nser.codnirser = l1.codnirser
            LEFT  JOIN nserii   s    on s.codserie     = nser.codserie
      WHERE (l1.codintr1 = i1.codintr1 OR l1.coddvi1 = dvi1.coddvi1)
            AND L.CODINTR = ' || coalesce(current_setting('PKG_LIST_BASE_LIVRINTRDOC.vCodIntr', true)::varchar ,'') || coalesce(vWhere,'') || '
      GROUP BY
            i.codintr, i1.codintr1, i1.indexlocal, i1.codobiect, i1.cant, i1.pu, i1.pumaximal, i1.nrcertif, i1.obs,  i1.codcentru,
            l.carnetlivr, l.nrlivr, l.datalivr, l.obs, l1.umsec, lv.codioart, lv.gest,
            ns.codlocatie, ns.codioart, ns.furn, ns.codgestprod, ns.tipserie, n.gest, ns.d1, ns.d2, ns.d3
  )
  SELECT
    nao.denumire, um.den_um1, lg.canti / um.paritate, lg.cant/um.paritate,
    lg.valachiz*um.paritate/lg.cant, lg.valinreg*um.paritate/lg.cant, lg.pu*um.paritate, lg.valachiz, lg.valinreg, lg.pu * lg.cant,
    ng.den_gest, nl.denumire, lg.nrlivr, lg.datalivr, dc.denumire, dc.simbol, dc.serie, lg.obslivr, lg.tg, lg.dp, nao.codintern, nao.codextern,
    ca.den_clasea, ca.simbol, nao.masa, nao.volum, prod.den_part, coalesce(gfurn.den_gest,furn.den_part), um1.den_um, um2.den_um, lg.cantum1, lg.cantum2,
    lg.tipserie, lg.serii, lg.ser, io.den_ioart, nc.simbol,
    i.prefixdoc, i.nrdoc, i.datadoc, lg.nrcertif,
    CASE WHEN coalesce(nao1.tippretmax,0) IN (1,2,3) THEN lg.pumaximal WHEN coalesce(nao1.tippretmax,0) IN (4,5,6) THEN nao1.pretmaximal ELSE NULL END,
    lg.d1,lg.d2,lg.d3,cs.den_claseas,c.nrdoc,c.datadoc,lg.obsdoc, ''Nu'' custodie, cc.denumire,LG.NIR' || coalesce(sPMP,'') || coalesce(sSelectUMA,'') || gUserAlias || '
  FROM lg
    INNER JOIN intrari    i     ON i.codintr      = lg.codintr
    INNER JOIN nartobj    nao   ON nao.codobiect  = lg.codobiect
    INNER JOIN nart       na    ON na.codarticol  = nao.codarticol
    INNER JOIN num1       um    ON um.codum1      = lg.umsec
    INNER JOIN ngest      ng    ON ng.codgest     = lg.gest
    LEFT  JOIN nlocatii   nl    ON nl.codlocatie  = lg.codlocatie
    LEFT  JOIN doccarnete dc    ON dc.codcarnet   = lg.carnetlivr
    LEFT  JOIN num        um1   ON um1.codum      = na.um1
    LEFT  JOIN num        um2   ON um2.codum      = na.um2
    LEFT  JOIN npart      prod  ON prod.codpart   = nao.codproducator
    LEFT  JOIN npart      furn  ON furn.codpart   = lg.furn
    LEFT  JOIN ngest      gfurn ON gfurn.codgest  = lg.gestfurn
    LEFT  JOIN nclasea    ca    ON ca.codclasea   = na.clasa
    LEFT  JOIN nclaseas   cs    ON cs.codclaseas  = na.clasastatist
    LEFT  JOIN ioart      io    ON io.codioart    = lg.codioart
    LEFT  JOIN ioart1     io1   ON io1.codioart   = lg.codioart  AND (i.an*12+i.luna) BETWEEN  io1.ALStart and  io1.ALStop
    LEFT  JOIN ncont      nc    ON nc.codcont     = io1.cont
    LEFT  JOIN nartobj1   nao1  ON nao1.codobiect = lg.codobiect AND (i.an*12+i.luna) BETWEEN nao1.ALStart and nao1.ALStop
    LEFT  JOIN intrlink   il    ON il.codintr1    = lg.codintr1
    LEFT  JOIN comanda1   c1    ON c1.codcomanda1 = il.codliniecomanda
    LEFT  JOIN comanda    c     ON c.codcomanda   = c1.codcomanda
    LEFT  JOIN centrecost cc    ON cc.codcentru   = lg.codcentru' || coalesce(sJoinUMA,'') || gSuplJoins || '
  ORDER BY lg.codintr, lg.indexlocal';

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_livrnerez_setjoinuri</obj_name>
  <obj_hashval>ef488e2aa1c3490f089ef560c8a6c90b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrnerez_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 13.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_LIVRNEREZ.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_livrpkdoc_processlist</obj_name>
  <obj_hashval>75474b99b7b0fe7c1a3e264be5377deb</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrpkdoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert          varchar := '';
  sSelect          varchar := '';
  sSelect1         varchar := '';
  gSuplCols        VARCHAR :=   'nartobj nao, num1 um, ngest ng, nlocatii nl, doccarnete dc, num1 um1, num1 um2, npart prod, npart furn, nclasea ca,'||
                               'ioart io, ioart1 io1, ncont nc, nartobj1 nao1';
  gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vTipPachet       NUMERIC := current_setting('PKG_LIST_BASE_LIVRPKDOC.vTipPachet', true)::numeric;
  vTipLivrare      NUMERIC := current_setting('PKG_LIST_BASE_LIVRPKDOC.vTipLivrare', true)::numeric;
  vCodPachete      varchar := current_setting('PKG_LIST_BASE_LIVRPKDOC.vCodPachete', true);
BEGIN
  --Florin 11.06.2024 - fixat 62301/62304
  --Florin 03.06.2024 - fixat 62213
  --Florin 27.05.2024 - sinc. Oracle
  --Adina 05.04.2021 - alstart, alstop
  --Adina 13.10.2020
  --Bogdan 04.12.2020
  IF  vTipPachet = 1 THEN
    --perform set_config('PKG_LIST_BASE_LIVRPKDOC.gSuplCols',(coalesce(current_setting('PKG_LIST_BASE_LIVRPKDOC.gSuplCols', true),'') || ',pachete pk')::varchar,false);
    gSuplCols := gSuplCols || ',pachete pk';
  ELSE
    --perform set_config('PKG_LIST_BASE_LIVRPKDOC.gSuplCols',(coalesce(current_setting('PKG_LIST_BASE_LIVRPKDOC.gSuplCols', true),'') || ',pachete1 pk1,pachete pk, PACHETEOBJL POBJL')::varchar,false);
    gSuplCols := gSuplCols || ',pachete1 pk1,pachete pk, PACHETEOBJL POBJL';
  END IF;

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = NAO.CODOBIECT',NULL);

  IF  vTipPachet = 1 THEN
    call pkg_list_struct_addsupltabs(gSuplCols, 'PACHETEEXT', 'PKEXT', 'PKEXT.CODPACHETE = LG.CODPACHETE', 1);
  ELSE
    call pkg_list_struct_addsupltabs(gSuplCols, 'PACHETEEXT', 'PKEXT', 'PKEXT.CODPACHETE = PK1.CODPACHETE',NULL);
  END IF;
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias , gNullAlias , gSuplJoins , gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_LIVRPKDOC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert := 'INSERT INTO ' || TMPNAME || '(
    ART, UM, CANTDOC, CANTLIVR, PACH, PINREG, PVANZ,
    VALACH, VALINREG, VALVANZ, GESTIUNE, LOCATIE, NRLIVR, DATALIVR, DENCARNET, SIMBCARNET, SERCARNET, GAR, DATAEXP, DATAPROD,
    CODINTERN, CODEXTERN, DENCLASAA, SIMBCLASAA, MASA, VOLUM, PRODUCATOR, FURNIZOR, UM1, UM2, CANT1, CANT2, TIPSERIE,
    SERII, DENIOART, SIMBCONT, PREFIXDOC, NRDOC, DATADOC, NRCERTIF,
    PUMAXIMAL,
    D1, D2, D3' || gUserFields || ')';

  IF  vTipPachet = 0 THEN
    DELETE FROM IESIRI1_MAN;

    INSERT INTO IESIRI1_MAN
    SELECT I1.*
    FROM IESIRI1 I1
    WHERE I1.TIPLIVRARE = vTipLivrare and  EXISTS (SELECT * FROM TMP_MANEVRA_LISTE TMP WHERE TMP.VALOARE = I1.CODIES::varchar and  UPPER(tmp.filtru) = 'CODIES');

  sSelect := '
    WITH
    LG AS (
      SELECT
        pobj.codpacheteobjl, pk1.codpachete1, i.codies coddoc, i.tipdoc, i1.indexlocal, i1.codobiect, coalesce(lv.gest, n.gest) gest,
        ns.codlocatie, l1.umsec, i1.pu, i1.cant canti, i1.garantie, l.carnetlivr, l.nrlivr, l.datalivr, coalesce(ns.codioart,lv.codioart) codioart,
        ns.furn, ns.codgestprod gestfurn, SUM(coalesce(lv.pretinreg,ns.pret)*l1.cant) valinreg, SUM(coalesce(lv.pretachiz,ns.pret - ns.adaos)*l1.cant) valachiz,
        pobj.cant, pobj.cantum1, sum(l1.cantum2) cantum2,
        CASE coalesce(ns.tipserie,na.tipserie)
          WHEN 1 THEN string_agg(s.serie,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''')
          WHEN 2 THEN string_agg(distinct concat(s.serie, ''(''||trunc(l1.cant, 2)::varchar||'')''),'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''')
          ELSE NULL
        END SERII,
        coalesce(i1.pumaximal,max(coalesce(ns.pumaximal,0))) pumaximal,
        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 to_char(nser.dataprod,''dd.mm.yyyy'') ,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''') dp,
        string_agg(DISTINCT int1.nrcertif::varchar ,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''') nrcertif,
        (case coalesce(ns.tipserie,na.tipserie) when 0 then ''fara serie'' when 1 then ''serie pe bucata'' when 2 then ''serie pe lot'' end) tipserie,
        na.um1, na.um2, na.clasa, ns.D1, ns.D2, ns.D3
      FROM   pacheteobjl pobj
            inner join pachete pk    on pk.codpachete   = pobj.codpachete
            INNER JOIN livr1 l1      ON l1.codlivr1     = pobj.codlivr1
            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 i.codies = l.codies
            INNER JOIN nartobj nao   ON nao.codobiect   = i1.codobiect
            INNER JOIN nart na       ON na.codarticol   = nao.codarticol
            left  JOIN pachete1 pk1  ON pk1.coddoc      = i.codies and pk1.tipdoc = i.tipdoc and PK1.CODPACHETE = pk.codpachete
            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 NIRSTOC1 NS1  ON NS1.CODNIRSTOC  = NS.CODNIRSTOC
            LEFT  JOIN NIRSTOC  NSIN ON nsin.codnirstoc = ns1.CODNIRSTOCORIG
            LEFT  JOIN dvi1          ON dvi1.coddvi1    = nsin.coddvi1
            LEFT  JOIN intrari1 int1 ON int1.codintr1   = coalesce(dvi1.codintr1, nsin.codintr1)
            LEFT  JOIN nirser nser   ON nser.codnirser  = l1.codnirser
            LEFT  JOIN nserii s      on s.codserie      = nser.codserie
      WHERE PK.CODPACHETE = ' || coalesce(vCodPachete,'') || '
      GROUP BY
        i.codies, i.tipdoc, i1.indexlocal, i1.codobiect, i1.cant, i1.garantie, i1.pu, i1.pumaximal,l.carnetlivr, l.nrlivr, l.datalivr, l1.umsec, lv.codioart, lv.gest,
        ns.codlocatie, ns.codioart, ns.furn, ns.codgestprod, ns.tipserie, n.gest, na.tipserie, na.um1, na.um2, na.clasa, ns.D1, ns.D2, ns.D3, pobj.cant, pobj.cantum1,
        pk1.codpachete1, pobj.codpacheteobjl
        )
    SELECT
      nao.denumire, um.den_um1, lg.canti / coalesce(um.paritate, 1), lg.cant/coalesce(um.paritate, 1),
      lg.valachiz*coalesce(um.paritate, 1)/lg.cant, lg.valinreg*coalesce(um.paritate, 1)/lg.cant, lg.pu*coalesce(um.paritate, 1),
      lg.valachiz, lg.valinreg, lg.pu * lg.cant, ng.den_gest, nl.denumire, lg.nrlivr, lg.datalivr, dc.denumire, dc.simbol, dc.serie, lg.garantie, lg.tg,  lg.dp,
      nao.codintern, nao.codextern, ca.den_clasea, ca.simbol, nao.masa, nao.volum, prod.den_part, coalesce(gfurn.den_gest,furn.den_part),
      um1.den_um, um2.den_um, lg.cantum1, lg.cantum2, lg.tipserie,
      lg.serii, io.den_ioart, nc.simbol, i.prefixdoc, i.nrdoc, i.datadoc, lg.nrcertif,
      CASE WHEN coalesce(nao1.tippretmax,0) IN (1,2,3) THEN lg.pumaximal WHEN coalesce(nao1.tippretmax,0) IN (4,5,6) THEN nao1.pretmaximal ELSE NULL END,
      lg.D1, lg.D2, lg.D3 ' || gUserAlias || '
    FROM   lg
          INNER JOIN iesiri i          ON i.codies        = lg.coddoc
          INNER JOIN nartobj nao       ON nao.codobiect   = lg.codobiect
          INNER JOIN num1 um           ON um.codum1       = lg.umsec
          INNER JOIN ngest ng          ON ng.codgest      = lg.gest
          LEFT  JOIN PACHETE1 PK1      ON PK1.CODPACHETE1 = LG.CODPACHETE1
          LEFT  JOIN PACHETE PK        ON PK.CODPACHETE   = PK1.CODPACHETE
          left  join pacheteobjl pobjl on pobjl.codpacheteobjl = lg.codpacheteobjl
          LEFT  JOIN nlocatii nl       ON nl.codlocatie  = lg.codlocatie
          LEFT  JOIN doccarnete dc     ON dc.codcarnet   = lg.carnetlivr
          LEFT  JOIN num um1           ON um1.codum      = lg.um1
          LEFT  JOIN num um2           ON um2.codum      = lg.um2
          LEFT  JOIN npart prod        ON prod.codpart   = nao.codproducator
          LEFT  JOIN npart furn        ON furn.codpart   = lg.furn
          LEFT  JOIN ngest gfurn       ON gfurn.codgest  = lg.gestfurn
          LEFT  JOIN nclasea ca        ON ca.codclasea   = lg.clasa
          LEFT  JOIN ioart io          ON io.codioart    = lg.codioart
          LEFT  JOIN ioart1 io1        ON io1.codioart   = lg.codioart  AND (i.an*12+i.luna) BETWEEN  io1.ALStart and  io1.ALStop
          LEFT  JOIN ncont nc          ON nc.codcont     = io1.cont
          LEFT  JOIN nartobj1 nao1     ON nao1.codobiect = lg.codobiect AND (i.an*12+i.luna) BETWEEN nao1.ALStart and nao1.ALStop '
          || gSuplJoins || '
    ORDER BY lg.coddoc, lg.indexlocal';

    DELETE FROM TRANSF1_MAN;

    INSERT INTO TRANSF1_MAN(CODTRANSF1, CODTRANSF, INDEXLOCAL, TIPLINIE, UMSEC, CODOBIECT, PU, CANT, TVA, OBS, CODCONT, PUMAXIMAL, COSTTRANSPORT, CODOBIECTORIG, CODAUTO)
    SELECT   T1.CODTRANSF1, T1.CODTRANSF, T1.INDEXLOCAL, T1.TIPLINIE, T1.UMSEC, T1.CODOBIECT, T1.PU, T1.CANT, T1.TVA, T1.OBS, T1.CODCONT,
            T1.PUMAXIMAL, T1.COSTTRANSPORT, TMP.VALOARE1::numeric, TMP.VALOARE2::numeric
    FROM   TRANSF1 T1
          INNER JOIN TMP_MANEVRA_LISTE TMP ON  TMP.VALOARE = T1.CODTRANSF::varchar and  UPPER(tmp.filtru) = 'CODTRANSF';

    sSelect1 := '
    WITH
    LG AS (
      SELECT
        0 codpacheteobjl, t1.CODOBIECTORIG codpachete1, t.codtransf coddoc, t.tipdoc, t1.indexlocal, t1.codobiect, coalesce(lv.gest, n.gest) gest,
        ns.codlocatie, l1.umsec, t1.pu, t1.cant cantt, l.carnetlivr, l.nrlivr, l.datalivr, coalesce(lv.codioart,ns.codioart) codioart,
        ns.furn, ns.codgestprod gestfurn, SUM(coalesce(lv.pretinreg,ns.pret)*l1.cant) valinreg, SUM(coalesce(lv.pretachiz,ns.pret - ns.adaos)*l1.cant) valachiz,
        sum(l1.cant) cant, sum(l1.cantum1) cantum1, sum(l1.cantum2) cantum2,
        CASE coalesce(ns.tipserie,na.tipserie)
          WHEN 1 THEN string_agg(distinct s.serie ,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''')
          WHEN 2 THEN string_agg(distinct concat(s.serie,''(''|| trunc(l1.cant, 2)::varchar||'')'') ,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''')
          ELSE NULL
        END SERII,
        coalesce(t1.pumaximal,max(ns.pumaximal)) pumaximal,
        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 to_char(nser.dataprod,''dd.mm.yyyy'') ,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''') dp,
        string_agg(DISTINCT int1.nrcertif::varchar ,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''') nrcertif,
        (case coalesce(ns.tipserie,na.tipserie) when 0 then ''fara serie'' when 1 then ''serie pe bucata'' when 2 then ''serie pe lot'' end) tipserie,
        na.um1, na.um2, na.clasa, ns.D1, ns.D2, ns.D3
      FROM  TRANSF1_MAN t1
            INNER JOIN transf t      ON t.codtransf     = t1.codtransf
            INNER JOIN nartobj nao   ON nao.codobiect   = t1.codobiect
            INNER JOIN nart na       ON na.codarticol   = nao.codarticol
            INNER JOIN livr l        ON l.codtransf     = t1.codtransf
            INNER JOIN livr1 l1      ON l1.codies1      = t1.codtransf1 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 NIRSTOC1 NS1  ON NS1.CODNIRSTOC  = NS.CODNIRSTOC
            LEFT  JOIN NIRSTOC  NSIN ON nsin.codnirstoc = ns1.CODNIRSTOCORIG
            LEFT  JOIN dvi1          ON dvi1.coddvi1    = nsin.coddvi1
            LEFT  JOIN intrari1 int1 ON int1.codintr1   = coalesce(dvi1.codintr1, nsin.codintr1)
            LEFT  JOIN nirser nser   ON nser.codnirser  = l1.codnirser
            LEFT  JOIN nserii s      on s.codserie      = nser.codserie
      GROUP BY
        t.codtransf, t.tipdoc, t1.indexlocal, t1.codobiect, t1.pu, t1.cant, t1.pumaximal, l.carnetlivr, l.nrlivr, l.datalivr, l1.umsec, lv.codioart, lv.gest,
        ns.codlocatie, ns.codioart, ns.furn, ns.codgestprod, ns.tipserie, n.gest, na.tipserie, na.um1, na.um2, na.clasa, ns.D1, ns.D2, ns.D3,t1.CODOBIECTORIG )
    SELECT
      nao.denumire, um.den_um1, lg.cantt / coalesce(um.paritate, 1), lg.cant/coalesce(um.paritate, 1),
      lg.valachiz*coalesce(um.paritate, 1)/lg.cant, lg.valinreg*coalesce(um.paritate, 1)/lg.cant, lg.pu*um.paritate,
      lg.valachiz, lg.valinreg, lg.pu * lg.cant, ng.den_gest, nl.denumire, lg.nrlivr, lg.datalivr, dc.denumire, dc.simbol, dc.serie, nao.lunigarantie, lg.tg, lg.dp,
      nao.codintern, nao.codextern, ca.den_clasea, ca.simbol, nao.masa, nao.volum, prod.den_part, coalesce(gfurn.den_gest,furn.den_part),
      um1.den_um, um2.den_um, lg.cantum1, lg.cantum2, lg.tipserie,
      lg.serii, io.den_ioart, nc.simbol, t.prefixdoc, t.nrdoc, t.datadoc, lg.nrcertif,
      CASE WHEN coalesce(nao1.tippretmax,0) IN (1,2,3) THEN lg.pumaximal WHEN coalesce(nao1.tippretmax,0) IN (4,5,6) THEN nao1.pretmaximal ELSE NULL END,
      lg.D1, lg.D2, lg.D3 ' || gUserAlias || '
    FROM LG
      INNER JOIN transf t          ON t.codtransf       = lg.coddoc
      INNER JOIN nartobj nao       ON nao.codobiect     = lg.codobiect
      INNER JOIN nart na           ON na.codarticol     = nao.codarticol
      INNER JOIN num1 um           ON um.codum1         = lg.umsec
      INNER JOIN ngest ng          ON ng.codgest        = lg.gest
      LEFT  JOIN PACHETE1 PK1      ON PK1.CODPACHETE1   = LG.CODPACHETE1
      LEFT  JOIN PACHETE PK        ON PK.CODPACHETE     = PK1.CODPACHETE
      LEFT  JOIN PACHETEOBJL POBJL ON LG.CODPACHETEOBJL = POBJL.CODPACHETEOBJL
      LEFT  JOIN nlocatii nl       ON nl.codlocatie     = lg.codlocatie
      LEFT  JOIN doccarnete dc     ON dc.codcarnet      = lg.carnetlivr
      LEFT  JOIN num um1           ON um1.codum         = lg.um1
      LEFT  JOIN num um2           ON um2.codum         = lg.um2
      LEFT  JOIN npart prod        ON prod.codpart      = nao.codproducator
      LEFT  JOIN npart furn        ON furn.codpart      = lg.furn
      LEFT  JOIN ngest gfurn       ON gfurn.codgest     = lg.gestfurn
      LEFT  JOIN nclasea ca        ON ca.codclasea      = lg.clasa
      LEFT  JOIN ioart io          ON io.codioart       = lg.codioart
      LEFT  JOIN ioart1 io1        ON io1.codioart      = lg.codioart AND (t.an*12+t.luna) BETWEEN  io1.ALStart and  io1.ALStop
      LEFT  JOIN ncont nc          ON nc.codcont        = io1.cont
      LEFT  JOIN nartobj1 nao1     ON nao1.codobiect    = lg.codobiect AND (t.an*12+t.luna) BETWEEN nao1.ALStart and nao1.ALStop ' || gSuplJoins || '
    ORDER BY lg.coddoc, lg.indexlocal';

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

    sSelect := '
    WITH
    LG AS (
      SELECT
        pobj.codpacheteobjl, 0 codpachete1, c.codcomanda coddoc, c.tipdoc, c1.indexlocal, c1.codobiect, n.gest, ns.codlocatie, ns.umsec, c1.pu, c1.cantacceptat canti, null::numeric garantie, c.carnetdoc, c.nrdoc, c.datadoc, ns.codioart,
        ns.furn, ns.codgestprod gestfurn, SUM(ns.pret*pobj.cant) valinreg, SUM((ns.pret - coalesce(ns.adaos,0))*pobj.cant) valachiz,
        pobj.cant, pobj.cantum1, sum(case when coalesce(ns.cantnir,0) = 0 then 0 else ns.cantum2*pobj.cant/ns.cantnir end) cantum2,
        CASE coalesce(ns.tipserie,na.tipserie)
          WHEN 1 THEN string_agg(distinct s.serie ,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''')
          WHEN 2 THEN string_agg(distinct concat(s.serie||''(''||trunc(pobj.cant, 2)::varchar||'')'') ,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''')
          ELSE NULL
        END SERII,
        coalesce(max(ns.pumaximal), 0) pumaximal,
        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 to_char(nser.dataprod,''dd.mm.yyyy'') ,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''') dp,
        string_agg(DISTINCT int1.nrcertif::varchar ,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''') nrcertif,
        case when coalesce(ns.tipserie,na.tipserie) = 0 then ''fara serie'' when coalesce(ns.tipserie,na.tipserie) = 1 then ''serie pe bucata''
        when coalesce(ns.tipserie,na.tipserie) = 2 then ''serie pe lot'' end tipserie,
        na.um1, na.um2, na.clasa, ns.D1, ns.D2, ns.D3
      FROM pacheteobjl pobj
        inner join pachete  pk  on pk.codpachete   = pobj.codpachete
        INNER JOIN rezervats r  ON r.codrezervats  = pobj.codrezervats
        INNER JOIN comanda1 c1  on c1.codcomanda1  = r.codcomanda1
        INNER JOIN comanda   c  ON c.codcomanda    = c1.codcomanda
        INNER JOIN nartobj nao  ON nao.codobiect   = c1.codobiect
        INNER JOIN nart    na   ON na.codarticol   = nao.codarticol
        left JOIN pachete1 pk1  ON pk1.coddoc      = na.codarticol - na.codarticol
        LEFT JOIN nirstoc  ns   ON ns.codnirstoc   = r.codnirstoc
        LEFT JOIN nir      n    ON n.codnir        = ns.codnir
        LEFT JOIN NIRSTOC1 NS1  ON NS1.CODNIRSTOC  = NS.CODNIRSTOC
        LEFT JOIN NIRSTOC  NSIN ON nsin.codnirstoc = ns1.CODNIRSTOCORIG
        LEFT JOIN dvi1          ON dvi1.coddvi1    = nsin.coddvi1
        LEFT JOIN intrari1 int1 ON int1.codintr1   = coalesce(dvi1.codintr1, nsin.codintr1)
        LEFT JOIN nirser   nser ON nser.codnirser  = r.codnirser
        LEFT JOIN nserii   s on s.codserie         = nser.codserie
      WHERE PK.CODPACHETE = '||COALESCE(vCodPachete, '')||'
      GROUP BY
        pobj.codpacheteobjl, c.codcomanda, c.tipdoc, c1.indexlocal, c1.codobiect, n.gest, ns.codlocatie, ns.umsec,
        c1.pu, c1.cantacceptat, c.carnetdoc, c.nrdoc, c.datadoc, ns.codioart, ns.furn, ns.codgestprod, pobj.cant, pobj.cantum1,
        ns.tipserie, na.tipserie, na.um1, na.um2, na.clasa, ns.D1, ns.D2, ns.D3
        )
    SELECT
      nao.denumire, um.den_um1, lg.canti / coalesce(um.paritate, 1), lg.cant/coalesce(um.paritate, 1), lg.valachiz*coalesce(um.paritate, 1)/lg.cant, lg.valinreg*coalesce(um.paritate, 1)/lg.cant, lg.pu*coalesce(um.paritate, 1),
      lg.valachiz, lg.valinreg, lg.pu * lg.cant, ng.den_gest, nl.denumire, c.nrdoc nrlivr, c.datadoc datalivr, dc.denumire, dc.simbol, dc.serie, lg.garantie, lg.tg,  lg.dp,
      nao.codintern, nao.codextern, ca.den_clasea, ca.simbol, nao.masa, nao.volum, prod.den_part, coalesce(gfurn.den_gest,furn.den_part), um1.den_um, um2.den_um, lg.cantum1, lg.cantum2, lg.tipserie,
      lg.serii, io.den_ioart, nc.simbol, c.prefixdoc, c.nrdoc, c.datadoc, lg.nrcertif,
      CASE WHEN coalesce(nao1.tippretmax,0) IN (1,2,3) THEN lg.pumaximal WHEN coalesce(nao1.tippretmax,0) IN (4,5,6) THEN nao1.pretmaximal ELSE NULL END,
      lg.D1, lg.D2, lg.D3 '||gUserAlias||'
    FROM lg
      INNER JOIN comanda     c     ON c.codcomanda    = lg.coddoc and c.tipdoc = lg.tipdoc
      INNER JOIN nartobj     nao   ON nao.codobiect   = lg.codobiect
      INNER JOIN num1        um    ON um.codum1       = lg.umsec
      INNER JOIN ngest       ng    ON ng.codgest      = lg.gest
      left  join pacheteobjl pobjl on pobjl.codpacheteobjl = lg.codpacheteobjl
      LEFT  JOIN PACHETE1    PK1   ON PK1.CODPACHETE1 = LG.CODPACHETE1
      LEFT  JOIN PACHETE     PK    ON PK.CODPACHETE   = POBJL.CODPACHETE
      LEFT  JOIN nlocatii    nl    ON nl.codlocatie  = lg.codlocatie
      LEFT  JOIN doccarnete  dc    ON dc.codcarnet   = lg.codlocatie - lg.codlocatie
      LEFT  JOIN num         um1   ON um1.codum      = lg.um1
      LEFT  JOIN num         um2   ON um2.codum      = lg.um2
      LEFT  JOIN npart       prod  ON prod.codpart   = nao.codproducator
      LEFT  JOIN npart       furn  ON furn.codpart   = lg.furn
      LEFT  JOIN ngest       gfurn ON gfurn.codgest  = lg.gestfurn
      LEFT  JOIN nclasea     ca    ON ca.codclasea   = lg.clasa
      LEFT  JOIN ioart       io    ON io.codioart    = lg.codioart
      LEFT  JOIN ioart1      io1   ON io1.codioart   = lg.codioart  AND (c.an*12+c.luna) BETWEEN  io1.ALStart and  io1.ALStop
      LEFT  JOIN ncont       nc    ON nc.codcont     = io1.cont
      LEFT  JOIN nartobj1    nao1  ON nao1.codobiect = lg.codobiect AND (c.an*12+c.luna) BETWEEN nao1.ALStart and nao1.ALStop  '||
      gSuplJoins||'
    ORDER BY lg.coddoc, lg.indexlocal';
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert||sSelect, aListID, aListVer);
  ELSE
    sSelect := '
    WITH
    LG AS (
      SELECT
        ns.codobiect, n.gest, ns.codlocatie, ns.umsec, pobj.cant canti, ns.codioart,
        ns.furn, ns.codgestprod gestfurn, ns.pret*pobj.cant valinreg, (ns.pret - coalesce(ns.adaos,0)) * pobj.cant valachiz,
        pobj.cant, ns.pret pu,
        round(CASE
                WHEN na.RELATIEUM1 IN (1, 7) AND coalesce(ns.D1, 0) &lt;&gt; 0 THEN pobj.cant/ns.D1
                WHEN na.RELATIEUM1 IN (2, 8) AND coalesce(ns.D1, 0) * coalesce(ns.D2, 0) &lt;&gt; 0 THEN pobj.cant / (coalesce(ns.D1,0) * coalesce(ns.D2,0))
                WHEN na.RELATIEUM1 IN (3, 9) AND coalesce(ns.D1, 0) * coalesce(ns.D2, 0) * coalesce(ns.D3, 0) &lt;&gt; 0 THEN pobj.cant / (coalesce(ns.D1,0) * coalesce(ns.D2,0) * coalesce(ns.D3,0))
                WHEN na.RELATIEUM1 IN (4, 10) THEN pobj.cant * coalesce(ns.D1,0)
                WHEN na.RELATIEUM1 IN (5, 11) THEN pobj.cant * coalesce(ns.D1, 0) * coalesce(ns.D2, 0)
                WHEN na.RELATIEUM1 IN (6, 12) THEN pobj.cant * coalesce(ns.D1, 0) * coalesce(ns.D2, 0) * coalesce(ns.D3, 0)
              END,7) cantum1,
        0 cantum2,
        coalesce(ns.pumaximal,0) pumaximal,
        ns.tg,
        int1.nrcertif::varchar nrcertif,
        (case coalesce(ns.tipserie,na.tipserie) when 0 then ''fara serie'' when 1 then ''serie pe bucata'' when 2 then ''serie pe lot'' end) tipserie,
        na.um1, na.um2, na.clasa, ns.D1, ns.D2, ns.D3, pk.an, pk.luna, pk.codpachete
      FROM  pacheteobj pobj
            INNER JOIN pachete pk     ON pobj.codpachete = pk.codpachete
            INNER JOIN nirstoc ns     ON ns.codnirstoc   = pobj.codnirstoc
            INNER JOIN nartobj nao    ON nao.codobiect   = ns.codobiect
            INNER JOIN nart na        ON na.codarticol   = nao.codarticol
            LEFT  JOIN nir n          ON n.codnir        = ns.codnir
            LEFT  JOIN NIRSTOC1  NS1  ON NS1.CODNIRSTOC  = NS.CODNIRSTOC
            LEFT  JOIN NIRSTOC   NSIN ON nsin.codnirstoc = ns1.CODNIRSTOCORIG
            LEFT  JOIN dvi1           ON dvi1.coddvi1    = nsin.coddvi1
            LEFT  JOIN intrari1 int1 ON int1.codintr1    = coalesce(dvi1.codintr1, nsin.codintr1)
      WHERE pk.codpachete = ' || coalesce(vCodPachete,'') || '
      )
    SELECT
      nao.denumire, um.den_um1, lg.canti / coalesce(um.paritate, 1), lg.cant/coalesce(um.paritate, 1),
      lg.valachiz*coalesce(um.paritate, 1)/lg.cant, lg.valinreg*coalesce(um.paritate, 1)/lg.cant, lg.pu*coalesce(um.paritate, 1),
      lg.valachiz, lg.valinreg, lg.pu * lg.cant, ng.den_gest, nl.denumire, null nrlivr, null datalivr, null denumire, null simbol, null serie,
      null garantie, lg.tg, null dp,
      nao.codintern, nao.codextern, ca.den_clasea, ca.simbol, nao.masa, nao.volum, prod.den_part, coalesce(gfurn.den_gest,furn.den_part),
      um1.den_um, um2.den_um, lg.cantum1, lg.cantum2, lg.tipserie,
      null serii, io.den_ioart, nc.simbol, null prefixdoc, null nrdoc, null datadoc, lg.nrcertif,
      CASE WHEN coalesce(nao1.tippretmax,0) IN (1,2,3) THEN lg.pumaximal WHEN coalesce(nao1.tippretmax,0) IN (4,5,6) THEN nao1.pretmaximal ELSE NULL END,
      lg.D1, lg.D2, lg.D3 ' || gUserAlias || '
    FROM  lg
          INNER JOIN nartobj nao   ON nao.codobiect  = lg.codobiect
          INNER JOIN num1 um       ON um.codum1      = lg.umsec
          INNER JOIN ngest ng      ON ng.codgest     = lg.gest
          INNER JOIN PACHETE PK    ON LG.CODPACHETE  = PK.CODPACHETE
          LEFT  JOIN nlocatii nl   ON nl.codlocatie  = lg.codlocatie
          LEFT  JOIN num um1       ON um1.codum      = lg.um1
          LEFT  JOIN num um2       ON um2.codum      = lg.um2
          LEFT  JOIN npart prod    ON prod.codpart   = nao.codproducator
          LEFT  JOIN npart furn    ON furn.codpart   = lg.furn
          LEFT  JOIN ngest gfurn   ON gfurn.codgest  = lg.gestfurn
          LEFT  JOIN nclasea ca    ON ca.codclasea   = lg.clasa
          LEFT  JOIN ioart io      ON io.codioart    = lg.codioart
          LEFT  JOIN ioart1 io1    ON io1.codioart   = lg.codioart  AND (lg.an*12+lg.luna) BETWEEN io1.ALStart and io1.ALStop
          LEFT  JOIN ncont nc      ON nc.codcont     = io1.cont
          LEFT  JOIN nartobj1 nao1 ON nao1.codobiect = lg.codobiect AND (lg.an*12+lg.luna) BETWEEN nao1.ALStart and nao1.ALStop ' || gSuplJoins || '
     ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_livrtransf_processlist</obj_name>
  <obj_hashval>c0c40467419ae632dc45f54a548404cc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrtransf_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSelect         varchar := '';
  sInsMAN         varchar := '';
  sInsertUMA       varchar := '';
  sSelectUMA       varchar := '';
  sJoinUMA         varchar := '';
  gSuplCols        VARCHAR :=   'transf t, nartobj nao, nart na, num1 um, ngest ng, nlocatii nl, doccarnete dc, num1 um1, num1 um2, npart prod, npart furn, nclasea ca, '||
                              'ioart io, ioart1 io1, ncont nc, nartobj1 nao1, nirstoc ns, comanda1 c1, comanda c';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vCodGest        NUMERIC := current_setting('PKG_LIST_BASE_LIVRTRANSF.vCodGest',   true)::NUMERIC;
  vCodTransf      NUMERIC := current_setting('PKG_LIST_BASE_LIVRTRANSF.vCodTransf', true)::NUMERIC;
BEGIN
  --Adina 05.04.2021 - alstart,alstop
  --Adina 18 septembrie 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_LIVRTRANSF.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  DELETE FROM LIVR1_MAN;

  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, L1.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 TRANSF1 t1
    INNER JOIN livr  l   ON l.codtransf = t1.codtransf
    INNER JOIN livr1 l1 ON l1.codies1  = t1.codtransf1 AND l1.codlivr = l.codlivr';

  IF  vCodGest &gt; 0 THEN
    sInsMAN := sInsMAN || '
    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';
  END IF;

  sInsMAN := sInsMAN || '
  WHERE T1.CodTransf';

  IF vCodTransf &gt; 0 THEN
    sInsMAN := sInsMAN || ' = ' || coalesce(vCodTransf::varchar ,'');
  ELSE
    sInsMAN := sInsMAN || ' IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE UPPER(FILTRU) = ''CODTRANSF'')';
  END IF;

  IF  vCodGest &gt; 0 THEN
    sInsMAN := coalesce(sInsMAN,'') || '
    AND coalesce(lv.gest,n.gest) = ' || coalesce(vCodGest::varchar ,'');
  END IF;

  EXECUTE sInsMAN;

  SELECT PKG_LIST_BASE_UTILS_UMA_UTILS.sInsertUMA, PKG_LIST_BASE_UTILS_UMA_UTILS.sSelectUMA, PKG_LIST_BASE_UTILS_UMA_UTILS.sJoinUMA
  INTO sInsertUMA, sSelectUMA, sJoinUMA
  FROM PKG_LIST_BASE_UTILS_UMA_UTILS('lg.cant', 't1.codobiect', sInsertUMA, sSelectUMA, sJoinUMA,NULL);

  sInsert :=
  'INSERT INTO ' || TMPNAME || ' (
    ART, UM, CANTDOC, CANTLIVR,
    PACH, PINREG, PVANZ,
    VALACH, VALINREG, VALVANZ,
    GESTIUNE, LOCATIE, NRLIVR, DATALIVR, DENCARNET, SIMBCARNET, SERCARNET, OBSLIVR, GAR, DATAEXP, DATAPROD, CODINTERN, CODEXTERN,
    DENCLASAA, SIMBCLASAA, MASA, VOLUM, PRODUCATOR, FURNIZOR, ARTFURN, UM1, UM2, CANT1, CANT2,
    TIPSERIE, SERII, SER, CERTIFSER, DENIOART, SIMBCONT,
    PREFIXDOC, NRDOC, DATADOC, NRCERTIF, PUMAXIMAL,D1,D2,D3,DENCLASEAS,NRCOM,DATACOM,OBSDOC,CUSTODIE' || coalesce(sInsertUMA,'') || gUserFields || ')';

  sSelect := '
  WITH
    NSIN AS (
--      SELECT connect_by_root ns.codnirstoc codnirstoc, ns.codintr1, ns.coddvi1
--      FROM nirstoc ns
--      WHERE coalesce(NS.CODNIRSTOCPARINTE,0) = 0
--      START WITH NS.CODNIRSTOC IN (SELECT DISTINCT CODNIRSTOC FROM LIVR1_MAN)
--      CONNECT BY NS.CODNIRSTOC = PRIOR NS.CODNIRSTOCPARINTE
      SELECT codnirstoc, codintr1, coddvi1
      FROM (
            WITH RECURSIVE a (rootcodnirstoc, codnirstoc, codintr1, coddvi1, CODNIRSTOCPARINTE) AS
            (
              SELECT codnirstoc rootcodnirstoc, codnirstoc, codintr1, coddvi1, CODNIRSTOCPARINTE
              FROM nirstoc
              WHERE CODNIRSTOC IN (228,225,307,306,207,533)  --(SELECT DISTINCT CODNIRSTOC FROM LIVR1_MAN)
              union ALL
              SELECT A.codnirstoc, a.CODNIRSTOCPARINTE codnirstoc, o.codintr1, O.coddvi1, o.CODNIRSTOCPARINTE
              FROM nirstoc O  inner join A ON o.codnirstoc = a.CODNIRSTOCPARINTE
            )
            SELECT rootcodnirstoc as codnirstoc, codintr1, coddvi1 FROM A WHERE Coalesce(CODNIRSTOCPARINTE,0) = 0
           ) A_PG
    ),
    LG AS (
      SELECT
        ns.codnirstoc, l1.codies1 codtransf1, coalesce(lv.gest, n.gest) gest, ns.codlocatie, l1.umsec, l1.codlivr,
        coalesce(lv.codioart,ns.codioart) codioart, ns.furn, ns.codgestprod gestfurn,
        SUM(coalesce(lv.pretinreg,ns.pret)*l1.cant) valinreg,
        SUM(coalesce(lv.pretachiz,ns.pret - ns.adaos)*l1.cant) valachiz,
        sum(l1.cant) cant, sum(l1.cantum1) cantum1, sum(l1.cantum2) cantum2, ns.d1, ns.d2, ns.d3,
        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,
        fnc_array_to_vc3200(array_agg(s.serie)) ser,
        max(ns.pumaximal) pumaximal,
        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 to_char(nser.dataprod,''dd.mm.yyyy''))) dp,
        fnc_array_to_vc3200(array_agg(DISTINCT int1.nrcertif)) nrcertif,
        fnc_array_to_vc3200(array_agg(DISTINCT c.nrcertif)) certifser,
        ns.tipserie
      FROM livr1_man l1
        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 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)
        LEFT JOIN nirser nser   ON nser.codnirser  = l1.codnirser
        LEFT JOIN nserii s       ON s.codserie      = nser.codserie
        LEFT JOIN certif c       ON c.codcertif     = nser.codcertif
      GROUP BY
        l1.codies1, l1.codlivr, l1.umsec, lv.codioart, lv.gest, ns.codnirstoc, ns.codlocatie, ns.codioart, ns.furn, ns.codgestprod,
        ns.tipserie, ns.d1, ns.d2, ns.d3, n.gest)
  SELECT
    nao.denumire, um.den_um1, t1.cant / um.paritate, lg.cant/um.paritate,
    lg.valachiz*um.paritate/lg.cant, lg.valinreg*um.paritate/lg.cant, t1.pu*um.paritate, lg.valachiz, lg.valinreg, t1.pu * lg.cant,
    ng.den_gest, nl.denumire, l.nrlivr, l.datalivr, dc.denumire, dc.simbol, dc.serie,
    l.obs, nao.lunigarantie, lg.tg, lg.dp, nao.codintern, nao.codextern,
    ca.den_clasea, ca.simbol, nao.masa, nao.volum, prod.den_part,
    case when coalesce(gfurn.codgest, 0) = 0 then furn.den_part else gfurn.den_gest end, fobj.denumire,
    um1.den_um, um2.den_um, lg.cantum1, lg.cantum2,
    (case lg.tipserie when 1 then ''serie pe bucata'' when 2 then ''serie pe lot'' else ''fara serie'' end), lg.serii, lg.ser, lg.certifser, io.den_ioart, nc.simbol,
    t.prefixdoc, t.nrdoc, t.datadoc, lg.nrcertif,
    CASE WHEN coalesce(nao1.tippretmax,0) IN (1,2,3) THEN coalesce(t1.pumaximal,lg.pumaximal) WHEN coalesce(nao1.tippretmax,0) IN (4,5,6) THEN nao1.pretmaximal ELSE NULL END,
    lg.d1,lg.d2,lg.d3,cs.den_claseas,c.nrdoc,c.datadoc, substr(t1.obs,1,200), ''Nu'' custodie' || coalesce(sSelectUMA,'') || gUserAlias || '
  FROM LG
    LEFT JOIN transf1 t1     ON t1.codtransf1  = lg.codtransf1
    LEFT JOIN transf t       ON t.codtransf    = t1.codtransf
    LEFT JOIN livr l         ON l.codlivr      = lg.codlivr
    LEFT JOIN nartobj nao   ON nao.codobiect  = t1.codobiect
    LEFT JOIN nart na       ON na.codarticol  = nao.codarticol
    LEFT JOIN num1 um       ON um.codum1      = lg.umsec
    LEFT JOIN ngest ng       ON ng.codgest     = lg.gest
    LEFT JOIN nirstoc ns     ON ns.codnirstoc  = lg.codnirstoc
    LEFT JOIN nlocatii nl   ON nl.codlocatie  = lg.codlocatie
    LEFT JOIN doccarnete dc ON dc.codcarnet   = l.carnetlivr
    LEFT JOIN num um1       ON um1.codum      = na.um1
    LEFT JOIN num um2       ON um2.codum      = na.um2
    LEFT JOIN npart prod     ON prod.codpart   = nao.codproducator
    LEFT JOIN npart furn     ON furn.codpart   = lg.furn
    LEFT JOIN ngest gfurn   ON gfurn.codgest  = lg.gestfurn
    LEFT JOIN nclasea ca     ON ca.codclasea   = na.clasa
    LEFT JOIN nclaseas cs   ON cs.codclaseas  = na.clasastatist
    LEFT JOIN ioart io       ON io.codioart    = lg.codioart
    LEFT JOIN ioart1 io1     ON io1.codioart   = lg.codioart  AND (t.an*12+t.luna) BETWEEN  io1.ALStart and  io1.ALStop
    LEFT JOIN ncont nc       ON nc.codcont     = io1.cont
    LEFT JOIN nartobj1 nao1 ON nao1.codobiect = t1.codobiect AND (t.an*12+t.luna) BETWEEN nao1.ALStart and nao1.ALStop
    LEFT JOIN transflink tl ON tl.codtransf1  = lg.codtransf1
    LEFT JOIN comanda1 c1   ON c1.codcomanda1 = tl.codliniecomanda
    LEFT JOIN comanda c     ON c.codcomanda   = c1.codcomanda
    LEFT JOIN nartcli fobj   ON fobj.codobiect = t1.codobiect AND fobj.codpart = lg.furn' || coalesce(sJoinUMA,'') || gSuplJoins || '
  ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
  PERFORM pkg_list_base_livrtransf_ProcessParams();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_manprod_processlist</obj_name>
  <obj_hashval>94d98b7ccde967687449d29e39fe8ada</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_manprod_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;
  vUserID      numeric;
  sAnLunaLucru varchar := COALESCE((getAnLucru() * 12 + getLunaLucru())::varchar,'0');
BEGIN
  --Adina 11.05.2021 - alstart, alstop
  --Bogdan 14.09.2020
  CALL PRC_AL_CHECK('tarifeman1', 0);

  vUserID := current_setting ('PKG_GLOBALS.USERID', true) ::numeric;
  gSuplCols := 'NARTOBJ PROD, PRODCOMP PC, NCLASEA CLSP';

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = PROD.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = PROD.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols( aLISTID, aLISTVER, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config ('PKG_LIST_BASE_MANPROD.gSuplCols',gSuplCols,false);

  IF current_setting ('PKG_LIST_BASE_MANPROD.p_flgAllArt', true) ::numeric = 1 THEN
    DELETE FROM tmp_prodcomp_man   WHERE userid = vuserid;
    DELETE FROM tmp_proiectnod_man WHERE userid = vUserID;

    IF current_setting ('PKG_LIST_BASE_MANPROD.p_Tip', true) ::numeric = 0 THEN
      INSERT INTO tmp_prodcomp_man (codprodcomp, cant, pret, userid)
      (SELECT PC.codprodcomp, PC.cant, PC.Pret, vUserID FROM prodcomp PC WHERE coalesce (pc.ascuns, 0) = 0);
    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 and coalesce (p.ascuns, 0) = 0;
    END IF;
  END IF;

  sInsert := 'INSERT INTO '||tmpName
          || '(
          SYSCOD,
          NAV_CodDoc,
          NAV_TipDoc,
          Reteta,
          Produs,
          SectieExec,
          Ordine,
          NrOp,
          Operatie,
          LocMunca,
          DenTarif,
          tarif,
          tu,
          valoare,
          dsv,
          bps,
          tpi,
          obs,
          detalii,
          tip,
          nivel,
          Nod,
          Parinte,
          CantP '
          || coalesce (gUserFields ,'')|| ')
        ';
  sSelect := '
        select pc.codprodcomp,
          pc.codprodcomp,
          504,
          pc.obs        Reteta,
          prod.denumire Produs,
          G.Den_Gest    SectieExec,
          pm.Ordine,
          pm.NrOp,
          op.denumire Operatie,
          lm.denumire LocMunca,
          t.denumire  DenTarif,
          t.tarif,
          tmp.cant / pm.bps * pm.tu,
          round (tmp.cant / pm.bps * (pm.tu * t.tarif) / 60,5) valoare,
          pm.dsv,
          pm.bps,
          pm.tpi,
          pm.obs,
          pm.detalii,
          ''Reteta'',
          1,
          LPAD (pm.ordine::varchar, 2, ''0'') ,
          prod.denumire,
          tmp.cant / pc.cant '
          || coalesce (gUserAlias ,'') || '
        from prodcomp                 pc
          INNER JOIN TMP_PRODCOMP_MAN TMP  ON PC.CodProdComp  = TMP.CodProdComp
          inner join nartobj          prod on prod.codobiect  = pc.codobiect
          inner join nart             artp on prod.codarticol = artp.codarticol
          inner join prodgest         pg   on pc.codprodcomp  = pg.codprodcomp
          inner join ngest            g    on coalesce (pg.codgest, 0) = g.codgest
          inner join (select m.*, row_number() over() Ordine from prodman m order by m.nrop, m.detalii) pm on pm.codprodcomp = pc.codprodcomp and pm.codprodgest = pg.codprodgest
          inner join noper            op   on pm.codop  = op.codop
          inner join locmunca         lm   on lm.codloc = pm.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 PM.CODTARIF             = T.CODTARIF
          LEFT  JOIN NCLASEA          CLSP ON coalesce (ARTP.CLASA,0) = CLSP.CODCLASEA'
          || coalesce (gSuplJoins ,'') || '
        where coalesce (pc.anulat, 0) = 0 and tmp.userid = ' || coalesce (vuserid::varchar,'') || '
        union all
        select p.codproiect,
          p.codproiect,
          507,
          p.versiune    Reteta,
          prod.denumire Produs,
          G.Den_Gest    SectieExec,
          pm.Ordine,
          coalesce (PN.ordine,0) ,
          op.denumire Operatie,
          lm.denumire LocMunca,
          t.denumire  DenTarif,
          t.tarif,
          tmp.cant / PN0.cant * PN.cant / pm.bps * pm.tu,
          round (tmp.cant / PN0.cant * PN.cant / pm.bps * (pm.tu * t.tarif) / 60,5) valoare,
          pm.dsv,
          pm.bps,
          pm.tpi,
          pm.obs,
          pm.detalii,
          ''Proiect'',
          coalesce (PN.nivel,0) ,
          X.IND,
          case when coalesce (pnp.codproiectnod,0) = 0 then pp.denumire else objp.denumire                  end,
          case when coalesce (pnp.codproiectnod,0) = 0 then tmp.cant    else tmp.cant / PN0.cant * PNP.cant end ' || coalesce (gUserAlias,'') || '
        from PROIECT                    P
          INNER JOIN TMP_PROIECTNOD_MAN TMP  ON P.CodProiect    = TMP.CodProiect
          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 PN.codreteta    = pc.codprodcomp
          inner join nartobj            prod on prod.codobiect  = p.codobiectprod
          inner join nart               artp on prod.codarticol = artp.codarticol
          inner join prodgest           pg   on pc.codprodcomp  = pg.codprodcomp
          inner join ngest              g    on coalesce (pg.codgest, 0) = g.codgest
          inner join (select m.*, row_number() over() Ordine from prodman m order by m.nrop, m.detalii) pm on pm.codprodcomp = pc.codprodcomp and pm.codprodgest = pg.codprodgest
          inner join noper              op   on pm.codop  = op.codop
          inner join locmunca           lm   on lm.codloc = pm.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 PM.CODTARIF    = T.CODTARIF
          LEFT  JOIN PROIECTNOD         PNP  ON PN.NODORIGINAL = PNP.CODPROIECTNOD
          left  join nartobj            pp   on pn0.codobiect  = pp.codobiect
          left  join nartobj            objp on pnp.codobiect  = objp.codobiect
          LEFT  JOIN NCLASEA            CLSP ON coalesce (ARTP.CLASA,0) = CLSP.CODCLASEA
          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'
          || coalesce (gSuplJoins ,'') || '
        where
          coalesce (pc.anulat, 0) = 0 and pn.codreteta &gt; 0 and tmp.userid = ' || coalesce (vuserid::varchar,'');

  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;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_mariridimin_processlist</obj_name>
  <obj_hashval>4e341d0c0029fdd2f8ca1acf75edbaf7</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_mariridimin_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'livr l, livr1 l1, nirstoc ns, nir nir, nartobj nobj, nart nart, num num, nclasea nca, ngest ng, ioart io, ioart1 io1, iesiri ies, ncont ncont, intrari1 intr1';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 05.04.2021 - alstart,alstop
  --Adina 16.10.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_MARIRIDIMIN.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert :=
  'INSERT INTO ' || tmpName || ' (
    NAV_CodDoc, NAV_TipDoc,DOCUMENT,PREFIXDOC,NRDOC,DATADOC,DENUMIRE,CANT,DEN_UM,CLASA,GEST_SURSA,GEST_DEST,CONT_SURSA,CONT_DEST,
    pretinreg,pretachiz,OPERAT ' || gUserFields || ')
  SELECT
    ies.codies NAV_CodDoc, ies.tipdoc NAV_TipDoc,
    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
      ELSE ies.prefixdoc||ies.nrdoc||'' / ''||ies.datadoc
    END document,
    ies.prefixdoc,ies.nrdoc,ies.datadoc, nobj.denumire,l1.cant,num.den_um,coalesce(nca.den_clasea,''-''),
    ng.den_gest AS gest_sursa,ng.den_gest AS gest_dest, ncont.simbol cont_sursa,ncont.simbol AS cont_dest,
    ns.pret pretinreg ,intr1.pu pretachiz ,(case when ies.operat=0 then ''Nu'' else ''Da'' end) operat ' || gUserAlias || '
  FROM livr l
    LEFT 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 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 AND (ies.an * 12 +ies.luna) BETWEEN io1.ALStart and io1.ALStop
    LEFT JOIN iesiri ies       ON ies.codies       = l.codies
    LEFT JOIN ncont           ON io1.cont         = ncont.codcont
    LEFT JOIN intrari1 intr1   ON intr1.codintr1   = ns.codintr1' || gSuplJoins || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('', 'subunitatea', '
  WHERE',NULL),'') || '
    AND l.tiplivr  = ' || coalesce(current_setting('PKG_LIST_BASE_MARIRIDIMIN.vTipLista', true),'') || '
    AND IES.DATADOC BETWEEN TO_DATE(''' || coalesce(To_Char(PKG_LIST_SELECTPER_DataIni(),'dd.mm.yyyy'),'') || ''',''DD/MM/YYYY'')
    AND TO_DATE(''' || coalesce(To_Char(PKG_LIST_SELECTPER_DataFin(),'dd.mm.yyyy'),'') || ''',''DD/MM/YYYY'') ';

  IF  current_setting('PKG_LIST_SELECTPER.vToateArt', true)::numeric = 0 THEN
    sInsert := coalesce(sInsert,'') || '
    AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' AND VALOARE = NOBJ.CODOBIECT::varchar ) ';
  END IF;

  IF  current_setting('PKG_LIST_SELECTPER.vToateGest', true)::numeric = 0 THEN
    sInsert := coalesce(sInsert,'') || '
    AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = NG.CODGEST::varchar) ';
  END IF;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_mifix_setjoinuri</obj_name>
  <obj_hashval>979c654bf4aa68c6900d9884300b6f2b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_mifix_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 21.09.2020
  PERFORM Pkg_List_Struct_SetTableSpec (current_setting ('PKG_LIST_BASE_MIFIX.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_mifix_setparams</obj_name>
  <obj_hashval>ef116665c0d0b7fb35bcbfe59ce9160e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_mifix_setparams(p_toatemf numeric DEFAULT 1, p_tipselmf numeric DEFAULT 0, p_amo numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  --Bogdan 21.09.2020
  perform set_config ('PKG_LIST_BASE_MIFIX.v_ToateMF' ,p_ToateMF::varchar ,false);
  perform set_config ('PKG_LIST_BASE_MIFIX.v_TipSelMF',p_TipSelMF::varchar,false);
  perform set_config ('PKG_LIST_BASE_MIFIX.v_Amo'     ,p_Amo::varchar     ,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_miscari_processlist</obj_name>
  <obj_hashval>88e23c4850a8a6d747c03272f8100712</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_miscari_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  gSuplCols   varchar :=  'NARTOBJ NOBJ, NART N, NPART PROD, NPART FURN, NARTAMB AA, NCONT CDOC, NCONT CS, NCONT CD, ' || 'NGEST NGS, NGEST NGD, NAGENDA AGS, NAGENDA AGD, TRANSF T, TRANSF1 T1, IESIRI I, IESIRI1 I1';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Adina 09.03.2021 - prc_al_check
  --Adina 05.12.2020 tichet 41435
  --Florin 06.08.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT'    , 'OEXT'      , 'OEXT.CODOBIECT           = NOBJ.CODOBIECT'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR'    , 'OATR'      , 'OATR.CODOBIECT           = NOBJ.CODOBIECT'  ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'ANALIZANOD'    , 'ANOD'      , 'ANOD.CODANALIZANOD       = I1.CODANALIZANOD',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'ANALIZA'       , '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, 'NCLASEG'       , 'CGS'       , 'CGS.CODCLASEG            = NGS.CODCLASA',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NCLASEG'       , 'CGD'       , 'CGD.CODCLASEG            = NGD.CODCLASA',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NACTIVIT'      , 'ACTD'      , 'ACTD.CODACTIVIT          = NGD.CODACTIVIT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NACTIVIT'      , 'ACTS'      , 'ACTS.CODACTIVIT          = NGS.CODACTIVIT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPERS'         , 'OPER'      , 'OPER.LOGONNAME           = COALESCE(I.USERID, T.USERID)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'TMP_UTILIZATOR', 'UTILIZATOR', 'UTILIZATOR.CODUTILIZATOR = COALESCE(I.USERID, T.USERID)');
  call pkg_list_struct_addsupltabs(gSuplCols, 'DOCCARNETE'    , 'DOC'       , 'DOC.CODCARNET            = COALESCE(I.CARNETDOC, T.CARNETDOC)');
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_MISCARI.gSuplCols', gSuplCols, FALSE);

  DELETE FROM tmp_manevra_serii;
  IF current_setting('PKG_LIST_SELECTPER.bAduSerii', TRUE)::NUMERIC = 1 THEN
    PERFORM pkg_list_base_miscari_GetNirCuSerii();
    PERFORM pkg_list_base_utils_BAGA_SERII_IN_TMP(0);
  END IF;

  CALL PRC_AL_CHECK('IOART1');
  CALL PRC_AL_CHECK('NART1');
  CALL PRC_AL_CHECK('NTVA1');

  sInsert := 'INSERT INTO ' || tmpName || '(
      NAV_CodDoc,NAV_TipDoc,DOCUMENT,SeriaDoc,PREFIXDOC,NRDOC,NRI,DATADOC,DENUMIRE,CANTS,CANTD,DEN_UMS,DEN_UMD,CLASA,GEST_SURSA,GEST_DEST,CONT_SURSA,CONT_DEST,
      PUINREGS,PUINREGD,PUACHIZS,PUACHIZD,PMAXS,PMAXD,PRODUCATOR,FURNIZOR,TG,OPERAT,VALINREGS,VALACHIZS,VALINREGD,VALACHIZD,BLOCAT,OBS,
      STORNO,TIPINREG,CODINTERN,CODEXTERN,PROCENT,TIPSERIE,SERII,SEROBS,TVACOLECTAT,SUBUNITATEA,
      UMALT1, UMALT2, S_CANTUM1, S_CANTUM2, S_D1, S_D2, S_D3, D_CANTUM1, D_CANTUM2, D_D1, D_D2, D_D3,
      CLASAS,DEN_CONTS,DEN_CONTD,PROVIZION, ADGESTS, ADGESTD,
      CONT_DOC, PIESDVAL, LOCNIR, LOCLIVR ' || gUserFields || ')
    WITH
     surse AS
     (
      SELECT
        l1.codlivr1,t1.umsec,nsdest.codnirstoc,NSDEST.TIPSERIE ,nsdest.furn,nsdest.tg,nsdest.codnirstocparinte,t1.codcont contdoc, COALESCE(lv.gest,nir.gest) codgest, io.den_ioart,
        io1.cont,t.codtransf,tt1.codtransf1,tt1.codobiect,nsdest.cantfurn / num1s.paritate cantS,nsdest.cantnir / num1d.paritate cantD, num1s.den_um1 den_um1s,NUM1D.DEN_UM1 DEN_UM1d ,num1s.paritate,
        COALESCE(NSSURSA.PRET,LV.PRETINREG) * num1s.paritate PUINREGS, nsdest.pret* num1d.paritate PUInregD,
        COALESCE((NSSURSA.PRET - NSSURSA.ADAOS),LV.PRETACHIZ) * num1s.paritate puAchizS,(NSdest.pret - nsdest.adaos) * num1d.paritate PUACHIZD,
        nssursa.pumaximal pmaxS,nsdest.pumaximal pmaxd,t.subunitatea,T.USERID,L1.CANTUM1,L1.CANTUM2,NSSURSA.D1,NSSURSA.D2,NSSURSA.D3,loc.denumire locatie
      FROM transf t
        inner join transf1 tt1       on tt1.codtransf   = t.codtransf
        LEFT JOIN livr l             ON l.codtransf     = t.codtransf AND l.tiplivr = t.tipdoc
        LEFT JOIN livr1 l1           ON l1.codlivr      = l.codlivr and l1.codies1 = tt1.codtransf1
        LEFT JOIN LIVRVAL LV         ON L1.CODLIVR1     = LV.CODLIVR1
        LEFT JOIN nirstoc nsdest     ON nsdest.codlivr1 = l1.codlivr1
        LEFT JOIN transf1 t1         ON t1.codtransf1   = nsdest.codtransf1
        LEFT JOIN nirstoc nssursa    ON nsdest.codnirstocparinte = nssursa.codnirstoc
        LEFT JOIN nir                ON nir.codnir     = nssursa.codnir
        LEFT JOIN ioart io           ON io.codioart    = COALESCE(lv.codioart, nssursa.codioart)
        LEFT JOIN ioart1         io1 on io1.codioart   = io.codioart and t.an*12+t.luna between io1.alstart and io1.alstop
        LEFT JOIN num1 num1s         on num1s.codum1   = l1.umsec
        LEFT JOIN num1 num1d         ON num1d.codum1   = nsdest.umsec
        LEFT JOIN nlocatii loc       on loc.codlocatie = COALESCE(nssursa.codlocatie,0)
      WHERE 1 = 1 ' || COALESCE(pkg_list_base_miscari_GetCondData('T'),'') || COALESCE(pkg_list_base_miscari_GetCondArt('T1.CODOBIECT'),'')
        || COALESCE(pkg_list_base_miscari_GetCondGest('COALESCE(nir.gest,lv.gest)'),'') || COALESCE(PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL),'') || '
     ),
     dest AS
     (
      SELECT
        l1.codlivr1,t.codtransf,t1.codtransf1,nir.gest codgest,ns.codioart,io.den_ioart,io1.cont,ns.codnirstoc,t.subunitatea,t.userid,ns.provizion,
        NS.CANTUM1,NS.CANTUM2,NS.D1,NS.D2,NS.D3,loc.denumire locatie
      FROM transf t
        LEFT JOIN transf1 t1         ON t1.codtransf   = t.codtransf
        LEFT JOIN nir                ON t.codtransf    = nir.codtransf
        LEFT JOIN nirstoc ns         ON ns.codtransf1  = t1.codtransf1 AND ns.codnir = nir.codnir
        LEFT JOIN ioart io           ON ns.codioart    = io.codioart
        LEFT JOIN ioart1         io1 on io1.codioart   = io.codioart and t.an*12+t.luna between io1.alstart and io1.alstop
        LEFT JOIN livr1 l1           ON ns.codlivr1    = l1.codlivr1
        LEFT JOIN nlocatii loc       on loc.codlocatie = COALESCE(ns.codlocatie,0)
      WHERE 1 = 1 ' || COALESCE(pkg_list_base_miscari_GetCondData('T'),'') || COALESCE(PKG_LIST_BASE_UTILS_COND_SUBUNIT('T',NULL,NULL,NULL),'')
          || coalesce(pkg_list_base_miscari_GetCondArt('T1.CODOBIECT') ,'') || '
    )
    SELECT
      t.codtransf NAV_CodDoc, t.TIPDOC NAV_TipDoc,
      CASE WHEN t.tipdoc = 12 THEN ''Transf. '' WHEN t.tipdoc = 13 THEN ''Modif. pret '' END ||t.prefixdoc||t.nrdoc||'' / ''||to_char(t.datadoc,''dd.mm.yyyy'') as document,
      t.seriadoc,t.prefixdoc,t.nrdoc, NULL nri, t.datadoc, nobj.denumire,surse.cants,surse.cantd,surse.den_um1s,surse.den_um1d,COALESCE(nca.den_clasea,''-''),
      ngs.den_gest, ngd.den_gest, cs.simbol,cd.simbol, surse.PUInregS, surse.PUInregD, surse.puachizs, surse.puachizd,
      surse.PMAXS, surse.pMaxD, PROD.DEN_PART PRODUCATOR,FURN.DEN_PART FURNIZOR, TMP.TG, (Case When t.operat=0 then ''Nu'' else ''Da'' end) operat,
      surse.cants * surse.puInregS valInregS, surse.cants * surse.puachizS valAchizS , surse.cantd * surse.puInregD valInregD, surse.cantd * surse.puAchizD ValAchizD,
      (Case When t.blocat=0 then ''Nu'' else ''Da'' END) blocat,t.obs,
      CASE WHEN t.TIPDOC = 12 THEN (Case When COALESCE(t.storno,0)=0 then''Nu'' ELSE ''Da'' end) ELSE ''-'' END storno,
      CASE
        WHEN t.TIPDOC &lt;&gt; 13 THEN ''-''
        WHEN t.TIPMODIFPRET = 0 THEN ''PU inreg. nou fara reevaluare PU achizitie ''
        WHEN t.TIPMODIFPRET = 1 THEN ''PU inreg. nou + reevaluare PU achizitie astfel incat adaos = 0  ''
        WHEN t.TIPMODIFPRET = 2 THEN ''PU inreg. nou + reevaluare PU achizitie numai daca adaos &lt; 0 ''
        WHEN t.TIPMODIFPRET = 3 THEN ''PU achiz. nou fara afectarea PU inregistrare ''
        ELSE ''-''
      END tipinreg,
      nobj.codintern,nobj.codextern,NTVA1.PROCENT, (Case  When SURSE.TIPSERIE=0 then ''fara serie'' When SURSE.TIPSERIE=1 then ''serie pe bucata'' When SURSE.TIPSERIE=2 THEN''serie pe lot'' END) tipserie, TMP.SERII, TMP.SERII_OBS,
      0 TVACOLECTAT,sub.den_subunit subunitatea,
      UMALT1.DEN_UM, UMALT2.DEN_UM, SURSE.CANTUM1, SURSE.CANTUM2, SURSE.D1, SURSE.D2, SURSE.D3, DEST.CANTUM1, DEST.CANTUM2, DEST.D1, DEST.D2, DEST.D3,
      NCLS.DEN_CLASEAS,
      surse.den_ioart den_conts, dest.den_ioart den_contd,dest.PROVIZION,
      (select getadresa.wme_result from getadresa('''',ags.SECTOR,ags.STRADA,ags.NR1,ags.NR2,ags.BLOC,ags.SCARA,ags.ETAJ,ags.APART,ags.CODPOSTAL)) AdGestS,
      (select getadresa.wme_result from getadresa('''',agd.SECTOR,agd.STRADA,agd.NR1,agd.NR2,agd.BLOC,agd.SCARA,agd.ETAJ,agd.APART,agd.CODPOSTAL)) AdGestD,
      cdoc.simbol, NULL piesdval, surse.locatie, dest.locatie ' || gUserAlias || '
    FROM surse
      LEFT JOIN dest                  ON dest.codnirstoc = surse.codnirstoc
      LEFT JOIN transf t              ON t.codtransf     = surse.codtransf
      LEFT JOIN transf1 t1            ON t1.codtransf1   = surse.codtransf1
      LEFT JOIN iesiri i              ON i.codies        = t.codtransf-t.codtransf
      LEFT JOIN iesiri1 i1            ON i1.codies1      = t.codtransf-t.codtransf
      LEFT JOIN nartobj nobj          ON nobj.codobiect  = surse.codobiect
      LEFT JOIN nart n                ON n.codarticol    = nobj.codarticol
      LEFT JOIN NPART PROD            ON PROD.CODPART    = NOBJ.CODPRODUCATOR
      LEFT JOIN NPART FURN            ON FURN.CODPART    = SURSE.FURN
      LEFT JOIN nclasea nca           ON nca.codclasea   = n.clasa
      LEFT JOIN ngest ngs             ON ngs.codgest     = surse.codgest
      LEFT JOIN ngest ngd             ON ngd.codgest     = dest.codgest
      LEFT JOIN ncont cs              ON cs.codcont      = surse.cont
      LEFT JOIN ncont cd              ON cd.codcont      = dest.cont
      LEFT JOIN nagenda ags           ON ags.codgest     = ngs.codgest
      LEFT JOIN nagenda agd           ON agd.codgest     = ngs.codgest
      LEFT JOIN NART1         N1      ON N1.CODARTICOL   = N.CODARTICOL AND t.an*12+t.luna between N1.alstart and N1.alstop
      LEFT JOIN NTVA1         NTVA1   on NTVA1.CODTVA    = N1.CODTVA AND t.an*12+t.luna between NTVA1.alstart and NTVA1.alstop
      LEFT JOIN NUM UMALT1            ON N.UM1           = UMALT1.CODUM
      LEFT JOIN NUM UMALT2            ON N.UM2           = UMALT2.CODUM
      LEFT JOIN TMP_MANEVRA_SERII TMP ON TMP.CODNIRSTOC  = SURSE.CODNIRSTOC
      LEFT JOIN NSUBUNIT SUB          ON SUB.CODSUBUNIT  = SURSE.SUBUNITATEA
      LEFT JOIN NCLASEAS NCLS         ON NCLS.CODCLASEAS = N.CLASASTATIST
      LEFT JOIN nartamb aa            ON aa.codobiect    = surse.codobiect AND aa.umsec = surse.umsec
      LEFT JOIN ncont cdoc            ON cdoc.codcont    = surse.contdoc' || gSuplJoins || '
    WHERE 1 = 1 ' || COALESCE(pkg_list_base_miscari_GetCondData('t'),'') || COALESCE(pkg_list_base_miscari_GetCondArt('t1.CODOBIECT') ,'')
      || COALESCE(pkg_list_base_miscari_GetCondGest('NGS.CODGEST') ,'') || COALESCE(PKG_LIST_BASE_UTILS_COND_SUBUNIT('t', 'SUBUNITATEA',NULL,NULL),'') || '
    UNION ALL
    SELECT ------- diminuari si mariri ----
      i.codies NAV_CodDoc, i.tipdoc NAV_TipDoc,
      CASE WHEN l.tiplivr = 14 THEN ''Dimin. '' WHEN l.tiplivr = 15 THEN ''Marire '' END || i.prefixdoc||i.nrdoc||'' / ''||to_char(i.datadoc,''dd.mm.yyyy'') as document,
      i.seriadoc,i.prefixdoc,i.nrdoc,i.nri,i.datadoc, nobj.denumire,l1.cant/num1.paritate cants,null cantd,num1.den_um1,null den_um1d,COALESCE(nca.den_clasea,''-''),
      ngs.den_gest, ngd.den_gest, cs.simbol,cd.simbol, COALESCE(NS.PRET,lv.pretinreg) * num1.paritate PUInreg, COALESCE(NS.PRET,lv.pretachiz) * num1.paritate pretRec,
      CASE WHEN LV.CODLIVR1 IS NULL THEN (NS.PRET - NS.ADAOS) * NUM1.PARITATE ELSE LV.PRETACHIZ * NUM1.PARITATE END * num1.paritate puachizs,
      0 puachizd , 0 pmaxs ,ns.pumaximal pmaxd, PROD.DEN_PART PRODUCATOR,FURN.DEN_PART FURNIZOR, TMP.TG, (Case  When i.operat=0 then ''Nu'' else ''Da'' end) operat,
      l1.cant * CASE WHEN LV.CODLIVR1 IS NULL THEN NS.PRET ELSE LV.PRETINREG END valInregS ,
      l1.cant * CASE WHEN LV.CODLIVR1 IS NULL THEN (NS.PRET - NS.ADAOS) ELSE LV.PRETACHIZ END ValAchizS, 0 ValInregD,0 ValAchizD,
      (Case When i.blocat=0 then ''Nu'' else ''Da'' end) blocat, i.obs, null storno,
      tc.denumire tipinreg, nobj.codintern,nobj.codextern,ntva1.PROCENT,
      (Case  When NS.TIPSERIE=0 then ''fara serie'' When NS.TIPSERIE=1 then ''serie pe bucata'' When NS.TIPSERIE=2 then ''serie pe lot'' end) tipserie, TMP.SERII, TMP.SERII_OBS, t1.TVA TVACOLECTAT,SUB.DEN_SUBUNIT SUBUNITATEA,
      UMALT1.DEN_UM, UMALT2.DEN_UM, (Case  When i.TIPDOC=14 then L1.CANTUM1 else 0 end), (Case  When i.TIPDOC=14 then L1.CANTUM2 else 0 end), NS.D1, NS.D2, NS.D3,
      (Case  When i.TIPDOC=15 then L1.CANTUM1 else 0 end), (Case  When i.TIPDOC=15 then L1.CANTUM2 else 0 end), NS.D1, NS.D2, NS.D3,
      NCLS.DEN_CLASEAS, io.den_ioart den_consts,io.den_ioart den_constd,NULL PROVIZION,
      (select getadresa.wme_result from getadresa('''',ags.SECTOR,ags.STRADA,ags.NR1,ags.NR2,ags.BLOC,ags.SCARA,ags.ETAJ,ags.APART,ags.CODPOSTAL)) AdGestS,
      (select getadresa.wme_result from getadresa('''',agd.SECTOR,agd.STRADA,agd.NR1,agd.NR2,agd.BLOC,agd.SCARA,agd.ETAJ,agd.APART,agd.CODPOSTAL)) AdGestD,
      cdoc.simbol, iesval.val/l1.cant*num1.paritate piesval, case when i.tipdoc = 14 then loc.denumire else ''...nedefinita...'' end,
      case when i.tipdoc = 15 then loc.denumire else ''...nedefinita...'' end ' || gUserAlias || '
    FROM iesiri i
      INNER JOIN livr l    ON l.codies      = i.codies AND l.tiplivr = i.tipdoc
      LEFT JOIN transf t   ON t.codtransf   = i.codies - i.codies
      LEFT JOIN transf1 t1 ON t1.codtransf1 = i.codies - i.codies
      LEFT JOIN livr1 l1   ON l.codlivr     = l1.codlivr
      LEFT JOIN (
        SELECT SUM(I1.CANT * I1.PU) VAL, IVL.CODLIVR1
        FROM IESIRI1 I1 INNER JOIN IESVALLINK IVL ON IVL.CODIES1 = I1.CODIES1
        GROUP BY IVL.CODLIVR1
      ) IESVAL                        ON IESVAL.CODLIVR1 = L1.CODLIVR1
      LEFT JOIN LIVRVAL LV            ON LV.CODLIVR1     = L1.CODLIVR1
      LEFT JOIN nirstoc ns            ON ns.codnirstoc   = l1.codnirstoc
      LEFT JOIN iesiri1 i1            ON l1.codies1      = i1.codies1
      LEFT JOIN nir                   ON nir.codnir      = ns.codnir
      LEFT JOIN nartobj nobj          ON nobj.codobiect  = i1.codobiect
      LEFT JOIN nart n                ON n.codarticol    = nobj.codarticol
      LEFT JOIN NUM UMALT1            ON N.UM1           = UMALT1.CODUM
      LEFT JOIN NUM UMALT2            ON N.UM2           = UMALT2.CODUM
      LEFT JOIN nclasea nca           ON nca.codclasea   = n.clasa
      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 ngest ngs             ON ngs.codgest     = COALESCE(nir.gest,lv.gest)
      LEFT JOIN ngest ngd             ON ngd.codgest     = COALESCE(nir.gest,lv.gest)
      LEFT JOIN ncont cs              ON cs.codcont      = io1.cont
      LEFT JOIN ncont cd              ON cd.codcont      = io1.cont
      LEFT JOIN nagenda ags           ON ags.codgest     = ngs.codgest
      LEFT JOIN nagenda agd           ON agd.codgest     = ngs.codgest
      LEFT JOIN num1                  on L1.umsec        = num1.codum1
      LEFT JOIN NPART PROD            ON PROD.CODPART    = NOBJ.CODPRODUCATOR
      LEFT JOIN NPART FURN            ON FURN.CODPART    = NS.FURN
      LEFT JOIN NART1         N1      ON N1.CODARTICOL   = N.CODARTICOL AND I.an*12+I.luna between N1.alstart    and N1.alstop
      LEFT JOIN NTVA1         NTVA1   on NTVA1.CODTVA    = N1.CODTVA    AND I.an*12+I.luna between NTVA1.alstart and NTVA1.alstop
      LEFT JOIN TMP_MANEVRA_SERII TMP ON TMP.CODNIRSTOC  = NS.CODNIRSTOC
      LEFT JOIN NSUBUNIT SUB          ON SUB.CODSUBUNIT  = i.SUBUNITATEA
      LEFT JOIN NCLASEAS NCLS         ON NCLS.CODCLASEAS = N.CLASASTATIST
      LEFT JOIN nartamb aa            ON aa.codobiect    = i1.codobiect AND aa.umsec = i1.umsec
      LEFT JOIN tipchelt tc           ON tc.codtipchelt  = i.tipchelt
      LEFT JOIN ncont cdoc            ON cdoc.codcont    = i1.cont
      LEFT JOIN nlocatii loc          on loc.codlocatie  = COALESCE(ns.codlocatie,0)' || gSuplJoins || '
    WHERE i.tipdoc IN (14,15) ' || COALESCE(pkg_list_base_miscari_GetCondData('I'),'') || COALESCE(pkg_list_base_miscari_GetCondArt('I1.CODOBIECT') ,'')
      || coalesce(pkg_list_base_miscari_GetCondGest('NGS.CODGEST') ,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I', 'SUBUNITATEA',NULL,NULL),'');
--    INSERT INTO x (view_name, test) VALUES ('misc', sinsert);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_mpvd_setjoinuri</obj_name>
  <obj_hashval>102f7d1d8e482ff264b5d4c847014149</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_mpvd_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
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_mpvp_setjoinuri</obj_name>
  <obj_hashval>cfb125f7e9b9ee1807f18a45d5bdb0ba</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_mpvp_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.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_naproviz4_umpletemporar</obj_name>
  <obj_hashval>dc733a34f2098efa900c4fa82e78cf64</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz4_umpletemporar()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSelect          VARCHAR := '';
  vToateGest       BOOLEAN;
  vToateIOArt      BOOLEAN;
  vAux             VARCHAR := '';
  vSelStocReal     VARCHAR := '';
  vCateGest        NUMERIC       := 0;
  vCateLGest       NUMERIC        := 0;
  vProductie       BOOLEAN;
  vCondIntrari     VARCHAR := '';
  vCondIesiri      VARCHAR := '';
  vNrZileStocMed   NUMERIC;

  vGestString     varchar := '';
  vIOArtString     varchar:= '';
  vCond_Subunit_C varchar := '';
  vCond_Subunit_G varchar := '';
  vSetimana       NUMERIC;
  vUserID         NUMERIC;
  vAn             NUMERIC;
  vPrevAn         NUMERIC;
  vPrevSetimana   NUMERIC;
  vPPrevAn         NUMERIC;
  vPPrevSetimana  NUMERIC;
  vNextAn         NUMERIC;
  vNextSetimana   NUMERIC;
  vCount           NUMERIC;
BEGIN
  --Adina 01 septembrie 2020 - netestat pt.ca nu stiu unde se apeleaza
  vUserId        := COALESCE(current_setting('PKG_GLOBALS.USERID'       , true)::numeric, 0);
  vToateGest     := (current_setting('PKG_LIST_SELECTSCAD.vToateGest'   , true)::NUMERIC = 1)::boolean;
  vToateIOArt    := (current_setting('PKG_LIST_SELECTSCAD.vToateGest'   , true)::NUMERIC = 1)::boolean;
  vProductie     :=  (current_setting('PKG_LIST_SELECTSCAD.vCentralizat', true)::numeric = 1)::boolean;
  vSetimana      := current_setting('PKG_LIST_SELECTSCAD.vSetimana'     , true)::numeric;
  vAn            := getANLUCRU();

  if vProductie then
    vCondIntrari := ' AND C1.TERMEN &lt; to_date(current_setting(''PKG_LIST_SELECTSCAD.vDataIni'', true), ''DD.MM.YYYY'') ';
    if to_date( current_setting('PKG_LIST_SELECTSCAD.vDataIni', true), 'DD.MM.YYYY') = to_date(current_setting('PKG_LIST_SELECTSCAD.vDataScad', true), 'DD.MM.YYYY') then
      vCondIesiri  := ' AND C1.TERMEN BETWEEN to_date(current_setting(''PKG_LIST_SELECTSCAD.vDataIni'', true), ''DD.MM.YYYY'') AND to_date(current_setting(''PKG_LIST_SELECTSCAD.vDataScad'', true), ''DD.MM.YYYY'') - 1 ';
    else
      vCondIesiri  := ' AND C1.TERMEN BETWEEN to_date(current_setting(''PKG_LIST_SELECTSCAD.vDataIni'', true), ''DD.MM.YYYY'') AND to_date(current_setting(''PKG_LIST_SELECTSCAD.vDataScad'', true), ''DD.MM.YYYY'') ';
    end if;
  end if;

  vNrZileStocMed := fnc_GetValConstanta('NrZileStocMed', getANLUCRU(), getLUNALUCRU()) ;
  vSelStocReal := '
      SELECT NS.CODOBIECT, SUM(case when n.operat = 0 then ns.cantnir else ns.rest end) CANT
      FROM NIRSTOC NS
        INNER JOIN NARTOBJ OBJ ON OBJ.CODOBIECT = NS.CODOBIECT
        INNER JOIN NIR     N   ON NS.CODNIR     = N.CODNIR
        INNER JOIN NGEST   G   ON G.CodGest     = N.GEST '||vCond_Subunit_G||'
        INNER JOIN (SELECT A.CODARTICOL, COUNT(O.CODOBIECT) NR
                    FROM NART A
                         INNER JOIN NARTOBJ O ON O.CODARTICOL = A.CODARTICOL
                    GROUP BY A.CODARTICOL) NROBJ ON OBJ.CODARTICOL = NROBJ.CODARTICOL
      WHERE (NROBJ.NR = 1 OR (NROBJ.NR &gt; 1 AND EXISTS (SELECT ATR.CODOBIECT FROM NATROBJ ATR WHERE ATR.CODOBIECT = OBJ.CODOBIECT)))
      and ((ns.rest &lt;&gt; 0 and n.operat = 1) or (ns.rest = 0 and n.operat = 0 and n.tipnir = 12)) and g.tip &lt;&gt; 4  ';
  vAux := '
      AND ';
  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
      vSelStocReal := vSelStocReal || vAux||' EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = N.GEST::varchar) ';
    elsif vCateGest = 0 then
      vSelStocReal := vSelStocReal || vAux||' EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND VALOARE = NS.CODLOCATIE::varchar) ';
    else
      vSelStocReal := vSelStocReal || vAux||' (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;
    vAux := '
        AND';
    vGestString := ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = N.GEST::varchar) ';
  end if;

  if NOT vToateIOArt then
    vSelStocReal := vSelStocReal || vAux||' EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND VALOARE = NS.CODIOAR::varcharT ) ';
    vIOArtString := ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND VALOARE = NS.CODIOART::varchar ) ';
  end if;
  vSelStocReal := vSelStocReal ||'
      GROUP BY NS.CODOBIECT';

  vSelStocReal := vSelStocReal||'
      UNION ALL
      SELECT OBJ.CODOBIECT, SUM(case when n.operat = 0 then ns.cantnir else ns.rest end) CANT
      FROM NARTOBJ OBJ
        INNER JOIN NARTOBJ O  ON OBJ.CODARTICOL = O.CODARTICOL
        INNER JOIN NIRSTOC NS ON O.CODOBIECT    = NS.CODOBIECT
        INNER JOIN NIR     N  ON NS.CODNIR      = N.CODNIR
        INNER JOIN NGEST   G  ON G.CodGest      = N.GEST '||vCond_Subunit_G||'
        INNER JOIN (SELECT A.CODARTICOL, COUNT(O.CODOBIECT) NR
                    FROM NART A
                         INNER JOIN NARTOBJ O ON O.CODARTICOL = A.CODARTICOL
                    GROUP BY A.CODARTICOL) NROBJ ON OBJ.CODARTICOL = NROBJ.CODARTICOL
      WHERE (NROBJ.NR &gt; 1 AND NOT EXISTS (SELECT ATR.CODOBIECT FROM NATROBJ ATR WHERE ATR.CODOBIECT = OBJ.CODOBIECT))
      and ((ns.rest &lt;&gt; 0 and n.operat = 1) or (ns.rest = 0 and n.operat = 0 and n.tipnir = 12)) and g.tip &lt;&gt; 4 ';
  vAux := '
      AND ';
  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
      vSelStocReal := vSelStocReal || vAux||' EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = N.GEST::varchar) ';
    elsif vCateGest = 0 then
      vSelStocReal := vSelStocReal || vAux||' EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND VALOARE = NS.CODLOCATIE::varchar) ';
    else
      vSelStocReal := vSelStocReal || vAux||' (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;
    vAux := '
        AND';
    vGestString := ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = N.GEST::varchar) ';
  end if;

  if NOT vToateIOArt then
    vSelStocReal := vSelStocReal || vAux||' EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND VALOARE = NS.CODIOART::varchar ) ';
    vIOArtString := ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND VALOARE = NS.CODIOART::varchar ) ';
  end if;
  vSelStocReal := vSelStocReal ||'
      GROUP BY OBJ.CODOBIECT';

  DELETE FROM TMP_STOCREAL;
  sSelect := 'insert into tmp_stocreal(codobiect,cant) '||vSelStocReal;
  EXECUTE sSelect;

  DELETE FROM TMP_STOCREZ;
  sSelect := 'insert into tmp_stocrez(codobiect,rezervat) '||'SELECT NS.CODOBIECT, SUM(R.REST) REZERVAT '||
      'FROM REZERVATS R '||
        'INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = R.CODNIRSTOC '||
        'INNER JOIN NIR     N  ON NS.CODNIR     = N.CODNIR '||
        'INNER JOIN NGEST   G  ON N.GEST        = G.CodGest '||vCond_Subunit_G||' '||
      'WHERE coalesce(R.REST,0) &gt; 0 '||
      vGestString||
      vIOArtString||
      'GROUP BY NS.CODOBIECT';
  EXECUTE sSelect;

  DELETE FROM TMP_CMD WHERE USERID = vUserId;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||chr(13)||
    'select codobiect, sum(cantc) cantc, sum(canta) canta, sum(resta) resta, ''CF'', '||vUserId::varchar||' from ('||chr(13)||
    '  SELECT C1.CodObiect, C1.CantComandat CantC, C1.CantAcceptat CantA, C1.RestAcceptat RestA '||chr(13)||
    '  FROM COMANDA1 C1'||chr(13)||
    '       INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'||chr(13)||
    '  WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 8 AND C1.RestAcceptat &gt; 0 '||vCond_Subunit_C||vCondIntrari||' '||chr(13)||
    ' ) GROUP BY CodObiect';
  EXECUTE sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,resta,tip, userid) '||
    'select codobiect, sum(resta) resta, ''CFN'', '||vUserId::varchar||' from ('||chr(13)||
    'SELECT C1.CodObiect, C1.RestAcceptat RestA, ''CFN'', '||vUserId::varchar||' '||
    '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 C1.RestAcceptat &gt; 0 '||vCond_Subunit_C||' '||
    '     AND C1.TERMEN BETWEEN PKG_LIST_SELECTSCAD.DATASCAD + 1 AND PKG_LIST_SELECTSCAD.DATASCAD + 7 '||
    ') GROUP BY CodObiect';
  EXECUTE sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'select codobiect, sum(cantc) cantc, sum(canta) canta, sum(resta) resta, ''CFT'', '||vUserId::varchar||' from ('||chr(13)||
    'SELECT C1.CodObiect, C1.CantComandat CantC, C1.CantAcceptat CantA, C1.RestAcceptat RestA, ''CFT'','||vUserId::varchar||' '||
    '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 C1.RestAcceptat &gt; 0 '||vCond_Subunit_C||' '||
    ') GROUP BY CodObiect';
  EXECUTE sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'select codobiect, sum(cantc) cantc, sum(canta) canta, sum(resta) resta, ''CFPER'', '||vUserId::varchar||' from ('||chr(13)||
    'SELECT C1.CodObiect, C1.CantComandat CantC, C1.CantAcceptat CantA, C1.RestAcceptat RestA, ''CFPER'','||vUserId::varchar||' '||
    '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 C1.RestAcceptat &gt; 0 '||vCond_Subunit_C||vCondIesiri||' '||
    ') GROUP BY CodObiect';
  EXECUTE sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT coalesce(NE.CODOBIECT,PN.CodObiect), SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantComandat else PN.Cant/PN0.Cant*C1.CantComandat end) CantC, SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantAcceptat else PN.Cant/PN0.Cant*C1.CantAcceptat end) CantA, SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.RestLansat else PN.Cant/PN0.Cant*C1.RestLansat end) RestA,
            ''CC'','||vUserId::varchar||' '||
      'FROM COMANDA C '||
        'INNER JOIN COMANDA1   C1  ON C.CodComanda   = C1.CodComanda '||
        'INNER JOIN PROIECTNOD PN  ON C1.CODPROIECT  = PN.CODPROIECT  AND PN.TIP = 3 '||
        'INNER JOIN PROIECTNOD PN0 ON C1.CODPROIECT  = PN0.CODPROIECT AND coalesce(PN0.NODORIGINAL, 0) = 0 '||
        'LEFT  JOIN NODECHIV   NE  ON C1.CODCOMANDA1 = NE.CODCOMANDA1 AND PN.CODPROIECTNOD = NE.CODPROIECTNOD '||
      'WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND coalesce(C.DispLivrare, 0) = 0 AND C.TipDoc = 18 '||
        'AND C1.RestLansat &gt; 0 and coalesce(c1.exceptional,0) = 0 '||vCond_Subunit_C||vCondIesiri||' '||
      'GROUP BY coalesce(NE.CODOBIECT,PN.CodObiect)';
  EXECUTE sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT coalesce(NE.CODOBIECT,PN.CodObiect), SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantComandat else PN.Cant/PN0.Cant*C1.CantComandat end) CantC, SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantAcceptat else PN.Cant/PN0.Cant*C1.CantAcceptat end) CantA, SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.RestLansat else PN.Cant/PN0.Cant*C1.RestLansat end) RestA,
            ''CIIES'','||vUserId::varchar||' '||
      'FROM COMANDA C '||
        'INNER JOIN COMANDA1   C1  ON C.CodComanda   = C1.CodComanda '||
        'INNER JOIN PROIECTNOD PN  ON C1.CODPROIECT  = PN.CODPROIECT  AND PN.TIP = 3 '||
        'INNER JOIN PROIECTNOD PN0 ON C1.CODPROIECT  = PN0.CODPROIECT AND coalesce(PN0.NODORIGINAL, 0) = 0 '||
        'LEFT  JOIN NODECHIV   NE  ON C1.CODCOMANDA1 = NE.CODCOMANDA1 AND PN.CODPROIECTNOD = NE.CODPROIECTNOD '||
      'WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND C.DispLivrare = 2 AND C.TipDoc = 18 '||
        'AND C1.RestLansat &gt; 0 and coalesce(c1.exceptional,0) = 0 '||vCond_Subunit_C||vCondIesiri||' '||
      'GROUP BY coalesce(NE.CODOBIECT,PN.CodObiect)';
  EXECUTE sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT coalesce(NE.CODOBIECT,PN.CodObiect), SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantComandat else PN.Cant/PN0.Cant*C1.CantComandat end) CantC, SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantAcceptat else PN.Cant/PN0.Cant*C1.CantAcceptat end) CantA, SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.RestLansat else PN.Cant/PN0.Cant*C1.RestLansat end) RestA,
            ''CCPANALA'','||vUserId::varchar||' '||
      'FROM COMANDA C '||
        'INNER JOIN COMANDA1   C1  ON C.CodComanda   = C1.CodComanda '||
        'INNER JOIN PROIECTNOD PN  ON C1.CODPROIECT  = PN.CODPROIECT  AND PN.TIP = 3 '||
        'INNER JOIN PROIECTNOD PN0 ON C1.CODPROIECT  = PN0.CODPROIECT AND coalesce(PN0.NODORIGINAL, 0) = 0 '||
        'LEFT  JOIN NODECHIV   NE  ON C1.CODCOMANDA1 = NE.CODCOMANDA1 AND PN.CODPROIECTNOD = NE.CODPROIECTNOD '||
      'WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0  AND coalesce(C.DispLivrare, 0) = 0 AND C.TipDoc = 18 '||
        'AND C1.RestLansat &gt; 0 and coalesce(c1.exceptional,0) = 0 '||vCond_Subunit_C||vCondIntrari||' '||
      'GROUP BY coalesce(NE.CODOBIECT,PN.CodObiect)';
  EXECUTE sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT coalesce(NE.CODOBIECT,PN.CodObiect), SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantComandat else PN.Cant/PN0.Cant*C1.CantComandat end) CantC, SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantAcceptat else PN.Cant/PN0.Cant*C1.CantAcceptat end) CantA, SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.RestLansat else PN.Cant/PN0.Cant*C1.RestLansat end) RestA,
            ''CIIESPANALA'','||vUserId::varchar||' '||
      'FROM COMANDA C '||
        'INNER JOIN COMANDA1   C1  ON C.CodComanda   = C1.CodComanda '||
        'INNER JOIN PROIECTNOD PN  ON C1.CODPROIECT  = PN.CODPROIECT  AND PN.TIP = 3 '||
        'INNER JOIN PROIECTNOD PN0 ON C1.CODPROIECT  = PN0.CODPROIECT AND coalesce(PN0.NODORIGINAL, 0) = 0 '||
        'LEFT  JOIN NODECHIV   NE  ON C1.CODCOMANDA1 = NE.CODCOMANDA1 AND PN.CODPROIECTNOD = NE.CODPROIECTNOD '||
      'WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND C.DispLivrare = 2 AND C.TipDoc = 18 '||
        'AND C1.RestLansat &gt; 0 and coalesce(c1.exceptional,0) = 0 '||vCond_Subunit_C||vCondIntrari||' '||
      'GROUP BY coalesce(NE.CODOBIECT,PN.CodObiect)';
  EXECUTE sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT coalesce(NE.CODOBIECT,PN.CodObiect),
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantComandat else PN.Cant/PN0.Cant*C1.CantComandat end) CantC,
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantAcceptat else PN.Cant/PN0.Cant*C1.CantAcceptat end) CantA,
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.RestLansat else PN.Cant/PN0.Cant*C1.RestLansat end) RestA,
            ''CCPER'','||vUserId::varchar||' '||
      'FROM COMANDA C '||
        'INNER JOIN COMANDA1   C1  ON C.CodComanda   = C1.CodComanda '                                         ||
        'INNER JOIN PROIECTNOD PN  ON C1.CODPROIECT  = PN.CODPROIECT  AND PN.TIP = 3 '                         ||
        'INNER JOIN PROIECTNOD PN0 ON C1.CODPROIECT  = PN0.CODPROIECT AND coalesce(PN0.NODORIGINAL, 0) = 0 '   ||
        'LEFT  JOIN NODECHIV   NE  ON C1.CODCOMANDA1 = NE.CODCOMANDA1 AND PN.CODPROIECTNOD = NE.CODPROIECTNOD '||
      'WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND coalesce(C.DispLivrare, 0) = 0 AND C.TipDoc = 18 '||
        'AND C1.RestLansat &gt; 0 and coalesce(c1.exceptional,0) = 0 '||vCond_Subunit_C||vCondIesiri||' '         ||
      'GROUP BY coalesce(NE.CODOBIECT,PN.CodObiect)';
  EXECUTE sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT coalesce(NE.CODOBIECT,PN.CodObiect),
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantComandat else PN.Cant/PN0.Cant*C1.CantComandat end) CantC,
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantAcceptat else PN.Cant/PN0.Cant*C1.CantAcceptat end) CantA,
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.RestLansat else PN.Cant/PN0.Cant*C1.RestLansat end) RestA,
            ''CIPER'','||vUserId::varchar||' '||
      'FROM COMANDA C '||
        'INNER JOIN COMANDA1   C1  ON C.CodComanda   = C1.CodComanda '                                             ||
        'INNER JOIN PROIECTNOD PN  ON C1.CODPROIECT  = PN.CODPROIECT  AND PN.TIP = 3 '                             ||
        'INNER JOIN PROIECTNOD PN0 ON C1.CODPROIECT  = PN0.CODPROIECT AND coalesce(PN0.NODORIGINAL, 0) = 0 '       ||
        'LEFT  JOIN NODECHIV   NE  ON C1.CODCOMANDA1 = NE.CODCOMANDA1 AND PN.CODPROIECTNOD = NE.CODPROIECTNOD '    ||
      'WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND C.DispLivrare = 2 AND C.TipDoc = 18 '||
        'AND C1.RestLansat &gt; 0 and coalesce(c1.exceptional,0) = 0 '||vCond_Subunit_C||vCondIesiri||' '             ||
      'GROUP BY coalesce(NE.CODOBIECT,PN.CodObiect)';
  EXECUTE sSelect;

  /*informatii aduse din planificari*/
  if vSetimana = 1 then
    vPrevAn := vAn - 1;
    vPrevSetimana := 53;
  else
    vPrevAn := vAn;
    vPrevSetimana := vSetimana - 1;
  end if;
  if vPrevSetimana = 1 then
    vPPrevAn := vPrevAn - 1;
    vPPrevSetimana := 53;
  else
    vPPrevAn := vPrevAn;
    vPPrevSetimana := vPrevSetimana - 1;
  end if;
  if vSetimana = 53 then
    vNextAn := vAn + 1;
    vNextSetimana := 1;
  else
    vNextAn := vAn;
    vNextSetimana := vSetimana + 1;
  end if;

  select count(*) into vCount
  from planifprod
  where ((saptamana = vSetimana      and an = vAn      and (subunitatea = GETSUBUNITATE() or GETSUBUNITATE() = 1)) or
         (saptamana = vPrevSetimana  and an = vPrevAn  and (subunitatea = GETSUBUNITATE() or GETSUBUNITATE() = 1)) or
         (saptamana = vPPrevSetimana and an = vPPrevAn and (subunitatea = GETSUBUNITATE() or GETSUBUNITATE() = 1)) or
         (saptamana = vNextSetimana  and an = vNextAn  and (subunitatea = GETSUBUNITATE() or GETSUBUNITATE() = 1))
        )
        and anulat = 0;

  if vCount &gt; 0 then
    DELETE FROM TMP_PLANIFNODZ;
    INSERT INTO TMP_PLANIFNODZ (CODRETETA, CODOBIECT, NECESAR)
    SELECT CODRETETA, CODOBIECT, SUM(NECESAR)
    FROM (
          SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
          FROM PLANIFNOD PNOD
               INNER JOIN PLANIFPROD1 PP1 ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
               INNER JOIN PLANIFPROD  PP  ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
          WHERE PP.An = vAn and PP.Saptamana = vSetimana 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 (PP.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
          UNION ALL
          SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
          FROM PLANIFNOD PNOD
               INNER JOIN PLANIFPROD1 PP1 ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
               INNER JOIN PLANIFPROD  PP  ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
          WHERE PP.An = vAn and PP.Saptamana = vSetimana 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 (PP.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
          UNION ALL
          SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
          FROM PLANIFNOD PNOD
               INNER JOIN PLANIFPROD1 PP1 ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
               INNER JOIN PLANIFPROD  PP  ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
          WHERE PP.An = vAn and PP.Saptamana = vSetimana 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 (PP.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
          UNION ALL
          select codreteta, codobiect, NEXTWEEK necesar
          from
              (SELECT L1.CODRETETA, L1.CODOBIECT, sum(coalesce(l1.nextweek,0)) nextweek
               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 = vPrevAn and l.saptamana = vPrevSetimana
                     and l1.nextweek &gt; 0
                     AND (L.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
               group by l1.codreteta, l1.codobiect
               ) A_PG
         ) B_PG
     group by codobiect, codreteta;

     sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '                            ||CHR(13)||
      'SELECT MAT.CodObiect, SUM((TMP.NECESAR - coalesce(REPORT.NEXTWEEK,0))/PC.CANT*MAT.CANT) CantC, SUM(coalesce(REPORT.NEXTWEEK,0)/PC.CANT*MAT.CANT) CantA, SUM((TMP.NECESAR - coalesce(REPORT.NEXTWEEK,0))/PC.CANT*MAT.CANT) - coalesce(LANS.STINS,0) RestA, ''PLANIFPER'','||vUserId||' '||CHR(13)||
      'FROM TMP_PLANIFNODZ TMP '                                                                          ||CHR(13)||
      '     INNER JOIN PRODCOMP PC ON TMP.CODRETETA = PC.CODPRODCOMP '                                    ||CHR(13)||
      '     INNER JOIN PRODMAT MAT ON PC.CODPRODCOMP = MAT.CODPRODCOMP '                                  ||CHR(13)||
      '     LEFT JOIN ( '                                                                                 ||CHR(13)||
      '                SELECT L1.CODRETETA, L1.CODOBIECT, SUM(coalesce(L1.NEXTWEEK,0)) NEXTWEEK '         ||CHR(13)||
      '                from LANSZ1 L1 '                                                                   ||CHR(13)||
      '                     inner join LANSZ l on l.codlansz = l1.codlansz '                              ||CHR(13)||
      '                where l.operat = 1 and l.anulat = 0 and l.blocat = 0 '                             ||CHR(13)||
      '                      and l.an = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||CHR(13)||
      '                      and l1.nextweek &gt; 0 '                                                        ||CHR(13)||
      '                      AND (L.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1) '               ||CHR(13)||
      '               group by l1.codreteta, l1.codobiect '                                               ||CHR(13)||
      '               ) REPORT ON REPORT.CODRETETA = TMP.CODRETETA'                                       ||CHR(13)||
      '     LEFT JOIN (SELECT CODOBIECT, SUM(STINS) STINS FROM ( '                                        ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                         ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                              ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '           ||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_LUNI '             ||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '                  ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                           ||CHR(13)||
      '                union all '                                                                        ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                         ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                              ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '           ||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_MARTI '            ||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '                  ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                           ||CHR(13)||
      '                union all '                                                                        ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                         ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                              ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '           ||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_MIERCURI '         ||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '                  ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                           ||CHR(13)||
      '                union all '                                                                        ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                         ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                              ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '           ||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_JOI '              ||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '                  ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                           ||CHR(13)||
      '                union all '                                                                        ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                         ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                              ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '           ||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_VINERI '           ||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '                  ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                           ||CHR(13)||
      '                union all '                                                                        ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                         ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                              ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '           ||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_SAMBATA '          ||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '                  ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                           ||CHR(13)||
      '                union all '                                                                        ||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                         ||CHR(13)||
      '                FROM IESPRODLINK IL '                                                              ||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '           ||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_DUMINICA '         ||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '                  ||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '                                                           ||CHR(13)||
      '                ) GROUP BY CODOBIECT) LANS ON LANS.CODOBIECT = MAT.CODOBIECT  '                    ||CHR(13)||
      'GROUP BY MAT.CodObiect,coalesce(LANS.STINS,0)';
      EXECUTE sSelect;

      DELETE FROM TMP_PLANIFNODZ;
      INSERT INTO TMP_PLANIFNODZ (CODRETETA, CODOBIECT, NECESAR)
      SELECT CODRETETA, CODOBIECT, SUM(NECESAR)
      FROM (
            SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
            FROM PLANIFNOD PNOD
                 INNER JOIN PLANIFPROD1 PP1 ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                 INNER JOIN PLANIFPROD  PP  ON PP.CODPLANIFPROD  = PP1.CODPLANIFPROD
            WHERE PP.An = vPrevAn and PP.Saptamana = vPrevSetimana 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 (PP.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
            UNION ALL
            SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
            FROM PLANIFNOD PNOD
                 INNER JOIN PLANIFPROD1 PP1 ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                 INNER JOIN PLANIFPROD  PP  ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
            WHERE PP.An = vPrevAn and PP.Saptamana = vPrevSetimana 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 (PP.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
            UNION ALL
            SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
            FROM PLANIFNOD PNOD
                 INNER JOIN PLANIFPROD1 PP1 ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                 INNER JOIN PLANIFPROD  PP  ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
            WHERE PP.An = vPrevAn and PP.Saptamana = vPrevSetimana 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 (PP.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
            UNION ALL
            (
            select codreteta, codobiect, nextweek necesar
            from
                (SELECT distinct L1.CODRETETA, L1.CODOBIECT, sum(coalesce(l1.nextweek,0)) nextweek
                 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 = vPPrevAn and l.saptamana = vPPrevSetimana
                       and l1.nextweek &gt; 0
                       AND (L.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
                 group by l1.codreteta, l1.codobiect
                 ) A_PG
             )
           ) C_PG
     group by codobiect, codreteta;

     sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||CHR(13)||
      'SELECT MAT.CodObiect, SUM((TMP.NECESAR - coalesce(REPORT.NEXTWEEK,0))/PC.CANT*MAT.CANT) CantC, SUM(coalesce(REPORT.NEXTWEEK,0)/PC.CANT*MAT.CANT) CantA, SUM((TMP.NECESAR - coalesce(REPORT.NEXTWEEK,0))/PC.CANT*MAT.CANT) - coalesce(LANS.STINS,0) RestA, ''PLANIFPREV'','||vUserId||' '||CHR(13)||
      'FROM TMP_PLANIFNODZ TMP '||CHR(13)||
      '     INNER JOIN PRODCOMP PC ON TMP.CODRETETA = PC.CODPRODCOMP '||CHR(13)||
      '     INNER JOIN PRODMAT MAT ON PC.CODPRODCOMP = MAT.CODPRODCOMP '||CHR(13)||
      '     LEFT JOIN ( '||CHR(13)||
      '                SELECT L1.CODRETETA, L1.CODOBIECT, SUM(coalesce(L1.NEXTWEEK,0)) NEXTWEEK '||CHR(13)||
      '                from LANSZ1 L1 '||CHR(13)||
      '                     inner join LANSZ l on l.codlansz = l1.codlansz '||CHR(13)||
      '                where l.operat = 1 and l.anulat = 0 and l.blocat = 0 '||CHR(13)||
      '                      and l.an = '||vPPrevAn::varchar||' and l.saptamana = '||vPPrevSetimana::varchar||CHR(13)||
      '                      and l1.nextweek &gt; 0 '||CHR(13)||
      '                      AND (L.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1) '||CHR(13)||
      '                group by l1.codreteta, l1.codobiect '||CHR(13)||
      '               ) REPORT ON REPORT.CODRETETA = TMP.CODRETETA'||CHR(13)||
      '     LEFT JOIN (SELECT CODOBIECT, SUM(STINS) STINS FROM ( '||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
      '                FROM IESPRODLINK IL '||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_LUNI '||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '||CHR(13)||
      '                union all '||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
      '                FROM IESPRODLINK IL '||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_MARTI '||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '||CHR(13)||
      '                union all '||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
      '                FROM IESPRODLINK IL '||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_MIERCURI '||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '||CHR(13)||
      '                union all '||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
      '                FROM IESPRODLINK IL '||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_JOI '||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '||CHR(13)||
      '                union all '||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
      '                FROM IESPRODLINK IL '||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_VINERI '||CHR(13)||
      '                     INNER JOIN LANSZ       L  ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '||CHR(13)||
      '                union all '||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
      '                FROM IESPRODLINK IL '||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_SAMBATA '||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '||CHR(13)||
      '                union all '||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
      '                FROM IESPRODLINK IL '||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_DUMINICA '||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '||CHR(13)||
      '                ) GROUP BY CODOBIECT) LANS ON LANS.CODOBIECT = MAT.CODOBIECT  '||CHR(13)||
      'GROUP BY MAT.CodObiect,coalesce(LANS.STINS,0)';
      EXECUTE sSelect;

      DELETE FROM TMP_PLANIFNODZ;
      INSERT INTO TMP_PLANIFNODZ (CODRETETA, CODOBIECT, NECESAR)
      SELECT CODRETETA, CODOBIECT, SUM(NECESAR)
      FROM (
            SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
            FROM PLANIFNOD PNOD
                 INNER JOIN PLANIFPROD1 PP1 ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                 INNER JOIN PLANIFPROD  PP  ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
            WHERE PP.An = vNextAn and PP.Saptamana = vNextSetimana 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 (PP.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
            UNION ALL
            SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
            FROM PLANIFNOD PNOD
                 INNER JOIN PLANIFPROD1 PP1 ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                 INNER JOIN PLANIFPROD  PP  ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
            WHERE PP.An = vNextAn and PP.Saptamana = vNextSetimana 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 (PP.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
            UNION ALL
            SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
            FROM PLANIFNOD PNOD
                 INNER JOIN PLANIFPROD1 PP1 ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                 INNER JOIN PLANIFPROD  PP  ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
            WHERE PP.An = vNextAn and PP.Saptamana = vNextSetimana 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 (PP.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
            UNION ALL
            (
            select codreteta, codobiect, 0 necesar
            from
                (SELECT distinct L1.CODRETETA, L1.CODOBIECT, sum(coalesce(l1.nextweek,0)) nextweek
                 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 = vAn and l.saptamana = vSetimana
                       and l1.nextweek &gt; 0
                       AND (L.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1)
                 group by l1.codreteta, l1.codobiect
                 ) A_PG
             )
           ) B_PG
     group by codobiect, codreteta;

     sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||CHR(13)||
      'SELECT MAT.CodObiect, SUM((TMP.NECESAR - coalesce(REPORT.NEXTWEEK,0))/PC.CANT*MAT.CANT) CantC, SUM(coalesce(REPORT.NEXTWEEK,0)/PC.CANT*MAT.CANT) CantA, SUM((TMP.NECESAR - coalesce(REPORT.NEXTWEEK,0))/PC.CANT*MAT.CANT) - coalesce(LANS.STINS,0) RestA, ''PLANIFNEXT'','||vUserId||' '||CHR(13)||
      'FROM TMP_PLANIFNODZ TMP '||CHR(13)||
      '     INNER JOIN PRODCOMP PC ON TMP.CODRETETA  = PC.CODPRODCOMP '||CHR(13)||
      '     INNER JOIN PRODMAT MAT ON PC.CODPRODCOMP = MAT.CODPRODCOMP '||CHR(13)||
      '     LEFT JOIN ( '||CHR(13)||
      '                SELECT L1.CODRETETA, L1.CODOBIECT, SUM(coalesce(L1.NEXTWEEK,0)) NEXTWEEK '||CHR(13)||
      '                from LANSZ1 L1 '||CHR(13)||
      '                     inner join LANSZ l on l.codlansz = l1.codlansz '||CHR(13)||
      '                where l.operat = 1 and l.anulat = 0 and l.blocat = 0 '||CHR(13)||
      '                      and l.an = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||CHR(13)||
      '                      and l1.nextweek &gt; 0 '||CHR(13)||
      '                      AND (L.SUBUNITATEA = GETSUBUNITATE() OR GETSUBUNITATE() = 1) '||CHR(13)||
      '                group by l1.codreteta, l1.codobiect '||CHR(13)||
      '               ) REPORT ON REPORT.CODRETETA = TMP.CODRETETA'||CHR(13)||
      '     LEFT JOIN (SELECT CODOBIECT, SUM(STINS) STINS FROM ( '||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
      '                FROM IESPRODLINK IL '||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_LUNI '||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '||CHR(13)||
      '                union all '||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
      '                FROM IESPRODLINK IL '||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_MARTI '||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '||CHR(13)||
      '                union all '||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
      '                FROM IESPRODLINK IL '||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_MIERCURI '||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '||CHR(13)||
      '                union all '||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
      '                FROM IESPRODLINK IL '||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_JOI '||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '||CHR(13)||
      '                union all '||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
      '                FROM IESPRODLINK IL '||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_VINERI '||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '||CHR(13)||
      '                union all '||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
      '                FROM IESPRODLINK IL '||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_SAMBATA '||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '||CHR(13)||
      '                union all '||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
      '                FROM IESPRODLINK IL '||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_DUMINICA '||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                group by cmd.codobiect '||CHR(13)||
      '                ) GROUP BY CODOBIECT) LANS ON LANS.CODOBIECT = MAT.CODOBIECT  '||CHR(13)||
      'GROUP BY MAT.CodObiect,coalesce(LANS.STINS,0)';
      EXECUTE sSelect;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz4_umpletemporargenerator</obj_name>
  <obj_hashval>4568bf737cd9929028a565b4d7a484bc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz4_umpletemporargenerator(vcodnecesar numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSelect          VARCHAR := '';
  vToateGest       BOOLEAN;
  vToateIOArt      BOOLEAN;
  vAux             VARCHAR := '';
  vSelStocReal     VARCHAR := '';
  vCateGest        NUMERIC := 0;
  vCateLGest       NUMERIC := 0;
  vProductie       BOOLEAN;
  vCondIntrari     VARCHAR := '';
  vCondIesiri      VARCHAR := '';
  vNrZileStocMed   NUMERIC;

  vGestString     varchar := '';
  vIOArtString     varchar := '';
  vCond_Subunit_C varchar := '';
  vCond_Subunit_G varchar := '';
  vSetimana       NUMERIC := '';
  vUserID         NUMERIC := '';
  vAn             NUMERIC := '';
  vPrevAn         NUMERIC := '';
  vPrevSetimana   NUMERIC := '';
  vPPrevAn         NUMERIC := '';
  vPPrevSetimana   NUMERIC := '';
  vCount           NUMERIC := '';
  vSupliment       NUMERIC := '';
BEGIN
  --Florin 28.10.2022 - sinc. Oracle
  --Adina 01 septembrie 2020 - netestat pt.ca nu stiu unde se apeleaza
  vUserId        := COALESCE(current_setting('PKG_GLOBALS.USERID'      , true)::numeric, 0);
  vToateGest     := (current_setting('PKG_LIST_SELECTSCAD.vToateGest'  , true)::NUMERIC = 1)::boolean;
  vToateIOArt    := (current_setting('PKG_LIST_SELECTSCAD.vToateIoart' , true)::NUMERIC = 1)::boolean;
  vProductie     := (current_setting('PKG_LIST_SELECTSCAD.vCentralizat', true)::numeric = 1)::boolean;
  vSetimana      := current_setting('PKG_LIST_SELECTSCAD.vSetimana'    , true)::numeric;
  vAn            := getANLUCRU();

  begin
    select coalesce(Supliment,0) into vSupliment from necesar where codnecesar = vCodNecesar;
  exception when others then
    vSupliment := 0;
  end;

  vCondIntrari := ' AND C1.TERMEN &lt; to_date(current_setting(''PKG_LIST_SELECTSCAD.vDataIni'', true), ''DD.MM.YYYY'') ';
  if to_date( current_setting('PKG_LIST_SELECTSCAD.vDataIni', true), 'DD.MM.YYYY') = to_date(current_setting('PKG_LIST_SELECTSCAD.vDataScad', true), 'DD.MM.YYYY') then
    vCondIesiri  := ' AND C1.TERMEN BETWEEN to_date(current_setting(''PKG_LIST_SELECTSCAD.vDataIni'', true), ''DD.MM.YYYY'') AND to_date(current_setting(''PKG_LIST_SELECTSCAD.vDataScad'', true), ''DD.MM.YYYY'') - 1 ';
  else
    vCondIesiri  := ' AND C1.TERMEN BETWEEN to_date(current_setting(''PKG_LIST_SELECTSCAD.vDataIni'', true), ''DD.MM.YYYY'') AND to_date(current_setting(''PKG_LIST_SELECTSCAD.vDataScad'', true), ''DD.MM.YYYY'') ';
  end if;

  vNrZileStocMed := COALESCE(fnc_GetValConstanta('NrZileStocMed', getANLUCRU(), getLUNALUCRU()),'') ;
  vSelStocReal := '
      SELECT NS.CODOBIECT, SUM(case when n.operat = 0 then ns.cantnir else ns.rest end) CANT
      FROM NIRSTOC NS
        INNER JOIN NARTOBJ OBJ ON OBJ.CODOBIECT = NS.CODOBIECT
        INNER JOIN NIR N ON NS.CODNIR = N.CODNIR
        INNER JOIN NGEST G ON G.CodGest = N.GEST '||vCond_Subunit_G||'
        INNER JOIN (SELECT A.CODARTICOL, COUNT(O.CODOBIECT) NR
                    FROM NART A
                         INNER JOIN NARTOBJ O ON O.CODARTICOL = A.CODARTICOL
                    GROUP BY A.CODARTICOL) NROBJ ON OBJ.CODARTICOL = NROBJ.CODARTICOL
      WHERE (NROBJ.NR = 1 OR (NROBJ.NR &gt; 1 AND EXISTS (SELECT ATR.CODOBIECT FROM NATROBJ ATR WHERE ATR.CODOBIECT = OBJ.CODOBIECT)))
      and ((ns.rest &lt;&gt; 0 and n.operat = 1) or (ns.rest = 0 and n.operat = 0 and n.tipnir = 12)) and g.tip &lt;&gt; 4 ';
  vAux := '
      AND ';
  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
      vSelStocReal := vSelStocReal || vAux||' EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = N.GEST::varchar) ';
    elsif vCateGest = 0 then
      vSelStocReal := vSelStocReal || vAux||' EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND VALOARE = NS.CODLOCATIE::varchar) ';
    else
      vSelStocReal := vSelStocReal || vAux||' (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;
    vAux := '
        AND';
    vGestString := ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = N.GEST::varchar) ';
  end if;

  if NOT vToateIOArt then
    vSelStocReal := vSelStocReal || vAux||' EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND VALOARE = NS.CODIOART::varchar ) ';
    vIOArtString := ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND VALOARE = NS.CODIOART::varchar ) ';
  end if;
  vSelStocReal := vSelStocReal ||'
      GROUP BY NS.CODOBIECT';

  vSelStocReal := vSelStocReal||'
      UNION ALL
      SELECT OBJ.CODOBIECT, SUM(case when n.operat = 0 then ns.cantnir else ns.rest end) CANT
      FROM NARTOBJ OBJ
        INNER JOIN NARTOBJ O  ON OBJ.CODARTICOL = O.CODARTICOL
        INNER JOIN NIRSTOC NS ON O.CODOBIECT    = NS.CODOBIECT
        INNER JOIN NIR     N  ON NS.CODNIR      = N.CODNIR
        INNER JOIN NGEST   G  ON G.CodGest      = N.GEST '||vCond_Subunit_G||'
        INNER JOIN (SELECT A.CODARTICOL, COUNT(O.CODOBIECT) NR
                    FROM NART A
                         INNER JOIN NARTOBJ O ON O.CODARTICOL = A.CODARTICOL
                    GROUP BY A.CODARTICOL) NROBJ ON OBJ.CODARTICOL = NROBJ.CODARTICOL
        WHERE (NROBJ.NR &gt; 1 AND NOT EXISTS (SELECT ATR.CODOBIECT FROM NATROBJ ATR WHERE ATR.CODOBIECT = OBJ.CODOBIECT))
        and ((ns.rest &lt;&gt; 0 and n.operat = 1) or (ns.rest = 0 and n.operat = 0 and n.tipnir = 12)) and g.tip &lt;&gt; 4 ';
  vAux := '
      AND ';
  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
      vSelStocReal := vSelStocReal || vAux||' EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = N.GEST::varchar) ';
    elsif vCateGest = 0 then
      vSelStocReal := vSelStocReal || vAux||' EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'' AND VALOARE = NS.CODLOCATIE::varchar) ';
    else
      vSelStocReal := vSelStocReal || vAux||' (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;
    vAux := '
        AND';
    vGestString := ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'' AND VALOARE = N.GEST::varchar) ';
  end if;

  if NOT vToateIOArt then
    vSelStocReal := vSelStocReal || vAux||' EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND VALOARE = NS.CODIOART::varchar ) ';
    vIOArtString := ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND VALOARE = NS.CODIOART::varchar ) ';
  end if;
  vSelStocReal := vSelStocReal ||'
      GROUP BY OBJ.CODOBIECT';

  DELETE FROM TMP_STOCREAL;
  sSelect := 'insert into tmp_stocreal(codobiect,cant) '||vSelStocReal;
  EXECUTE sSelect;

  DELETE FROM TMP_STOCREZ;
  sSelect := 'insert into tmp_stocrez(codobiect,rezervat) '||'SELECT NS.CODOBIECT, SUM(R.REST) REZERVAT '||
      'FROM REZERVATS R '||
        'INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = R.CODNIRSTOC '||
        'INNER JOIN NIR     N  ON NS.CODNIR     = N.CODNIR '||
        'INNER JOIN NGEST   G  ON N.GEST        = G.CodGest '||vCond_Subunit_G||' '||
      'WHERE coalesce(R.REST,0) &gt; 0 '||
      vGestString||
      vIOArtString||
      'GROUP BY NS.CODOBIECT';
  EXECUTE sSelect;

  DELETE FROM TMP_CMD WHERE USERID = vUserId;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '                                                                             ||chr(13)||
    'select codobiect, sum(cantc) cantc, sum(canta) canta, sum(resta) resta, ''CF'', '||vUserId::varchar||' from ('                                     ||chr(13)||
    '  SELECT C1.CodObiect, C1.CantComandat CantC, C1.CantAcceptat CantA, C1.RestAcceptat RestA '                                                       ||chr(13)||
    '  FROM COMANDA1 C1'                                                                                                                                ||chr(13)||
    '       INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda'                                                                                       ||chr(13)||
    '  WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 8 AND C1.RestAcceptat &gt; 0 '||vCond_Subunit_C||vCondIntrari||' '||chr(13)||
    ' ) GROUP BY CodObiect';
  EXECUTE sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '                                                          ||chr(13)||
    'select codobiect, sum(cantc) cantc, sum(canta) canta, sum(resta) resta, ''CFNEXT'', '||vUserId::varchar||' from ('              ||chr(13)||
    '  SELECT C1.CodObiect, C1.CantComandat CantC, C1.CantAcceptat CantA, C1.RestAcceptat RestA '                                    ||chr(13)||
    '  FROM COMANDA1 C1 '                                                                                                            ||chr(13)||
    '       INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda '                                                                   ||chr(13)||
    '  WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 8 AND C1.RestAcceptat &gt; 0 '||vCond_Subunit_C||chr(13)||
    '        AND C1.TERMEN BETWEEN PKG_LIST_SELECTSCAD.DATASCAD AND PKG_LIST_SELECTSCAD.DATASCAD + 6 '                               ||chr(13)||
    ') GROUP BY CodObiect';
  EXECUTE sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,resta,tip, userid) '||
    'SELECT C1.CodObiect, SUM(C1.CantAcceptat - coalesce(Storno.Cant,0)) RestA, ''CFN'', '||vUserId::varchar||' '||
    'FROM COMANDA1 C1 '||
    '     INNER JOIN COMANDA    C  ON C1.CodComanda = C.CodComanda '||
    '     INNER JOIN NECESARCMD NC ON NC.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 coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 8 '||
    '      AND NC.CODNECESAR = '||vCodNecesar||' '||
    'GROUP BY C1.CodObiect';
  EXECUTE sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '                                                                            ||chr(13)||
    'select codobiect, sum(cantc) cantc, sum(canta) canta, sum(resta) resta, ''CFPER'', '||vUserId::varchar||' from ('                                 ||chr(13)||
    '  SELECT C1.CodObiect, C1.CantComandat CantC, C1.CantAcceptat CantA, C1.RestAcceptat RestA '                                                      ||chr(13)||
    '  FROM COMANDA1 C1 '                                                                                                                              ||chr(13)||
    '       INNER JOIN COMANDA C ON C1.CodComanda = C.CodComanda '                                                                                     ||chr(13)||
    '  WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND C.TipDoc = 8 AND C1.RestAcceptat &gt; 0 '||vCond_Subunit_C||vCondIesiri||' '||chr(13)||
    ') GROUP BY CodObiect';
  EXECUTE sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT coalesce(NE.CODOBIECT,PN.CodObiect),
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantComandat else PN.Cant/PN0.Cant*C1.CantComandat end) CantC,
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantAcceptat else PN.Cant/PN0.Cant*C1.CantAcceptat end) CantA,
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.RestLansat   else PN.Cant/PN0.Cant*C1.RestLansat   end) RestA,
            ''CC'','||vUserId::varchar||' '||
      'FROM COMANDA C '||
        'INNER JOIN COMANDA1   C1  ON C.CodComanda   = C1.CodComanda '||
        'INNER JOIN PROIECTNOD PN  ON C1.CODPROIECT  = PN.CODPROIECT AND PN.TIP = 3 '||
        'INNER JOIN PROIECTNOD PN0 ON C1.CODPROIECT  = PN0.CODPROIECT AND coalesce(PN0.NODORIGINAL, 0) = 0 '||
        'LEFT  JOIN NODECHIV   NE  ON C1.CODCOMANDA1 = NE.CODCOMANDA1 AND PN.CODPROIECTNOD = NE.CODPROIECTNOD '||
      'WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND coalesce(C.DispLivrare, 0) = 0 AND C.TipDoc = 18 '||
        'AND C1.RestLansat &gt; 0 and coalesce(c1.exceptional,0) = 0 '||vCond_Subunit_C||vCondIesiri||' '||
      'GROUP BY coalesce(NE.CODOBIECT,PN.CodObiect)';
  EXECUTE sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT coalesce(NE.CODOBIECT,PN.CodObiect),
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantComandat else PN.Cant/PN0.Cant*C1.CantComandat end) CantC,
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantAcceptat else PN.Cant/PN0.Cant*C1.CantAcceptat end) CantA,
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.RestLansat   else PN.Cant/PN0.Cant*C1.RestLansat   end) RestA,
            ''CIIES'','||vUserId::varchar||' '||
      'FROM COMANDA C '||
        'INNER JOIN COMANDA1   C1  ON C.CodComanda   = C1.CodComanda '||
        'INNER JOIN PROIECTNOD PN  ON C1.CODPROIECT  = PN.CODPROIECT  AND PN.TIP = 3 '||
        'INNER JOIN PROIECTNOD PN0 ON C1.CODPROIECT  = PN0.CODPROIECT AND coalesce(PN0.NODORIGINAL, 0) = 0 '||
        'LEFT  JOIN NODECHIV   NE  ON C1.CODCOMANDA1 = NE.CODCOMANDA1 AND PN.CODPROIECTNOD = NE.CODPROIECTNOD '||
      'WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND C.DispLivrare = 2 AND C.TipDoc = 18 '||
        'AND C1.RestLansat &gt; 0 and coalesce(c1.exceptional,0) = 0 '||vCond_Subunit_C||vCondIesiri||' '||
      'GROUP BY coalesce(NE.CODOBIECT,PN.CodObiect)';
  EXECUTE sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT coalesce(NE.CODOBIECT,PN.CodObiect),
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantComandat else PN.Cant/PN0.Cant*C1.CantComandat end) CantC,
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantAcceptat else PN.Cant/PN0.Cant*C1.CantAcceptat end) CantA,
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.RestLansat   else PN.Cant/PN0.Cant*C1.RestLansat   end) RestA,
            ''CCPANALA'','||vUserId::varchar||' '||
      'FROM COMANDA C '||
        'INNER JOIN COMANDA1   C1  ON C.CodComanda   = C1.CodComanda '||
        'INNER JOIN PROIECTNOD PN  ON C1.CODPROIECT  = PN.CODPROIECT  AND PN.TIP = 3 '||
        'INNER JOIN PROIECTNOD PN0 ON C1.CODPROIECT  = PN0.CODPROIECT AND coalesce(PN0.NODORIGINAL, 0) = 0 '||
        'LEFT  JOIN NODECHIV   NE  ON C1.CODCOMANDA1 = NE.CODCOMANDA1 AND PN.CODPROIECTNOD = NE.CODPROIECTNOD '||
      'WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0  AND coalesce(C.DispLivrare, 0) = 0 AND C.TipDoc = 18 '||
        'AND C1.RestLansat &gt; 0 and coalesce(c1.exceptional,0) = 0 '||vCond_Subunit_C||vCondIntrari||' '||
      'GROUP BY coalesce(NE.CODOBIECT,PN.CodObiect)';
  EXECUTE sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT coalesce(NE.CODOBIECT,PN.CodObiect),
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantComandat else PN.Cant/PN0.Cant*C1.CantComandat end) CantC,
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantAcceptat else PN.Cant/PN0.Cant*C1.CantAcceptat end) CantA,
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.RestLansat   else PN.Cant/PN0.Cant*C1.RestLansat   end) RestA,
            ''CIIESPANALA'','||vUserId::varchar||' '||
      'FROM COMANDA C '||
        'INNER JOIN COMANDA1   C1  ON C.CodComanda   = C1.CodComanda '||
        'INNER JOIN PROIECTNOD PN  ON C1.CODPROIECT  = PN.CODPROIECT  AND PN.TIP = 3 '||
        'INNER JOIN PROIECTNOD PN0 ON C1.CODPROIECT  = PN0.CODPROIECT AND coalesce(PN0.NODORIGINAL, 0) = 0 '||
        'LEFT  JOIN NODECHIV   NE  ON C1.CODCOMANDA1 = NE.CODCOMANDA1 AND PN.CODPROIECTNOD = NE.CODPROIECTNOD '||
      'WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND C.DispLivrare = 2 AND C.TipDoc = 18 '||
        'AND C1.RestLansat &gt; 0 and coalesce(c1.exceptional,0) = 0 '||vCond_Subunit_C||vCondIntrari||' '||
      'GROUP BY coalesce(NE.CODOBIECT,PN.CodObiect)';
  EXECUTE sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT coalesce(NE.CODOBIECT,PN.CodObiect),
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantComandat else PN.Cant/PN0.Cant*C1.CantComandat end) CantC,
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantAcceptat else PN.Cant/PN0.Cant*C1.CantAcceptat end) CantA,
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.RestLansat   else PN.Cant/PN0.Cant*C1.RestLansat   end) RestA,
            ''CCPER'','||vUserId::varchar||' '||
      'FROM COMANDA C '||
        'INNER JOIN COMANDA1   C1  ON C.CodComanda   = C1.CodComanda '||
        'INNER JOIN PROIECTNOD PN  ON C1.CODPROIECT  = PN.CODPROIECT  AND PN.TIP = 3 '||
        'INNER JOIN PROIECTNOD PN0 ON C1.CODPROIECT  = PN0.CODPROIECT AND coalesce(PN0.NODORIGINAL, 0) = 0 '||
        'LEFT  JOIN NODECHIV   NE  ON C1.CODCOMANDA1 = NE.CODCOMANDA1 AND PN.CODPROIECTNOD = NE.CODPROIECTNOD '||
      'WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND coalesce(C.DispLivrare, 0) = 0 AND C.TipDoc = 18 '||
        'AND C1.RestLansat &gt; 0 and coalesce(c1.exceptional,0) = 0 '||vCond_Subunit_C||vCondIesiri||' '||
      'GROUP BY coalesce(NE.CODOBIECT,PN.CodObiect)';
  EXECUTE sSelect;
  sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||
    'SELECT coalesce(NE.CODOBIECT,PN.CodObiect),
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantComandat else PN.Cant/PN0.Cant*C1.CantComandat end) CantC,
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.CantAcceptat else PN.Cant/PN0.Cant*C1.CantAcceptat end) CantA,
            SUM(case when NE.codobiect &gt; 0 then NE.Paritate * PN.Cant/PN0.Cant*C1.RestLansat   else PN.Cant/PN0.Cant*C1.RestLansat   end) RestA,
            ''CIPER'','||vUserId::varchar||' '||
      'FROM COMANDA C '||
        'INNER JOIN COMANDA1   C1  ON C.CodComanda   = C1.CodComanda '||
        'INNER JOIN PROIECTNOD PN  ON C1.CODPROIECT  = PN.CODPROIECT  AND PN.TIP = 3 '||
        'INNER JOIN PROIECTNOD PN0 ON C1.CODPROIECT  = PN0.CODPROIECT AND coalesce(PN0.NODORIGINAL, 0) = 0 '||
        'LEFT  JOIN NODECHIV   NE  ON C1.CODCOMANDA1 = NE.CODCOMANDA1 AND PN.CODPROIECTNOD = NE.CODPROIECTNOD '||
      'WHERE coalesce(C.INCHISA, 0) = 0 AND C.Operat = 1 AND C.Anulat = 0 AND C.DispLivrare = 2 AND C.TipDoc = 18 '||
        'AND C1.RestLansat &gt; 0 and coalesce(c1.exceptional,0) = 0 '||vCond_Subunit_C||vCondIesiri||' '||
      'GROUP BY coalesce(NE.CODOBIECT,PN.CodObiect)';
  EXECUTE sSelect;

  /*informatii aduse din planificari*/
  if vSetimana = 1 then
    vPrevAn := vAn - 1;
    vPrevSetimana := 53;
  else
    vPrevAn := vAn;
    vPrevSetimana := vSetimana - 1;
  end if;
  if vPrevSetimana = 1 then
    vPPrevAn := vPrevAn - 1;
    vPPrevSetimana := 53;
  else
    vPPrevAn := vPrevAn;
    vPPrevSetimana := vPrevSetimana - 1;
  end if;

  if vSupliment = 0 then
    select count(*) into vCount
    from planifprod
    where ((saptamana = vSetimana and an = vAn and (subunitatea = GETSUBUNITATE() or GETSUBUNITATE() = 1)) or
         (saptamana = vPrevSetimana and an = vPrevAn and (subunitatea = GETSUBUNITATE() or GETSUBUNITATE() = 1)) or
         (saptamana = vPPrevSetimana and an = vPPrevAn and (subunitatea = GETSUBUNITATE() or GETSUBUNITATE() = 1))
          )
          and anulat = 0;
    if vCount &gt; 0 then
      DELETE FROM TMP_PLANIFNODZ;
      INSERT INTO TMP_PLANIFNODZ (CODRETETA, CODOBIECT, NECESAR)
      SELECT CODRETETA, CODOBIECT, SUM(NECESAR)
      FROM (
            SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
            FROM PLANIFNOD PNOD
                 INNER JOIN PLANIFPROD1 PP1  ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                 INNER JOIN PLANIFPROD  PP   ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
                 INNER JOIN NECESARDOC  NECP ON NECP.CODPLANIFPROD = PP.CODPLANIFPROD
            WHERE PP.An = vAn and PP.Saptamana = vSetimana 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 NECP.CODNECESAR = vCodNecesar
            UNION ALL
            SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
            FROM PLANIFNOD PNOD
                 INNER JOIN PLANIFPROD1 PP1  ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                 INNER JOIN PLANIFPROD  PP   ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
                 INNER JOIN NECESARDOC  NECP ON NECP.CODPLANIFPROD = PP.CODPLANIFPROD
            WHERE PP.An = vAn and PP.Saptamana = vSetimana 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 NECP.CODNECESAR = vCodNecesar
            UNION ALL
            SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
            FROM PLANIFNOD PNOD
                 INNER JOIN PLANIFPROD1 PP1  ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                 INNER JOIN PLANIFPROD  PP   ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
                 INNER JOIN NECESARDOC  NECP ON NECP.CODPLANIFPROD = PP.CODPLANIFPROD
            WHERE PP.An = vAn and PP.Saptamana = vSetimana 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 NECP.CODNECESAR = vCodNecesar
            UNION ALL
            select codreteta, codobiect, NEXTWEEK necesar
            from
                (SELECT L1.CODRETETA, L1.CODOBIECT, sum(coalesce(l1.nextweek,0)) nextweek
                 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 = vPrevAn and l.saptamana = vPrevSetimana
                       and l1.nextweek &gt; 0
                       AND L.SUBUNITATEA = GETSUBUNITATE()
                 group by l1.codreteta, l1.codobiect
                 ) A_PG
             ) B_PG
       group by codobiect, codreteta;

       sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '                                                         ||CHR(13)||
        'SELECT MAT.CodObiect, SUM((TMP.NECESAR)/PC.CANT*MAT.CANT) CantC, SUM(coalesce(REPORT.NEXTWEEK,0)/PC.CANT*MAT.CANT) CantA, SUM((TMP.NECESAR - coalesce(REPORT.NEXTWEEK,0))/PC.CANT*MAT.CANT) - coalesce(LANS.STINS,0) RestA, ''PLANIFPER'','||vUserId||' '||CHR(13)||
        'FROM TMP_PLANIFNODZ TMP '                                                                                                       ||CHR(13)||
        '     INNER JOIN PRODCOMP PC ON TMP.CODRETETA = PC.CODPRODCOMP '                                                                 ||CHR(13)||
        '     INNER JOIN PRODMAT MAT ON PC.CODPRODCOMP = MAT.CODPRODCOMP '                                                               ||CHR(13)||
        '     LEFT JOIN ( '                                                                                                              ||CHR(13)||
        '                SELECT L1.CODRETETA, L1.CODOBIECT, SUM(coalesce(L1.NEXTWEEK,0)) NEXTWEEK '                                      ||CHR(13)||
        '                from LANSZ1 L1 '                                                                                                ||CHR(13)||
        '                     inner join LANSZ l on l.codlansz = l1.codlansz '                                                           ||CHR(13)||
        '                where l.operat = 1 and l.anulat = 0 and l.blocat = 0 '                                                          ||CHR(13)||
        '                      and l.an = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar                             ||CHR(13)||
        '                      and l1.nextweek &gt; 0 '                                                                                     ||CHR(13)||
        '                      AND L.SUBUNITATEA = GETSUBUNITATE() '                                                                     ||CHR(13)||
        '               group by l1.codreteta, l1.codobiect '                                                                            ||CHR(13)||
        '               ) REPORT ON REPORT.CODRETETA = TMP.CODRETETA'                                                                    ||CHR(13)||
        '     LEFT JOIN (SELECT CODOBIECT, SUM(STINS) STINS FROM ( '                                                                     ||CHR(13)||
        '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                                                      ||CHR(13)||
        '                FROM IESPRODLINK IL '                                                                                           ||CHR(13)||
        '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '                                        ||CHR(13)||
        '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_LUNI '                                          ||CHR(13)||
        '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '                                               ||CHR(13)||
        '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
        '                      AND L.SUBUNITATEA = GETSUBUNITATE() '                                                                     ||CHR(13)||
        '                group by cmd.codobiect '                                                                                        ||CHR(13)||
        '                union all '                                                                                                     ||CHR(13)||
        '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                                                      ||CHR(13)||
        '                FROM IESPRODLINK IL '                                                                                           ||CHR(13)||
        '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '                                        ||CHR(13)||
        '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_MARTI '                                         ||CHR(13)||
        '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '                                               ||CHR(13)||
        '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
        '                      AND L.SUBUNITATEA = GETSUBUNITATE() '                                                                     ||CHR(13)||
        '                group by cmd.codobiect '                                                                                        ||CHR(13)||
        '                union all '                                                                                                     ||CHR(13)||
        '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                                                      ||CHR(13)||
        '                FROM IESPRODLINK IL '                                                                                           ||CHR(13)||
        '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '                                        ||CHR(13)||
        '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_MIERCURI '                                      ||CHR(13)||
        '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '                                               ||CHR(13)||
        '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
        '                      AND L.SUBUNITATEA = GETSUBUNITATE() '                                                                     ||CHR(13)||
        '                group by cmd.codobiect '                                                                                        ||CHR(13)||
        '                union all '                                                                                                     ||CHR(13)||
        '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                                                      ||CHR(13)||
        '                FROM IESPRODLINK IL '                                                                                           ||CHR(13)||
        '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '                                        ||CHR(13)||
        '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_JOI '                                           ||CHR(13)||
        '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '                                               ||CHR(13)||
        '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
        '                      AND L.SUBUNITATEA = GETSUBUNITATE() '                                                                     ||CHR(13)||
        '                group by cmd.codobiect '                                                                                        ||CHR(13)||
        '                union all '                                                                                                     ||CHR(13)||
        '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                                                      ||CHR(13)||
        '                FROM IESPRODLINK IL '                                                                                           ||CHR(13)||
        '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '                                        ||CHR(13)||
        '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_VINERI '                                        ||CHR(13)||
        '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '                                               ||CHR(13)||
        '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
        '                      AND L.SUBUNITATEA = GETSUBUNITATE() '                                                                     ||CHR(13)||
        '                group by cmd.codobiect '                                                                                        ||CHR(13)||
        '                union all '                                                                                                     ||CHR(13)||
        '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                                                      ||CHR(13)||
        '                FROM IESPRODLINK IL '                                                                                           ||CHR(13)||
        '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '                                        ||CHR(13)||
        '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_SAMBATA '                                       ||CHR(13)||
        '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '                                               ||CHR(13)||
        '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
        '                      AND L.SUBUNITATEA = GETSUBUNITATE() '                                                                     ||CHR(13)||
        '                group by cmd.codobiect '                                                                                        ||CHR(13)||
        '                union all '                                                                                                     ||CHR(13)||
        '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '                                                                      ||CHR(13)||
        '                FROM IESPRODLINK IL '                                                                                           ||CHR(13)||
        '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '                                        ||CHR(13)||
        '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_DUMINICA '                                      ||CHR(13)||
        '                     INNER JOIN LANSZ       L  ON L1.CODLANSZ      = L.CODLANSZ '                                               ||CHR(13)||
        '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
        '                      AND L.SUBUNITATEA = GETSUBUNITATE() '                                                                     ||CHR(13)||
        '                group by cmd.codobiect '                                                                                        ||CHR(13)||
        '                ) GROUP BY CODOBIECT) LANS ON LANS.CODOBIECT = MAT.CODOBIECT  '                                                 ||CHR(13)||
        'WHERE coalesce(MAT.TIP,3) &gt; 2 '                                                                                                 ||CHR(13)||
        'GROUP BY MAT.CodObiect, coalesce(LANS.STINS,0)';
        EXECUTE sSelect;

        DELETE FROM TMP_PLANIFNODZ;
        INSERT INTO TMP_PLANIFNODZ (CODRETETA, CODOBIECT, NECESAR)
        SELECT CODRETETA, CODOBIECT, SUM(NECESAR)
        FROM (
              SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
              FROM PLANIFNOD PNOD
                   INNER JOIN PLANIFPROD1 PP1 ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                   INNER JOIN PLANIFPROD  PP  ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
              WHERE PP.An = vPrevAn and PP.Saptamana = vPrevSetimana 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 PP.SUBUNITATEA = GETSUBUNITATE()
              UNION ALL
              SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
              FROM PLANIFNOD PNOD
                   INNER JOIN PLANIFPROD1 PP1 ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                   INNER JOIN PLANIFPROD  PP  ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
              WHERE PP.An = vPrevAn and PP.Saptamana = vPrevSetimana 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 PP.SUBUNITATEA = GETSUBUNITATE()
              UNION ALL
              SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
              FROM PLANIFNOD PNOD
                   INNER JOIN PLANIFPROD1 PP1 ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
                   INNER JOIN PLANIFPROD  PP  ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
              WHERE PP.An = vPrevAn and PP.Saptamana = vPrevSetimana 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 PP.SUBUNITATEA = GETSUBUNITATE()
              UNION ALL
              (
              select codreteta, codobiect, nextweek necesar
              from
                  (SELECT distinct L1.CODRETETA, L1.CODOBIECT, sum(coalesce(l1.nextweek,0)) nextweek
                   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 = vPPrevAn and l.saptamana = vPPrevSetimana
                         and l1.nextweek &gt; 0
                         AND L.SUBUNITATEA = GETSUBUNITATE()
                   group by l1.codreteta, l1.codobiect
                   ) A_PG
               )
             ) C_PG
       group by codobiect, codreteta;

       sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||CHR(13)||
        'SELECT MAT.CodObiect, SUM((TMP.NECESAR)/PC.CANT*MAT.CANT) CantC, SUM(coalesce(REPORT.NEXTWEEK,0)/PC.CANT*MAT.CANT) CantA, SUM((TMP.NECESAR - coalesce(REPORT.NEXTWEEK,0))/PC.CANT*MAT.CANT) - coalesce(LANS.STINS,0) RestA, ''PLANIFPREV'','||vUserId||' '||CHR(13)||
        'FROM TMP_PLANIFNODZ TMP '||CHR(13)||
        '     INNER JOIN PRODCOMP PC ON TMP.CODRETETA  = PC.CODPRODCOMP '||CHR(13)||
        '     INNER JOIN PRODMAT MAT ON PC.CODPRODCOMP = MAT.CODPRODCOMP '||CHR(13)||
        '     LEFT JOIN ( '||CHR(13)||
        '                SELECT L1.CODRETETA, L1.CODOBIECT, SUM(coalesce(L1.NEXTWEEK,0)) NEXTWEEK '||CHR(13)||
        '                from LANSZ1 L1 '||CHR(13)||
        '                     inner join LANSZ l on l.codlansz = l1.codlansz '||CHR(13)||
        '                where l.operat = 1 and l.anulat = 0 and l.blocat = 0 '||CHR(13)||
        '                      and l.an = '||vPPrevAn::varchar||' and l.saptamana = '||vPPrevSetimana::varchar||CHR(13)||
        '                      and l1.nextweek &gt; 0 '||CHR(13)||
        '                      AND L.SUBUNITATEA = GETSUBUNITATE() '||CHR(13)||
        '                group by l1.codreteta, l1.codobiect '||CHR(13)||
        '               ) REPORT ON REPORT.CODRETETA = TMP.CODRETETA'||CHR(13)||
        '     LEFT JOIN (SELECT CODOBIECT, SUM(STINS) STINS FROM ( '||CHR(13)||
        '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
        '                FROM IESPRODLINK IL '||CHR(13)||
        '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
        '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_LUNI '||CHR(13)||
        '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
        '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
        '                      AND L.SUBUNITATEA = GETSUBUNITATE() '||CHR(13)||
        '                group by cmd.codobiect '||CHR(13)||
        '                union all '||CHR(13)||
        '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
        '                FROM IESPRODLINK IL '||CHR(13)||
        '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
        '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_MARTI '||CHR(13)||
        '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
        '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
        '                      AND L.SUBUNITATEA = GETSUBUNITATE() '||CHR(13)||
        '                group by cmd.codobiect '||CHR(13)||
        '                union all '||CHR(13)||
        '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
        '                FROM IESPRODLINK IL '||CHR(13)||
        '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
        '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_MIERCURI '||CHR(13)||
        '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
        '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
        '                      AND L.SUBUNITATEA = GETSUBUNITATE() '||CHR(13)||
        '                group by cmd.codobiect '||CHR(13)||
        '                union all '||CHR(13)||
        '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
        '                FROM IESPRODLINK IL '||CHR(13)||
        '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
        '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_JOI '||CHR(13)||
        '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
        '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
        '                      AND L.SUBUNITATEA = GETSUBUNITATE() '||CHR(13)||
        '                group by cmd.codobiect '||CHR(13)||
        '                union all '||CHR(13)||
        '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
        '                FROM IESPRODLINK IL '||CHR(13)||
        '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
        '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_VINERI '||CHR(13)||
        '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
        '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
        '                      AND L.SUBUNITATEA = GETSUBUNITATE() '||CHR(13)||
        '                group by cmd.codobiect '||CHR(13)||
        '                union all '||CHR(13)||
        '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
        '                FROM IESPRODLINK IL '||CHR(13)||
        '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
        '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_SAMBATA '||CHR(13)||
        '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
        '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
        '                      AND L.SUBUNITATEA = GETSUBUNITATE() '||CHR(13)||
        '                group by cmd.codobiect '||CHR(13)||
        '                union all '||CHR(13)||
        '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
        '                FROM IESPRODLINK IL '||CHR(13)||
        '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
        '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_DUMINICA '||CHR(13)||
        '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
        '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vPrevAn::varchar||' and l.saptamana = '||vPrevSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
        '                      AND L.SUBUNITATEA = GETSUBUNITATE() '||CHR(13)||
        '                group by cmd.codobiect '||CHR(13)||
        '                ) GROUP BY CODOBIECT) LANS ON LANS.CODOBIECT = MAT.CODOBIECT  '||CHR(13)||
        'WHERE coalesce(MAT.TIP,3) &gt; 2 '||CHR(13)||
        'GROUP BY MAT.CodObiect,coalesce(LANS.STINS,0)';
        EXECUTE sSelect;
    end if;
  else
    DELETE FROM TMP_PLANIFNODZ;
    INSERT INTO TMP_PLANIFNODZ (CODRETETA, CODOBIECT, NECESAR)
    SELECT CODRETETA, CODOBIECT, SUM(NECESAR)
    FROM (
          SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
          FROM PLANIFNOD PNOD
               INNER JOIN PLANIFPROD1 PP1  ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
               INNER JOIN PLANIFPROD  PP   ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
               INNER JOIN NECESARDOC  NECP ON NECP.CODPLANIFPROD = PP.CODPLANIFPROD
          WHERE PP.An = vAn and PP.Saptamana = vSetimana 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 NECP.CODNECESAR = vCodNecesar
          UNION ALL
          SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
          FROM PLANIFNOD PNOD
               INNER JOIN PLANIFPROD1 PP1  ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
               INNER JOIN PLANIFPROD  PP   ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
               INNER JOIN NECESARDOC  NECP ON NECP.CODPLANIFPROD = PP.CODPLANIFPROD
          WHERE PP.An = vAn and PP.Saptamana = vSetimana 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 NECP.CODNECESAR = vCodNecesar
          UNION ALL
          SELECT PNOD.CODRETETA, PNOD.CODOBIECT, PNOD.NECESAR
          FROM PLANIFNOD PNOD
               INNER JOIN PLANIFPROD1 PP1  ON PP1.CODPLANIFPROD1 = PNOD.CODPLANIFPROD1
               INNER JOIN PLANIFPROD  PP   ON PP.CODPLANIFPROD   = PP1.CODPLANIFPROD
               INNER JOIN NECESARDOC  NECP ON NECP.CODPLANIFPROD = PP.CODPLANIFPROD
          WHERE PP.An = vAn and PP.Saptamana = vSetimana 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 NECP.CODNECESAR = vCodNecesar
          ) A_PG
     group by codobiect, codreteta;

     sSelect := 'insert into tmp_cmd(codobiect,cantc,canta,resta,tip,userid) '||CHR(13)||
      'SELECT MAT.CodObiect, SUM((TMP.NECESAR)/PC.CANT*MAT.CANT) CantC, 0 CantA, SUM(TMP.NECESAR/PC.CANT*MAT.CANT) - coalesce(LANS.STINS,0) RestA, ''PLANIFPER'','||vUserId||' '||CHR(13)||
      'FROM TMP_PLANIFNODZ TMP '||CHR(13)||
      '     INNER JOIN PRODCOMP PC ON TMP.CODRETETA = PC.CODPRODCOMP '||CHR(13)||
      '     INNER JOIN PRODMAT MAT ON PC.CODPRODCOMP = MAT.CODPRODCOMP '||CHR(13)||
      '     LEFT JOIN (SELECT CODOBIECT, SUM(STINS) STINS
                       FROM ( '||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
      '                FROM IESPRODLINK IL '||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_LUNI '||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                      AND L.SUBUNITATEA = GETSUBUNITATE() '||CHR(13)||
      '                group by cmd.codobiect '||CHR(13)||
      '                union all '||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
      '                FROM IESPRODLINK IL '||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_MARTI '||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                      AND L.SUBUNITATEA = GETSUBUNITATE() '||CHR(13)||
      '                group by cmd.codobiect '||CHR(13)||
      '                union all '||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
      '                FROM IESPRODLINK IL '||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_MIERCURI '||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                      AND L.SUBUNITATEA = GETSUBUNITATE() '||CHR(13)||
      '                group by cmd.codobiect '||CHR(13)||
      '                union all '||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
      '                FROM IESPRODLINK IL '||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_JOI '||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                      AND L.SUBUNITATEA = GETSUBUNITATE() '||CHR(13)||
      '                group by cmd.codobiect '||CHR(13)||
      '                union all '||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
      '                FROM IESPRODLINK IL '||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_VINERI '||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                      AND L.SUBUNITATEA = GETSUBUNITATE() '||CHR(13)||
      '                group by cmd.codobiect '||CHR(13)||
      '                union all '||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
      '                FROM IESPRODLINK IL '||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_SAMBATA '||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                      AND L.SUBUNITATEA = GETSUBUNITATE() '||CHR(13)||
      '                group by cmd.codobiect '||CHR(13)||
      '                union all '||CHR(13)||
      '                SELECT CMD.CODOBIECT, SUM(IL.CANT) STINS '||CHR(13)||
      '                FROM IESPRODLINK IL '||CHR(13)||
      '                     INNER JOIN CMDPRODMAT CMD ON IL.CODCMDPRODMAT = CMD.CODCMDPRODMAT '||CHR(13)||
      '                     INNER JOIN LANSZ1     L1  ON CMD.CODCOMANDA1  = L1.CODCMD1_DUMINICA '||CHR(13)||
      '                     INNER JOIN LANSZ      L   ON L1.CODLANSZ      = L.CODLANSZ '||CHR(13)||
      '                WHERE coalesce(L.ANULAT,0) = 0 AND L.AN = '||vAn::varchar||' and l.saptamana = '||vSetimana::varchar||' AND CMD.TIP = 1 '||CHR(13)||
      '                      AND L.SUBUNITATEA = GETSUBUNITATE() '||CHR(13)||
      '                group by cmd.codobiect '||CHR(13)||
      '                ) GROUP BY CODOBIECT
                      ) LANS ON LANS.CODOBIECT = MAT.CODOBIECT  '||CHR(13)||
      'GROUP BY MAT.CodObiect, coalesce(LANS.STINS,0)';
      EXECUTE sSelect;
  end if;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nartofe_processlist</obj_name>
  <obj_hashval>bf0d189966a0f25767ed3f5f5ab32ee1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nartofe_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sJoinDC         varchar := '';
  sJoinPA         varchar := '';
  sCursPA         varchar := '';
  sInsertDC       varchar := '';
  sSelectDC       varchar := '';
  sMultimeCatPret varchar := '';
  sCondCatPret    varchar;
  sColMinMax      varchar := ', os.stocmin, os.stocmed, os.stocmax';
  gSuplCols       varchar := '';
  gUserFields     VARCHAR := '';
  gUserAlias      VARCHAR := '';
  gNullAlias      VARCHAR := '';
  gSuplJoins      VARCHAR := '';
  AnPrec          numeric;
  LunaPrec        numeric;
  k               NUMERIC;
  aSitV           numeric;
  aBancaV         numeric;
  aMonedaV        numeric;
  XNRCOL          numeric;
  sSubunitate     varchar := '';
  nSubunitate     NUMERIC;
  wmeRes          boolean;
  sView           TEXT;
BEGIN
  --Stef 21.11.2021 - sinc.Oracle

  sSubunitate := coalesce(current_setting('PKG_GLOBALS.SUBUNITATE', true),'0');
  nSubunitate := coalesce(getSubunitate(),0);

  gSuplCols := 'nartobj o, nart a, pretm p, nsubunit sub, ncatpret ncp, nartimplicite nai, num u, num1 u1, num1 uamb, ngest ng, nmonede mon, nclasea c, npart npart, '
            || 'ntaxe ntacc, ntaxe ntax1, ntaxe ntax2, ncont nc, nagenda nag, nlocalit loc, njudet jud';
  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_NARTOFE.gSuplCols', gSuplCols, False);

  IF  getSUBUNITATE() = 1 THEN
    sColMinMax := ', o.stocmin, o.stocmed, o.stocmax';
  END IF;

  IF  nSubunitate &lt;&gt; 1 AND  coalesce(fnc_GetValConstanta('PretAchizSubunit', getanlucru(), getlunalucru()),'0') = '2' THEN
    sJoinPA := '
      INNER JOIN NGEST NG ON NG.CODGEST = N.GEST AND NG.CODSUBUNIT = ' || sSubunitate;
  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
    sCursPA := '/ (Select wme_result From PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null, ' || coalesce(aMonedaV::varchar,'') || ',' || coalesce(aBancaV::varchar,'') || ', to_char(pa.dataachizlast,''dd.mm.yyyy'') ) )';
  END IF;

  IF current_setting('PKG_LIST_BASE_NARTOFE.vPretImplicit', true)::numeric = 1  OR  current_setting('PKG_LIST_BASE_NARTOFE.vCatPret', true)::numeric &lt;= 0 THEN
    sCondCatPret := coalesce((SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'p',NULL,NULL,NULL)),'') || ' AND p.implicit = 1 ';
  ELSE
    sCondCatPret := coalesce((SELECT WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'p',NULL,NULL,NULL)),'') || ' AND p.codcatpret = ' || coalesce(current_setting('PKG_LIST_BASE_NARTOFE.vCatPret', true),'');
  END IF;

  PERFORM pkg_globals_SetLunaTemp(getanlucru(), getlunalucru());
  select  NEWAN, newLuna from PKG_GLOBALS_CALCULEAZA_LUNA_PRECEDENTA(getanlucru(),getlunalucru(), AnPrec, LunaPrec) into AnPrec, LunaPrec;
  PERFORM pkg_globals_SetLunaPRECEDENTA(AnPrec, LunaPrec);

  PERFORM pkg_stoc_generare_facturi_make_config_luna();

  XNRCOL := coalesce(current_setting('PKG_LIST_BASE_NARTOFE.vNrCol', true),'0')::numeric;

  IF  XNRCOL &gt; 0 THEN
    sJoinDC := '
      LEFT JOIN (
        SELECT p.codobiect';

    FOR k IN 1..XNRCOL LOOP
      sJoinDC   := sJoinDC||',Max((case when c.x= '||k||' then p.lei else 0 end)) l'||k||', Max((case when c.x= '||k||' then p.valuta else 0 end)) v'||k;
      sInsertDC := sInsertDC||',L'||k||', V'||k;
      sSelectDC := sSelectDC||',dc.L'||k||', dc.V'||k;
    END LOOP;

    sMultimeCatPret := '&lt;&gt; 0';

    IF  current_setting('PKG_LIST_BASE_NARTOFE.vCatPret', true)::numeric = -1 THEN
      IF current_setting('PKG_LIST_BASE_NARTOFE.vToateArt', true)::numeric = 1   THEN
        sMultimeCatPret := 'in ( select distinct CODCATPRET from PretM )';
      ELSE
        sMultimeCatPret := 'in ( select distinct CODCATPRET from PretM where codobiect::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT''))';
      END IF;
    ELSE
      sMultimeCatPret := '&lt;&gt; 0';
    END IF;

    sJoinDC := coalesce(sJoinDC,'') || '
      FROM ( SELECT Dense_Rank() OVER (ORDER BY CODCATPRET) x, CODCATPRET FROM ncatpret WHERE CODCATPRET ' || coalesce(sMultimeCatPret,'') || ') c
        LEFT JOIN pretm p ON p.codcatpret = c.codcatpret
      WHERE p.subunitatea = '||sSubunitate;
     IF  current_setting('PKG_LIST_BASE_NARTOFE.vToateArt', true)::numeric = 0 THEN
      sJoinDC := coalesce(sJoinDC,'') || '
        AND p.codobiect::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' )';
    END IF;

    sJoinDC := coalesce(sJoinDC,'') || '
        GROUP BY p.codobiect
      ) dc ON dc.codobiect = o.codobiect';
  END IF;

  SELECT v_stocluna() INTO sView;

  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(
    CodObiect, DenArt, CodExtern, TipSer, DenUM, DenClasaA,
    Masa, Volum, PretVinz, PretValuta, TVAPret, ProcTVA, Moneda,
    TipUM, PretMaximal, StocMinim, StocMediu, StocMaxim, TipArticol, TipContabil,
    ContImplicit, CodArt, StocCurent, PretPrestab, CodIntern, Producator, SimbolClasaA,
    GestImpl, CodVamal, Accize, TaxeSupl1, TaxeSupl2,
    Promotie, UMAmb, ParAmb, CNAS, ARETG,
    tippretmax,
    PRETMIN, SUBUNITATEA,
    PRACHIZLAST, PRACHIZLASTV, PRACHIZMAX
    , x_Judet, X_CodSubunit,X_CodGest,X_CodClasaP ' || coalesce(sInsertDC,'') || gUserFields || ' )
  WITH S AS (
    SELECT ns.codobiect, SUM(vs.rest) rest
    FROM ('||sView||') vs
      INNER JOIN nirstoc ns ON ns.codnirstoc = vs.codnirstoc
      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', '
    WHERE',NULL))::varchar ,'') || '
    GROUP BY ns.codobiect),
  PA AS (
    SELECT
      NS.CODOBIECT,
      MAX(PRACHIZLAST) PRACHIZLAST,
      MAX(N.DATANIR) DATAACHIZLAST,
      MAX(NS.PRET-NS.ADAOS) PRACHIZMAX
    FROM (
          Select x.CODOBIECT,MAX(x.PRET-x.ADAOS) PRACHIZLAST
          From (Select NS.CODOBIECT,NS.PRET,NS.ADAOS,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 ' || coalesce(sJoinPA,'') || '
                Where N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 15) AND N.OPERAT = 1 AND N.ANULAT = 0
               ) x Where x.NR=1
          Group by x.CODOBIECT
         ) S
         INNER JOIN NIRSTOC NS ON NS.CODOBIECT = S.CODOBIECT
         INNER JOIN NIR     N  ON N.CODNIR     = NS.CODNIR ' || coalesce(sJoinPA,'') || '
    WHERE N.TIPNIR IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 15) AND N.OPERAT = 1 AND N.ANULAT = 0';

  IF  current_setting('PKG_LIST_BASE_NARTOFE.vToateArt', true)::numeric = 0 THEN
    sInsert := sInsert || '
        AND ns.codobiect::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' )';
  END IF;

  sInsert := sInsert || '
    GROUP BY NS.CODOBIECT )
  SELECT
    o.codobiect, o.denumire, o.codextern, CASE a.tipserie WHEN 0 THEN ''fara serie'' WHEN 1 THEN ''serie pe bucata'' WHEN 2 THEN ''serie pe lot'' ELSE '''' END, u.den_um , c.Den_Clasea,
    o.Masa, o.Volum, p.lei as PretVanz, p.valuta, CASE ncp.tip WHEN 1 THEN ''Da'' ELSE ''NU'' END, t.procent, mon.den_moneda,
    u.tip, o1.pretmaximal'||sColMinMax||', CASE a.tiparticol WHEN ''0'' THEN ''Stoc'' ELSE ''Serviciu'' END, ioa.den_ioart,
    nc.simbol, a.codarticol, COALESCE(s.rest,0), o1.pretreferinta, o.codintern, npart.den_part, c.simbol ,
    ng.den_gest, o.codvamal, ntacc.den_taxa, ntax1.den_taxa, ntax2.den_taxa,
    CASE o.promotie WHEN 0 THEN ''Nu'' ELSE ''Da'' END, uamb.den_um1, uamb.paritate, o.codcnas, CASE a.aretg WHEN 0 THEN ''Nu'' ELSE ''Da'' END aretg,
    CASE o1.tippretmax
      WHEN 1 THEN ''din stoc * Impus''
      WHEN 2 THEN ''din stoc * Recomandat''
      WHEN 3 THEN ''din stoc * Netransmisibil''
      WHEN 4 THEN ''lunar * Impus''
      WHEN 5 THEN ''lunar * Recomandat''
      WHEN 6 THEN ''lunar * Netransmisibil''
      WHEN 7 THEN ''nu se foloseste''
      ELSE '' ''
    END TIPPRETMAX,
    o.pretminim, sub.den_subunit,
    pa.prachizlast, pa.prachizlast '||sCursPA||', pa.prachizmax,
    coalesce(JUD.SIMBAUTO,''XX''), sub.codsubunit, ng.codgest, npart.codclasa '||sSelectDC||gUserAlias||'
  FROM nartobj o
    LEFT JOIN nart             a     ON a.codarticol   = o.codarticol
    LEFT JOIN nartobjsubunit   os    ON os.codobiect   = o.codobiect and (os.codgest is null or os.codgest = 0) AND os.subunitate = '||sSubunitate||'
    LEFT JOIN pretm            p     ON p.codobiect    = o.codobiect ' || coalesce(sCondCatPret,'') || '
    LEFT JOIN nsubunit         sub   ON sub.codsubunit = COALESCE(p.subunitatea,' || sSubunitate || ')
    LEFT JOIN ncatpret         ncp   ON ncp.codcatpret = p.codcatpret
    LEFT JOIN tmp_nartobj_luna o1    ON o.codobiect    = o1.codobiect
    LEFT JOIN tmp_nart_luna    a1    on a.codarticol   = a1.codarticol
    LEFT JOIN nartimplicite    nai   ON nai.codarticol = a.codarticol AND nai.codsubunit = COALESCE(p.subunitatea,' || sSubunitate || ')
    LEFT JOIN nartobjimp       noi   ON noi.codobiect  = o.codobiect  AND noi.codsubunit = coalesce(p.subunitatea,'||sSubunitate||')
    LEFT JOIN num              u     ON a.um           = u.codum
    LEFT JOIN num1             u1    ON u1.codum1      = a.um1
    LEFT JOIN num1             uamb  ON uamb.codum1    = o.umambalare
    LEFT JOIN ngest            ng    ON ng.codgest     = nai.gestimplicita
    LEFT JOIN nmonede          mon   ON mon.codmoneda  = p.moneda
    LEFT JOIN nclasea          c     ON c.codclasea    = a.clasa
    LEFT JOIN npart                  ON npart.codpart  = o.codproducator
    LEFT JOIN NAGENDA          NAG   ON npart.codpart  = NAG.CODPART AND NAG.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(NAG.INACTIV, 0) = 0
    LEFT JOIN NLOCALIT         LOC   ON NAG.CODLOCALIT = LOC.CODLOCALIT
    LEFT JOIN NJUDET           JUD   ON JUD.CODJUDET   = LOC.CODJUDET
    LEFT JOIN ntaxe            ntacc ON ntacc.codtaxa  = a1.codaccize
    LEFT JOIN ntaxe            ntax1 ON ntax1.codtaxa  = a1.codtaxa1
    LEFT JOIN ntaxe            ntax2 ON ntax2.codtaxa  = a1.codtaxa2
    LEFT JOIN ioart1           i1    ON i1.codioart    = case when coalesce(noi.contimplicit,0) = 0 then nai.contimplicit else coalesce(noi.contimplicit,0) end AND '||to_char(getanlunalucru(),'fm99999')||' BETWEEN i1.ALStart AND i1.ALStop
    LEFT JOIN ioart            ioa   ON i1.codioart    = ioa.codioart
    LEFT JOIN ncont            nc    ON nc.codcont     = (Case  When a.tiparticol= ''0'' then i1.cont else a.contserviciu end)
    LEFT JOIN ntva1            t     ON t.codtva       = a1.codtva  AND '||to_char(getanlunalucru(),'fm99999')||' BETWEEN t.ALStart AND t.ALStop
    LEFT JOIN s                      on s.codobiect    = o.codobiect
    LEFT JOIN pa                     ON pa.codobiect   = o.codobiect' || coalesce(sJoinDC,'') || gSuplJoins || '
  WHERE o.codarticol &gt; 0 ';

  IF  current_setting('PKG_LIST_BASE_NARTOFE.vToateArt', true)::numeric = 0 THEN
    sInsert := sInsert||'
      AND o.codobiect::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' )';
  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_nartpart_processlist</obj_name>
  <obj_hashval>a5129b724c8caf4338a81b98a0dd45dd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nartpart_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  gSuplCols   varchar := 'npart p, nartobj o, nart a, nartcli ac, num u, num1 u1, num1 uamb, ngest ng, nclasea c, npart prod, ncont nc, nclaseas cs, ncarsupart s, ioart ioa, ntari t, nartobj1 o1, pretm pm';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  sColMinMax  varchar := ', os.stocmin, os.stocmed, os.stocmax';
  sSubunitate varchar;
BEGIN
  --Adina 20.04.2021 - sinc.Oracle
  --Adina 26.03.2021 - alstart, alstop
  --Adina 18.02.2021 - dupa modif.Oracle din 17.02.2021
  sSubunitate := coalesce(current_setting('PKG_GLOBALS.SUBUNITATE', true),'0');

  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_NARTPART.gSuplCols', gSuplCols, False);


  IF  current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric = 1 THEN
    sColMinMax := ', o.stocmin, o.stocmed, o.stocmax';
  END IF;

  sInsert := 'INSERT INTO ' || coalesce(tmpName,'') || '(
      DenPart, DenArt, ArtPart, TipSer,
      DenUM, DenClasaA, SimbolClasaA, Masa, Volum, StocMinim, StocMediu, StocMaxim, TipArticol, TipContabil, ContImplicit,
      CodIntern, CodExtern, CodExtPart,
      CodListat,
      Producator, GestImpl, Promotie, UMAmb, ParAmb, CNAS, AreTG,
      TipPretMax,
      Accize, TaxeSupl1, TaxeSupl2,
      NRCOLETE' || coalesce(gUserFields,'') || ')
  WITH
  NAI AS
  (
    SELECT O.CODOBIECT, COALESCE(NOI.CODSUBUNIT,0) CODSUBUNIT,
          CASE WHEN COALESCE(NOI.CONTIMPLICIT ,0) = 0    THEN NAI.CONTIMPLICIT     ELSE COALESCE(NOI.CONTIMPLICIT ,0)    END CONTIMPLICIT,
          CASE WHEN COALESCE(NOI.GESTIMPLICITA,0) = 0    THEN NAI.GESTIMPLICITA    ELSE COALESCE(NOI.GESTIMPLICITA,0)    END GESTIMPLICITA,
          CASE WHEN COALESCE(NOI.LOCATIEIMPLICITA,0) = 0 THEN NAI.LOCATIEIMPLICITA ELSE COALESCE(NOI.LOCATIEIMPLICITA,0) END LOCATIEIMPLICITA
    FROM NARTOBJ O
         INNER JOIN NART         A   ON A.CODARTICOL = O.CODARTICOL
         LEFT JOIN NARTIMPLICITE NAI ON A.CODARTICOL = NAI.CODARTICOL AND NAI.CODSUBUNIT = '||sSubunitate||'
         LEFT JOIN NARTOBJIMP    NOI ON O.CODOBIECT  = NOI.CODOBIECT  AND NOI.CODSUBUNIT = '||sSubunitate||'
  )
  SELECT
      p.den_part, o.denumire, COALESCE(ac.denumire,ntrad.denumiretrad,o.denumire), (Case  When a.tipserie=0 then ''fara serie'' When a.tipserie= 1 then  ''serie pe bucata'' When a.tipserie= 2 then ''serie pe lot'' end) tipser,
      u.den_um1, c.Den_Clasea, c.simbol, o.Masa, o.Volum, os.stocmin, os.stocmed, os.stocmax, (Case  When a.tiparticol=''0'' then ''Stoc'' else ''Serviciu'' end) TipArt, ioa.den_ioart TipContabil, nc.simbol,
      o.codintern, o.codextern, ac.codextern,
      Coalesce((Case  When ac.tipcodafisat=1 then gre.cod When ac.tipcodafisat=2 then ac.codextern When ac.tipcodafisat=3 then o.codextern When ac.tipcodafisat=4 then o.codintern When ac.tipcodafisat=5 then o.codvamal When ac.tipcodafisat=6 then o.codplu::varchar end),o.codextern),
      prod.den_part, ng.den_gest, (case when o.promotie = 0 then ''Nu'' else ''Da'' end), uamb.den_um1, uamb.paritate, o.codcnas, (case when a.aretg = 0 then ''Nu'' else ''Da'' end) aretg,
     (Case  When o1.TIPPRETMAX= 1 then ''din stoc * Impus''
            When o1.TIPPRETMAX= 2 then ''din stoc * Recomandat''
            When o1.TIPPRETMAX= 3 then ''din stoc * Netransmisibil''
            When o1.TIPPRETMAX= 4 then ''lunar * Impus''
            When o1.TIPPRETMAX= 5 then ''lunar * Recomandat''
            When o1.TIPPRETMAX= 6 then ''lunar * Netransmisibil''
            When o1.TIPPRETMAX= 7 then ''nu se foloseste'' end) ,
      ntacc.den_taxa, ntax1.den_taxa, ntax2.den_taxa,
      (SELECT COUNT(1) FROM nartobjcolet oc WHERE oc.codobiect = o.codobiect)' || coalesce(gUserAlias,'') || '
    FROM nartcli ac
      INNER JOIN npart          p     ON p.codpart         = ac.codpart
      INNER JOIN nartobj        o     ON o.codobiect       = ac.codobiect
      INNER JOIN nart           a     ON a.codarticol      = o.codarticol
      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 ssoc.codlocalit   = lsoc.codlocalit
      LEFT  JOIN ntari          tsoc  ON tsoc.codtara      = lsoc.codtara
      LEFT  JOIN nartobjtrad    ntrad ON ntrad.codlimba   = tsoc.codlimba and ntrad.codobiect = o.codobiect
      LEFT  JOIN nai                  ON nai.codobiect     = o.codobiect
      LEFT  JOIN nechiv         e     ON e.codobiect       = o.codobiect
      LEFT  JOIN grechiv        gre   ON gre.codgrechiv   = e.codgrupa
      LEFT  JOIN nart1          a1    on a.codarticol     = a1.codarticol and ' || GetAnLunaLucru() || ' between a1.alstart and a1.alstop
      LEFT  JOIN nartobjsubunit os    ON os.codobiect     = o.codobiect
                                      and ( os.codgest is null or os.codgest = 0)
                                      AND os.subunitate = ' ||sSubunitate || '
      LEFT  JOIN num1           u     ON u.codum1         = ac.umsec
      LEFT  JOIN num1           u1    ON u1.codum1         = a.um1
      LEFT  JOIN num1           uamb  ON uamb.codum1       = o.umambalare
      LEFT  JOIN ngest          ng    ON ng.codgest       = nai.gestimplicita
      LEFT  JOIN nclasea        c     ON c.codclasea       = a.clasa
      LEFT  JOIN npart          prod  ON prod.codpart      = o.codproducator
      LEFT  JOIN ioart          ioa   ON ioa.codioart     = nai.contimplicit
      LEFT  JOIN ioart1         ioa1  ON ioa1.codioart     = nai.contimplicit and ' || GetAnLunaLucru() || ' between ioa1.alstart and ioa1.alstop
      LEFT  JOIN ncont          nc    ON nc.codcont       = (Case when a.tiparticol = ''0'' then ioa1.cont else a.contserviciu end)
      LEFT  JOIN nclaseas       cs    ON cs.codclaseas     = a.clasastatist
      LEFT  JOIN ncarsupart     s     ON s.codcarsupart   = o.codcaract
      LEFT  JOIN ntari          t     ON t.codtara         = o.taraorigine
      LEFT  JOIN nartobj1       o1    ON o1.codobiect     = o.codobiect and ' || GetAnLunaLucru() || ' between o1.alstart and o1.alstop
      LEFT  JOIN pretm          pm    ON pm.codobiect     = o.codobiect AND pm.implicit = 1 AND pm.subunitatea = ' ||sSubunitate || '
      LEFT  JOIN ntaxe          ntacc ON ntacc.codtaxa     = a1.codaccize
      LEFT  JOIN ntaxe          ntax1 ON ntax1.codtaxa     = a1.codtaxa1
      LEFT  JOIN ntaxe          ntax2 ON ntax2.codtaxa     = a1.codtaxa2' || coalesce(gSuplJoins,'') || '
    WHERE Coalesce(ac.codpart,0) &gt; 0 AND Coalesce(ac.codobiect,0) &gt; 0';

    IF (not pkg_list_selpart_isallpart()) THEN
      sInsert := sInsert || '
        AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPART'' AND VALOARE = ac.CODPART::varchar )';
    END IF;

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nartum_setjoinuri</obj_name>
  <obj_hashval>d17d2b086c97b41bfd8a655b21866620</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nartum_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_NARTUM.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nir_getguseralias</obj_name>
  <obj_hashval>f1495bd3a40e5c62645d537f5a859efc</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_getguseralias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NIR.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_nir_processlist</obj_name>
  <obj_hashval>055a28b5876fef0fe8aa5df21ba80463</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nir_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert          varchar := '';
  sInsertUMA       varchar := '';
  sInsertDez       varchar := '';
  sSelectUMA       varchar := '';
  sSelectDez       varchar := '';
  sJoinUMA         varchar := '';
  sJoinDez         varchar := '';
  aTipNir          numeric;
  gSuplCols        VARCHAR :=   'NIR NIR, NGEST NG, NCONT NC, NLOCATII NL, NUM1 NUM1, NARTOBJ NOBJ, NART NART, NPART NP, NPART PROD, NPART FURN, NCLASEA NCA, NCLASEAS NCLS, NUM UM1, NUM UM2, '||
                              'INTRARI1 I1, INTRARI I, NARTCLI AC, COMANDA1 CF1, COMANDA CF, COMANDA1 CCL1, COMANDA CCL, COMANDA1 CINT1, COMANDA CINT, NPART PARTCMDCL';
   gUserFields     VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vTipDoc          NUMERIC := current_setting('PKG_LIST_BASE_NIR.vTipDoc'    , true)::NUMERIC;
  vCodNir          NUMERIC := current_setting('PKG_LIST_BASE_NIR.vCodNir'    , true)::NUMERIC;
  vCodNirStoc      NUMERIC := current_setting('PKG_LIST_BASE_NIR.vCodNirStoc', true)::NUMERIC;
  vVerso           boolean := current_setting('PKG_LIST_BASE_NIR.vVerso'     , true)::boolean;
  vSEP             VARCHAR := COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|');
BEGIN
  --Florin 09.12.2025 - sinc. Oracle
  --Stef  15.11.2022
  --Stef  10.05.2022
  --Adina 17 septembrie 2020
  --PERFORM pkg_globals_setdebugmode(TRUE);

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs( gSuplCols, 'NPARTDET',    'PD',       'PD.CODPART = NP.CODPART');
  call pkg_list_struct_addsupltabs( gSuplCols, 'NARTOBJEXT',  'OEXT',     'OEXT.CODOBIECT = NOBJ.CODOBIECT');
  call pkg_list_struct_addsupltabs( gSuplCols, 'NARTOBJATR',  'OATR',     'OATR.CODOBIECT = NOBJ.CODOBIECT');
  call pkg_list_struct_addsupltabs( gSuplCols, 'NAGENDA',     'SDOC',     'SDOC.CODAGENDA = I.CODLOCATIE');
  call pkg_list_struct_addsupltabs( gSuplCols, 'NLOCALIT',    'LOCDOC',   'LOCDOC.CODLOCALIT = SDOC.CODLOCALIT');
  call pkg_list_struct_addsupltabs( gSuplCols, 'NTARI',       'TARADOC',  'LOCDOC.CODTARA = TARADOC.CODTARA');
  call pkg_list_struct_addsupltabs( gSuplCols, 'NAGENDA',     'SSOC',     'SSOC.CODPART = NP.CODPART 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');
  call pkg_list_struct_addsupltabs( gSuplCols, 'NTARI',       'TARASOC',  'LOCSOC.CODTARA = TARASOC.CODTARA');
  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');
  call pkg_list_struct_addsupltabs( gSuplCols, 'NTARI',       'TARAPROD', 'LOCPROD.CODTARA = TARAPROD.CODTARA');
  call pkg_list_struct_addsupltabs( gSuplCols, 'BCAR',        'BCAR',     'BCAR.TIPDOC = NIR.TIPNIR AND BCAR.CODDOC1 = I1.CODINTR1');
  call pkg_list_struct_addsupltabs( gSuplCols, 'NPARTTR',     'DEL_BCAR', 'BCAR.CODDELEGAT = DEL_BCAR.CODPARTTR');
  call pkg_list_struct_addsupltabs( gSuplCols, 'BCAREXT',     'BCAREXT',  'BCAREXT.CODBCAR = BCAR.CODBCAR');
  call pkg_list_struct_addsupltabs( gSuplCols, 'CCOST',       'CCOST',    'CCOST.CODCENTRU = coalesce(I1.CODCENTRU,0)');
  call pkg_list_struct_addsupltabs( gSuplCols, 'NPERS',       'OPER',     'OPER.LOGONNAME = I.USERID');
  call pkg_list_struct_addsupltabs( gSuplCols, 'NIRSTOC',     'NS',       'NS.CODNIRSTOC = N.CODNIRSTOC',1);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_NIR.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsertDez := '';
  sSelectDez := '';
  sJoinDez := '';

  IF  vTipDoc = 7 THEN
    sInsertDez := ',BC_NrDoc,BC_DataDoc,DEZ_INCHIS,BC_NrDocIntr,BC_DataDocIntr';
    sSelectDez := ',DEZ.BC_NrDoc, DEZ.BC_DataDoc, case when dez.inchisa = 0 then ''NU'' else ''DA'' end DEZ_INCHIS, DEZ.BC_NrDocIntr, DEZ.BC_DataDocIntr';
    sJoinDez := '
    LEFT JOIN (
      SELECT i.nrdoc BC_NrDoc, i.datadoc BC_DataDoc, coalesce(dz.inchisa,0) inchisa, int.nrdoc BC_NrDocIntr, int.datadoc BC_DataDocIntr, nir.codnir
      FROM nir
        INNER JOIN intrari       intr on nir.codintr     = intr.codintr
        INNER JOIN dezasamblari1 dz1   on dz1.codintrlink = intr.codintr
        LEFT  JOIN dezasamblari  dz   on dz.codlivr1     = dz1.codlivr1
        LEFT  JOIN livr1         l1   on l1.codlivr1     = dz.codlivr1
        LEFT  JOIN livr          l     on l.codlivr       = l1.codlivr
        LEFT  JOIN iesiri1       i1   on i1.codies1      = l1.codies1
        LEFT  JOIN iesiri        i     on i.codies        = l.codies and i.codies = i1.codies
        LEFT  JOIN nirstoc1      ns1   on dz.codnirstoc   = ns1.codnirstoc
        LEFT  JOIN nirstoc       nso   on nso.codnirstoc  = ns1.codnirstocorig
        LEFT  JOIN intrari1      int1 on nso.codintr1    = int1.codintr1
        LEFT  JOIN intrari       int   on int.codintr     = int1.codintr
      WHERE nir.codnir = ' || COALESCE(vCodNir::varchar,'') || '
    ) DEZ on DEZ.codnir = nir.codnir ';
  END IF;

  BEGIN
    SELECT tipnir INTO STRICT aTipNir FROM nir WHERE CODNIR = vCodNir;
  EXCEPTION WHEN others THEN
    aTipNir := 0;
  END;

  DELETE FROM tmp_manevra_liste;
  DELETE FROM nirstoc_man;

  IF  vCodNirStoc &gt; 0 THEN
    INSERT INTO nirstoc_man  SELECT ns.* FROM nirstoc ns  WHERE ns.codnirstoc = vCodNirStoc;
    INSERT INTO intrari1_man SELECT i1.* FROM intrari1 i1 WHERE i1.codintr1 IN (SELECT codintr1 FROM nirstoc_man);
  ELSE
    IF vVerso
    THEN INSERT INTO nirstoc_man SELECT ns.* FROM nirstoc ns WHERE ns.codnir = vCodnir AND  ns.cantfurn &lt;&gt; ns.cantnir;
    ELSE INSERT INTO nirstoc_man SELECT ns.* FROM nirstoc ns WHERE ns.codnir = vCodnir;
    END IF;

    DELETE FROM intrari1_man;
    IF aTipNir = 5 THEN
      INSERT INTO intrari1_man
      SELECT i1.*
      FROM intrari1 i1 INNER JOIN dvi1 ON i1.codintr1 = dvi1.codintr1
      WHERE dvi1.coddvi1 IN (SELECT coddvi1 FROM nirstoc_man);
    ELSE
      INSERT INTO intrari1_man
      SELECT i1.*
      FROM intrari1 i1
      WHERE i1.codintr1 IN (SELECT codintr1 FROM nirstoc_man);
    END IF;
  END IF;

  SELECT
    COALESCE(PKG_LIST_BASE_UTILS_UMA_UTILS.sInsertUMA,''),
    COALESCE(PKG_LIST_BASE_UTILS_UMA_UTILS.sSelectUMA,''),
    COALESCE(PKG_LIST_BASE_UTILS_UMA_UTILS.sJoinUMA,'')
  INTO sInsertUMA, sSelectUMA, sJoinUMA
  FROM PKG_LIST_BASE_UTILS_UMA_UTILS( 'n.cantnir', 'n.codobiect', sInsertUMA, sSelectUMA, sJoinUMA,NULL);

  sINSERT :=
  'INSERT INTO ' || TMPNAME || '(
    DOCUMENT,ORD,DENUMIRE,DENARTPART,SIMBOL,DEN_UM1,CANT,CANTNIR,PU,PRET,PROCADAOS,ADAOSUNITAR,VALOARE,PROCTVA,TVA_UNITAR,TVA_TOTAL,ADAOSTOTAL,
    DEN_GEST,LOCATIE,PROD,PRETMAXIMAL,TIPSERIE,SERII,SERNOCANT,SERCANT,SERTG,TG,CERTIF,DATACERTIF,DATAPROD,DIVIZOR,BUCATI,
    CODEXTERN,CODINTERN,DEN_CLASEA,NRCERTIF,PRETFARATVA,VALFARATVA,
    CANTUM1,DENUM1,CANTUM2,DENUM2,ADAOSSTOC,DATAACHIZ,furnizor,AdaosInvers,valachiz,adaosFurn,adaosmaximal,suplunitar,d1,d2,d3,clasas,TVADED,
    NRCMDFURN, DATACMDFURN, NRCMDINT, DATACMDINT, NRCMDCL, DATACMDCL, PARTCMDCL, PROVIZION, SERIELOT, OPERATOR, EUDR_RN, EUDR_VN '||sInsertDez||sInsertUMA||gUserFields||')
  WITH
  MAN1 AS (
    SELECT
      ns.codnirstoc,
      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''),'''||vSep||''' )  tg,
      string_agg(DISTINCT c.nrcertif,'''                                     ||vSep||''' )  nrcertif,
      string_agg(DISTINCT to_char(c.dataprimire,''dd.mm.yyyy''),'''          ||vSep||''' )  datacertif,
      string_agg(DISTINCT to_char(nser.dataprod,''dd.mm.yyyy''),'''          ||vSep||''' )  dataprod,
      string_agg(DISTINCT nser.divizor::varchar,'''                          ||vSep||''' )  divizor,
      string_agg(DISTINCT nser.bucati::varchar,'''                           ||vSep||''' )  bucati
    FROM   NIRSTOC_MAN NS
      INNER JOIN nirser nser   ON ns.codnirstoc = nser.codnirstoc
      INNER JOIN nserii s     ON s.codserie    = nser.codserie
      LEFT  JOIN certif c     ON c.codcertif    = nser.codcertif
    GROUP BY ns.codnirstoc, ns.tipserie),
  MAN2 AS (
    SELECT
      codnirstoc,
      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 ns.codnirstoc, s.serie, sum(nser.cantnir) cant, coalesce(nser.tg, ns.tg) tg
      FROM   NIRSTOC_MAN NS
        INNER JOIN nirser nser   ON ns.codnirstoc   = nser.codnirstoc
        INNER JOIN nserii s     ON s.codserie     = nser.codserie
        LEFT  JOIN certif c     ON c.codcertif     = nser.codcertif
      WHERE coalesce(ns.tipserie,0) &gt; 0
      GROUP BY ns.codnirstoc, s.serie, coalesce(nser.tg, ns.tg)) A_PG
    GROUP BY codnirstoc),
  N AS (
    SELECT
      NIR.CodNir, Row_Number() OVER (ORDER BY nir.codnir, Coalesce(d1.indexlocal,0), Coalesce(d1.coddvi1,0), Coalesce(i1.indexlocal,0), i1.codintr1, ns.codnirstoc) Ord,
      CASE
        WHEN nir.tipnir BETWEEN 1 AND 9 THEN i.prefixdoc ||''.''||i.nrdoc ||''.''||i.datadoc
        ELSE t.prefixdoc ||''.''||t.nrdoc||''.''||t.datadoc
      END AS document,
      CASE WHEN nir.tipnir BETWEEN 1 AND 5 THEN i.partener ELSE NULL END partener,
      NS.CODNIRSTOC, NS.CANTNIR, NIR.GEST, NS.CODIOART, Coalesce(NS.CODLOCATIE,0) CODLOCATIE, NS.UMSEC, NS.CODOBIECT, NS.TG,
      NS.PRET, NS.ADAOS, NS.CANTFURN,ns.tva tvanir,ns.procentadaos,
      Coalesce(T1.INDEXLOCAL,D1.INDEXLOCAL,I1.INDEXLOCAL) INDEXLOCAL,
      Coalesce(T1.CANT,D1.CANT,I1.CANT) CANT, Coalesce(T1.TVA,D1.TVA,I1.TVA,0) TVA , Coalesce(T1.PU,D1.PRETIMPORT,I1.PU) PU,
      Coalesce(T.AN*12+T.LUNA,I1.AN*12+I1.LUNA,I.AN*12+I.LUNA) AL,
      i1.nrcertif,ns.cantum1,ns.cantum2, Coalesce(i1.dataachizavizsubunit,ns.dataachiz) dataachiz , Coalesce(i1.furnavizsubunit, ns.furn) codfurn, i1.addim,
      ns.pumaximal,CASE Coalesce(ns.cantnir,0) WHEN 0 THEN 0 ELSE ns.supliment/ns.cantnir END suplunitar,
      ns.d1, ns.d2, ns.d3,i1.codintr1,ns.provizion, ns.serielot, ns.eudr_rn, ns.eudr_vn
    FROM NIRSTOC_MAN NS
      INNER JOIN NIR ON NIR.CODNIR = NS.CODNIR
      LEFT JOIN DVI1 D1 ON D1.CODDVI1 = NS.CODDVI1
      LEFT JOIN INTRARI1_MAN I1 ON I1.CODINTR1 = Coalesce(D1.CODINTR1,NS.CODINTR1)
      LEFT JOIN TRANSF1 T1 ON T1.CODTRANSF1 = NS.CODTRANSF1
      LEFT JOIN TRANSF T ON T.CODTRANSF = T1.CODTRANSF
      LEFT JOIN INTRARI I ON NIR.CODINTR = I.CODINTR
  )
  SELECT
    n.document, n.ord, nobj.denumire, ac.denumire, nc.simbol, num1.den_um1,
    n.cantfurn/num1.paritate cant, n.cantnir/num1.paritate cantnir, (n.pret - n.adaos) * num1.paritate PU, n.pret * num1.paritate pret,
    CASE
      WHEN io1.difpret = 1 THEN
        Round(
          CASE
            WHEN io1.aretvaneex = 0 THEN 100*(n.pret-n.pu)                                       /Coalesce(NULLIF(n.pu            ,0),1)
            WHEN io1.aretvaneex = 1 THEN 100*(n.pret/(1+(ntva1.procent/100))-(n.pret - n.adaos)) /Coalesce(NULLIF(n.pret - n.adaos,0),1)
            WHEN io1.aretvaneex = 2 THEN 100*((n.pret-(n.pret-n.pu)/(1+ntva1.procent/100) )-n.pu)/Coalesce(NULLIF(n.pu            ,0),1)
          END,2)
      ELSE 0
    END procadaos,
    CASE WHEN io1.aretvaneex = 1 THEN  n.adaos -((n.pret*ntva1.procent)/Coalesce(NULLIF(100+ntva1.procent,0),1)) ELSE n.adaos END * num1.paritate adaosunitar,
    n.pret * n.cantnir valoare, ntva1.procent procTVA,
    CASE WHEN io1.aretvaneex = 1 THEN (n.pret*ntva1.procent)/(100+ntva1.procent) ELSE 0 END * num1.paritate tva_unitar,
    CASE WHEN io1.aretvaneex = 1 THEN (n.pret*ntva1.procent)*n.cantnir/(100+ntva1.procent) ELSE 0 END tva_total,
    CASE WHEN io1.aretvaneex = 1 THEN (n.adaos -((n.pret*ntva1.procent)/(100+ntva1.procent))) * n.cantnir ELSE n.adaos * n.cantnir END adaostotal,
    ng.den_gest, nl.denumire locatie, prod.den_part prod, n.pumaximal * num1.paritate 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, coalesce(MAN1.TG,to_char(N.TG,''dd.mm.yyyy'')), MAN1.NRCERTIF, MAN1.DATACERTIF, MAN1.DATAPROD, MAN1.DIVIZOR, MAN1.BUCATI,
    nobj.codextern,nobj.codintern,nca.den_clasea,n.nrcertif,
    (n.pret - CASE WHEN io1.aretvaneex = 1 THEN (n.pret*ntva1.procent)/(100+ntva1.procent) ELSE 0 END) * num1.paritate pretfaratva,
    (n.pret * n.cantnir - CASE WHEN io1.aretvaneex = 1 THEN (n.pret*ntva1.procent)*n.cantnir/(100+ntva1.procent) ELSE 0 END) valfaratva,
    n.cantum1 CANTUM1, um1.den_um denum1, n.cantum2 CANTUM2, um2.den_um denum2, n.procentadaos adaosstoc, n.dataachiz, furn.Den_Part,
    ((((n.pret - n.adaos)/( (case when coalesce(n.pret,0)=0 then 1 else n.pret end) - CASE WHEN io1.aretvaneex = 1 THEN (n.pret*ntva1.procent)/(100+ntva1.procent) ELSE 0 END ) ) - 1 ) * 100 )  AdaosInvers,
    ((n.pret - n.adaos)) * n.cantnir valachiz,
    CASE
      WHEN coalesce(n.pret,0) = 0 THEN 1
      ELSE 1-(n.pret - n.adaos)/(n.pret - CASE WHEN io1.aretvaneex = 1 THEN (n.pret*ntva1.procent)/(100+ntva1.procent) ELSE 0 END)
    END*100 AdaosFurn,
    CASE
      WHEN coalesce(n.pret,0) = 0 THEN 1
      ELSE n.pumaximal /(1+ntva1.procent/100)/(n.pret - CASE WHEN io1.aretvaneex = 1 THEN (n.pret*ntva1.procent)/(100+ntva1.procent) ELSE 0 END)-1
    END*100 adaosmaximal,
    n.suplunitar, n.d1, n.d2,n.d3,NCLS.DEN_CLASEAS,N.TVA,
    CF.NRDOC, CF.DATADOC, CINT.NRDOC, CINT.DATADOC, CCL.NRDOC, CCL.DATADOC, PARTCMDCL.DEN_PART,n.provizion, n.serielot, UT.USERNAME, N.eudr_rn, N.eudr_vn '||sSelectDez||sSelectUMA||gUserAlias||'
  FROM N
    INNER JOIN nir            nir       ON n.codnir = nir.codnir
    INNER JOIN ngest          ng        ON ng.codgest = n.gest
    INNER JOIN ioart1         io1       ON io1.codioart = n.codioart          AND n.al BETWEEN io1.ALStart   AND io1.ALStop
    INNER JOIN ncont          nc        ON nc.codcont = io1.cont
    INNER JOIN nlocatii       nl        ON nl.codlocatie = n.codlocatie
    INNER JOIN num1           num1      ON num1.codum1 = n.umsec
    INNER JOIN nartobj        nobj      ON nobj.codobiect = n.codobiect
    INNER JOIN nart           nart      ON nart.codarticol = nobj.codarticol
    INNER JOIN nart1          nart1     ON nart1.codarticol = nobj.codarticol AND n.al BETWEEN nart1.ALStart AND nart1.ALStop
    INNER JOIN ntva1          ntva1     ON ntva1.codtva = nart1.codtva        AND n.al BETWEEN ntva1.ALStart AND ntva1.ALStop
    INNER JOIN nartobj1       nobj1     ON nobj1.codobiect = nobj.codobiect   AND n.al BETWEEN nobj1.ALStart AND nobj1.ALStop
    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 npart          prod      ON prod.codpart = Coalesce(nobj.codproducator,0)
    LEFT  JOIN npart          furn      ON furn.codpart = Coalesce(n.codfurn,0)
    LEFT  JOIN intrari1       i1        ON i1.codintr1 = n.codintr1
    LEFT  JOIN intrari        i         ON i.codintr = i1.codintr
    LEFT  JOIN tmp_utilizator ut        ON ut.codutilizator = i.userid
    LEFT  JOIN nclaseas       ncls      ON ncls.codclaseas = nart.clasastatist
    LEFT  JOIN man1           man1      ON man1.codnirstoc = n.codnirstoc
    LEFT  JOIN man2           man2      ON man2.codnirstoc = n.codnirstoc
    LEFT  JOIN intrprodlink   iprodlink ON iprodlink.codintr1 = n.codintr1
    LEFT  JOIN intrlink       il        ON il.codintr1 = n.codintr1
    LEFT  JOIN comanda1       cf1       ON cf1.codcomanda1 = Coalesce(i1.codcmd1ae,il.codliniecomanda)
    LEFT  JOIN comanda        cf        ON cf.codcomanda = cf1.codcomanda
    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 = n.partener
    LEFT  JOIN nartcli        ac        ON ac.codobiect = n.codobiect AND ac.codpart = n.partener '||
    sJoinDez ||
    sJoinUMA ||
    gSuplJoins || '
  ORDER BY n.indexlocal ';
  PERFORM LIST_EXECUTE_IMMEDIATE( sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nompart_setparams</obj_name>
  <obj_hashval>5a181771f86efa7620c245211021836d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nompart_setparams(aallpart numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  perform set_config('PKG_LIST_BASE_NOMPART.vAllPart', aallpart::varchar, false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nompers_processlist</obj_name>
  <obj_hashval>6af56cc88f3a0bfa5c591bfb973dfe06</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nompers_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 := '';
  vAnLunaLucru numeric := GetANLUCRU() * 12 + GetLUNALUCRU();
BEGIN
  --Florin 20.07.2022 - sinc. Oracle
  --Adina 05.05.2021 - alstart,alstop
  --Adina 18.01.2021 - optimizare + aranjat. Atentie: param. vPerDataPlanif = 1 indiferent daca pun sau nu bifa!!!!!!!!! (- vine din delphi)
  CALL PRC_AL_CHECK('npers1',0);

  IF current_setting('PKG_LIST_BASE_NOMPERS.vGDPR', true)::numeric &gt; 0 THEN
    gSuplCols:='NPERS P, NPERS1 P1, NAGENDA NAG, NLOCALIT LOC, NJUDET JUD, NTARI T, NLOCALIT LOCAG, NSUBUNIT SUB, NGEST G';

    IF current_setting('PKG_LIST_BASE_NOMPERS.vDetaliere', true)::numeric = 1 THEN
      gSuplCols:= gSuplCols||',NPERSCURS CV,CURSURI CS,TEME TM';
    END IF;
  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_NOMPERS.gSuplCols', gSuplCols, false);

  DELETE FROM tmp_nperscurs;
  DELETE FROM tmp_nperscurs0;

  IF current_setting('PKG_LIST_BASE_NOMPERS.vDetaliere', true)::numeric = 1 THEN
    INSERT INTO TMP_NPERSCURS0(CODPERS, NUME, PRENUME, FORMATIE, FUNCTIE, MESERIE, SCHIMB, DataPlecarii, Plecat, ACTIV, selectat)
    SELECT CODPERS, NUME, PRENUME, FORMATIE, FUNCTIE, MESERIE, SCHIMB, DataPlecarii,
           CASE WHEN  LuniRamase &lt; 0 THEN 1 ELSE 0 END, ACTIV, 1
    FROM (
          SELECT P.CodPers, P.Nume, P.Prenume, C.Den_Formatie FORMATIE, F.DENUMIRE FUNCTIE, M.DEN_MESERIE MESERIE, P1.Schimb, p.DataPlecarii,
                 Extract( YEAR FROM COALESCE(DataPlecarii, CURRENT_TIMESTAMP)) * 12 + Extract( MONTH FROM COALESCE(DataPlecarii, CURRENT_TIMESTAMP)) - GETANLUNALUCRU() LUNIRAMASE,
                 COALESCE(p.ACTIV, 1) ACTIV
          FROM NPers P
               INNER JOIN NPERS1  P1 ON  P1.CodPers    = P.CodPers AND vAnLunaLucru BETWEEN P1.ALStart AND P1.ALStop
               LEFT JOIN Formatii C  ON  C.CodFormatie = P1.CodFormatie
               LEFT JOIN Functii  F  ON  F.CodFunctie  = P1.CodFunctie
               LEFT JOIN NMESERII M  ON  M.CodMeserie  = P1.CodMeserie
          WHERE ((COALESCE(p.ACTIV, 1) = 1)  or (p.ACTIV = 0 and Extract( YEAR FROM DataPlecarii) * 12 + Extract( MONTH FROM DataPlecarii) &gt;= getanlunalucru()))
                and (EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE filtru = 'CODPERS' AND valoare = P.CODPERS::varchar)
                     OR current_setting('PKG_LIST_BASE_NOMPERS.vAllPers', true)::numeric = 1)
      ) A_PG WHERE LuniRamase &gt;= -1;

    INSERT INTO TMP_NPERSCURS(CODNPERSCURS, CODPERS, CODFUNCTIE, CODCURS, CODTEMA, STARE, DATA, NOTA, DATAPLAN, ORE_REALIZ, SUPLIM, DEN_CURS,
                              DEN_TEMA, SSTARE, ORE_AFER, Nume, Prenume, Activ, DataPlecarii, Plecat, TipFormare, NivelFormare, CodObiectiv, Den_Obiectiv, Sel
                             )
    WITH
    CF AS (
            SELECT  DISTINCT P1.CodPers, F1.CodCurs, F1.CodTema, x.Activ, x.DataPlecarii, x.Plecat, 0 SUPLIM
            FROM NPERS1 P1
                 INNER JOIN FUNCTII1 F1 ON  F1.CodFunctie = P1.Codfunctie
                 INNER JOIN (SELECT CodPers, Activ, DataPlecarii, Plecat FROM TMP_NPERSCURS0) X ON  X.CodPers = P1.CodPers
          ),
    PC AS (
            SELECT NP.CodPers, NP.CODNPERSCURS, COALESCE(NP.codfunctie, 0) CODFUNCTIE, NP.CodCurs, NP.CodTema, COALESCE(NP.STARE, 0) STARE,
                   CASE WHEN  COALESCE(NP.codfunctie, 0) = 0 THEN 1 ELSE 0 END  SUPLIM,
                   NP.Nota, NP.Data, NP.DataPlan, NP.TipFormare, NP.NivelFormare, NP.CodObiectiv, NP.ORE_REALIZ, x.Activ, x.DataPlecarii, x.Plecat
            FROM NPERSCURS NP
                 INNER JOIN (SELECT CodPers, Activ, DataPlecarii, Plecat FROM TMP_NPERSCURS0 WHERE Selectat = 1) X ON  X.CodPers = NP.CodPers
          )
    SELECT TMP.CODNPERSCURS, TMP.CODPERS, TMP.CodFunctie, TMP.CODCURS, TMP.CODTEMA, TMP.STARE, TMP.DATA, TMP.NOTA, TMP.DATAPLAN, TMP.ORE_REALIZ, TMP.Suplim, CC.DEN_CURS, TT.DEN_TEMA, 'xxxxxxxxxx', TT.ORE, P.Nume, P.Prenume, TMP.Activ, TMP.DataPlecarii, TMP.Plecat, TMP.TipFormare, TMP.NivelFormare, TMP.CodObiectiv, O.Den_Obiectiv, 0 SEL
    FROM (
          SELECT PC.CODNPERSCURS, PC.CodPers, COALESCE(PC.CodFunctie, 0) CODFUNCTIE, PC.CodCurs, PC.CodTema, PC.DATA, PC.DATAPLAN, PC.ORE_REALIZ,
                 COALESCE(PC.STARE, 0) STARE, PC.Nota, PC.Activ, PC.DataPlecarii, PC.Plecat, PC.Suplim, COALESCE(PC.TipFormare, 0) TIPFORMARE,
                 COALESCE(PC.NivelFormare, 0) NIVELFORMARE, COALESCE(PC.CodObiectiv, 0) CODOBIECTIV
          FROM PC
          union all
          SELECT -ROW_NUMBER () OVER (ORDER BY CF.CODPERS) CODNPERSCURS, CF.CODPERS, -1 CODFUNCTIE, COALESCE(CF.CodCurs, 0) CODCURS,
                 COALESCE(CF.CodTema, 0) CODTEMA, null AS DATA, null DATAPLAN, 0 ORE_REALIZ, 0 STARE, null NOTA, CF.Activ, CF.DataPlecarii,
                 CF.Plecat, 0 SUPLIM, 0 TIPFORMARE, 0 NIVELFORMARE, 0 CODOBIECTIV
          FROM CF
          WHERE NOT EXISTS (SELECT CodNPERSCURS FROM NPERSCURS
                            WHERE COALESCE(CodFunctie, 0) &lt;&gt; 0 and  CodCurs = CF.CodCurs and  CodTema = CF.CodTema and  Codpers = CF.CodPers)
         ) TMP
            INNER JOIN Npers    P  ON  P.Codpers     = TMP.CodPers
            LEFT JOIN CURSURI   CC ON  CC.CodCurs    = TMP.CodCurs
            LEFT JOIN TEME      TT ON  TT.CodTema    = TMP.CodTEMA
            LEFT JOIN OBIECTIVE O  ON  O.CodObiectiv = TMP.CodObiectiv
            WHERE
            (EXISTS(SELECT valoare FROM tmp_manevra_liste
              WHERE filtru = 'CODPERS' AND  valoare = P.CODPERS::varchar) OR current_setting('PKG_LIST_BASE_NOMPERS.vAllPers', true)::numeric = 1);

    IF  current_setting('PKG_LIST_BASE_NOMPERS.vAllCursuri', true)::numeric + current_setting('PKG_LIST_BASE_NOMPERS.vAllTeme', true)::numeric = 2 THEN
      sInsert := 'INSERT INTO ' || tmpName || '(
        MARCA, NUME, PRENUME, CNP, BISERIA, BINR, LOCNASTERE, ADRESA, PRENUMET, PRENUMEM, DATAN,
        SCIVILA,
        STRAINATATE,
        AGENT,
        DELEGAT,
        A_LOCALITATE,
        A_ADRESA, A_TELEFON, A_EMAIL,
        BIELIBERATDE, LADATADE, TARAN,
        CETATENIE,
        Den_IOPers,
        Formatie,
        Functie,
        Den_meserie,
        Schimb,
        Den_curs,
        Den_tema,
        Stare,
        Nota,
        DEN_OBIECTIV,
        STIPFORMARE,
        SNIVELFORMARE, AnPlanif, LunaPlanif, An, Luna ' || gUserFields || ')
      SELECT
        P.MARCA, P.NUME, P.PRENUME, P.CNP, P.BISERIA, P.BINR, LOC.DEN_LOCALIT, P.ADRESA, P.PRENUMET, P.PRENUMEM, PKG_NOMPERS_GETDATAN(P.CNP),
       (Case  When P.SCIVILA=-1 then ''CASATORIT'' else ''NECASATORIT'' end) SCivila,
        CASE WHEN P.STRAINATATE = 1 THEN ''DA'' ELSE ''NU'' END,
        CASE WHEN P.AGENT = 1 THEN ''DA'' ELSE ''NU'' END,
        CASE WHEN P.DELEGAT = 1 THEN ''DA'' ELSE ''NU'' END,
        LOCAG.DEN_LOCALIT, (select getadresa.wme_result from getadresa('''',NAG.SECTOR,NAG.STRADA,NAG.NR1,NAG.NR2,NAG.BLOC,NAG.SCARA,NAG.ETAJ,NAG.APART,NAG.CODPOSTAL)) Adresa, NAG.TELEFON, NAG.EMAIL,
        P.BIELIBERATDE, P.LADATADE, T.DEN_TARA,
        (Case  When P.CETATENIE=0 then ''Stat Extra Comunitar (non UE)'' When P.CETATENIE=1 then ''Stat Comunitar (UE)'' When P.CETATENIE=-1 then ''Romana'' end) Cetatenie,
        IO.Den_IOPers, F.DEN_FORMATIE, FT.DENUMIRE, M.DEN_MESERIE, P1.SCHIMB, CS.DEN_CURS, TM.DEN_TEMA,
        CASE WHEN COALESCE(CV.STARE,0) = 0 THEN ''?''
             WHEN COALESCE(CV.STARE,0) = 1 THEN ''Planificat''
             WHEN COALESCE(CV.STARE,0) = 2 THEN ''Suspendat''
             WHEN COALESCE(CV.STARE,0) = 9 THEN ''Efectuat''
        END,
        CV.NOTA,
        OBIECTIVE.DEN_OBIECTIV,
        CASE CV.TIPFORMARE
          WHEN 1 THEN ''Ex-cunostintele exista''
          WHEN 2 THEN ''Ie-instruit extern''
          WHEN 3 THEN ''Ii-instruit intern''
          WHEN 4 THEN ''Si-studiu individual''
        END,
        CASE CV.NIVELFORMARE
          WHEN 0 THEN ''Ou-bligatoriu si urgent''
          WHEN 1 THEN ''O-obligatoriu''
          WHEN 2 THEN ''U-Util''
        END,
        extract(year from CV.DataPlan),
        extract(month from CV.DataPlan),
        extract(year from CV.Data),
        extract(month from CV.Data)' || gUserAlias || '
      FROM NPERS P
        LEFT JOIN (SELECT CVV.*
                    FROM TMP_NPERSCURS CVV
                    WHERE (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODTEMA'' AND valoare = CVV.CODTEMA::varchar) OR
                           current_setting(''PKG_LIST_BASE_NOMPERS.vAllTeme'', true)::numeric = 1
                          )
                          AND
                          (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODCURS'' AND valoare = CVV.CODCURS::varchar) OR
                           current_setting(''PKG_LIST_BASE_NOMPERS.vAllCursuri'', true)::numeric = 1
                          )
                  )        CV    ON CV.CODPERS     = P.CODPERS
        LEFT JOIN NPERS1   P1    ON P.CODPERS      = P1.CODPERS AND '||COALESCE(vAnLunaLucru::varchar,'0')||' BETWEEN P1.ALStart and P1.ALStop
        LEFT JOIN NAGENDA  NAG   ON NAG.CODAGENDA  = P.AGENDA
        LEFT JOIN NLOCALIT LOC   ON P.LOCNASTERE   = LOC.CODLOCALIT
        LEFT JOIN NJUDET   JUD   ON LOC.CODJUDET   = JUD.CODJUDET
        LEFT JOIN NTARI    T     ON P.TARAN        = T.CODTARA
        LEFT JOIN NLOCALIT LOCAG ON NAG.CODLOCALIT = LOCAG.CODLOCALIT
        LEFT JOIN IOPERS   IO    ON P1.CODIOPERS   = IO.CODIOPERS
        LEFT JOIN FORMATII F     ON P1.CODFORMATIE = F.CODFORMATIE
        LEFT JOIN FUNCTII  FT    ON P1.CODFUNCTIE  = FT.CODFUNCTIE
        LEFT JOIN NMESERII M     ON P1.CODMESERIE  = M.CODMESERIE
        LEFT JOIN OBIECTIVE      ON OBIECTIVE.CODOBIECTIV = CV.CODOBIECTIV
        LEFT JOIN CURSURI  CS    ON CS.CODCURS     = CV.CODCURS
        LEFT JOIN TEME     TM    ON TM.CODTEMA     = CV.CODTEMA
        LEFT JOIN NSUBUNIT SUB   ON SUB.CODSUBUNIT = P.CODSUBUNIT
        LEFT JOIN NGEST    G     ON P.CODGEST      = G.CODGEST
        LEFT JOIN (
                    SELECT sold.CODPERS , SUM(sold.soldlei) soldlei
                    FROM nperssoldluna sold
                    WHERE sold.luna = GetLUNALUCRU() AND sold.an = GetANLUCRU()
                    GROUP BY sold.codpers
                  ) NPS ON P.CODPERS = NPS.CODPERS' || gSuplJoins || '
      WHERE P.CODPERS &gt; 0
            AND (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODPERS'' AND valoare = P.CODPERS::varchar) OR
                 current_setting(''PKG_LIST_BASE_NOMPERS.vAllPers'', true)::numeric = 1) ';
    ELSE
      sInsert := 'INSERT INTO ' || tmpName || '(
        MARCA, NUME, PRENUME, CNP, BISERIA, BINR, LOCNASTERE, ADRESA, PRENUMET, PRENUMEM, DATAN,
        SCIVILA,
        STRAINATATE,
        AGENT,
        DELEGAT,
        A_LOCALITATE,
        A_ADRESA, A_TELEFON, A_EMAIL,
        BIELIBERATDE, LADATADE, TARAN,
        CETATENIE,
        Den_IOPers,
        Formatie,
        Functie,
        Den_meserie,
        Schimb,
        Den_curs,
        Den_tema,
        Stare,
        Nota,
        DEN_OBIECTIV,
        STIPFORMARE,
        SNIVELFORMARE, AnPlanif, LunaPlanif, An, Luna ' || gUserFields || ')
      SELECT
        P.MARCA, P.NUME, P.PRENUME, P.CNP, P.BISERIA, P.BINR, LOC.DEN_LOCALIT, P.ADRESA, P.PRENUMET, P.PRENUMEM, PKG_NOMPERS_GETDATAN(P.CNP),
        (Case  When P.SCIVILA=-1 then ''CASATORIT'' else ''NECASATORIT'' end) SCivila,
        CASE WHEN P.STRAINATATE = 1 THEN ''DA'' ELSE ''NU'' END,
        CASE WHEN P.AGENT = 1 THEN ''DA'' ELSE ''NU'' END,
        CASE WHEN P.DELEGAT = 1 THEN ''DA'' ELSE ''NU'' END,
        LOCAG.DEN_LOCALIT, (select getadresa.wme_result from getadresa('''',NAG.SECTOR,NAG.STRADA,NAG.NR1,NAG.NR2,NAG.BLOC,NAG.SCARA,NAG.ETAJ,NAG.APART,NAG.CODPOSTAL)) Adresa, NAG.TELEFON, NAG.EMAIL,
        P.BIELIBERATDE, P.LADATADE, T.DEN_TARA,
        (Case  When P.CETATENIE=0 then ''Stat Extra Comunitar (non UE)'' When P.CETATENIE=1 then ''Stat Comunitar (UE)'' When P.CETATENIE=-1 then ''Romana'' end) Cetatenie,
        IO.Den_IOPers, F.DEN_FORMATIE, FT.DENUMIRE, M.DEN_MESERIE, P1.SCHIMB, CS.DEN_CURS, TM.DEN_TEMA,
        CASE WHEN COALESCE(CV.STARE,0) = 0 THEN ''?''
             WHEN COALESCE(CV.STARE,0) = 1 THEN ''Planificat''
             WHEN COALESCE(CV.STARE,0) = 2 THEN ''Suspendat''
             WHEN COALESCE(CV.STARE,0) = 9 THEN ''Efectuat''
        END,
        CV.NOTA,
        OBIECTIVE.DEN_OBIECTIV,
        CASE CV.TIPFORMARE
          WHEN 1 THEN ''Ex-cunostintele exista''
          WHEN 2 THEN ''Ie-instruit extern''
          WHEN 3 THEN ''Ii-instruit intern''
          WHEN 4 THEN ''Si-studiu individual''
        END,
        CASE CV.NIVELFORMARE
          WHEN 0 THEN ''Ou-bligatoriu si urgent''
          WHEN 1 THEN ''O-obligatoriu''
          WHEN 2 THEN ''U-Util''
        END,
        extract(year from CV.DataPlan),
        extract(month from CV.DataPlan),
        extract(year from CV.Data),
        extract(month from CV.Data)' || gUserAlias || '
      FROM NPERS P
        INNER JOIN (SELECT CVV.*
                    FROM TMP_NPERSCURS CVV
                    WHERE (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODTEMA'' AND valoare = CVV.CODTEMA::varchar) OR
                           current_setting(''PKG_LIST_BASE_NOMPERS.vAllTeme'', true)::numeric = 1
                          )
                          AND
                          (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODCURS'' AND valoare = CVV.CODCURS::varchar) OR
                           current_setting(''PKG_LIST_BASE_NOMPERS.vAllCursuri'', true)::numeric = 1)
                   ) CV          ON CV.CODPERS     = P.CODPERS
        LEFT JOIN NPERS1   P1    ON P.CODPERS      = P1.CODPERS AND '||COALESCE(vAnLunaLucru::varchar,'0')||' BETWEEN P1.ALStart and P1.ALStop
        LEFT JOIN NAGENDA  NAG   ON NAG.CODAGENDA  = P.AGENDA
        LEFT JOIN NLOCALIT LOC   ON P.LOCNASTERE   = LOC.CODLOCALIT
        LEFT JOIN NJUDET   JUD   ON LOC.CODJUDET   = JUD.CODJUDET
        LEFT JOIN NTARI    T     ON P.TARAN        = T.CODTARA
        LEFT JOIN NLOCALIT LOCAG ON NAG.CODLOCALIT = LOCAG.CODLOCALIT
        LEFT JOIN IOPERS   IO    ON P1.CODIOPERS   = IO.CODIOPERS
        LEFT JOIN FORMATII F     ON P1.CODFORMATIE = F.CODFORMATIE
        LEFT JOIN FUNCTII  FT    ON P1.CODFUNCTIE  = FT.CODFUNCTIE
        LEFT JOIN NMESERII M     ON P1.CODMESERIE  = M.CODMESERIE
        LEFT JOIN OBIECTIVE      ON OBIECTIVE.CODOBIECTIV = CV.CODOBIECTIV
        LEFT JOIN CURSURI  CS    ON CS.CODCURS     = CV.CODCURS
        LEFT JOIN TEME     TM    ON TM.CODTEMA     = CV.CODTEMA
        LEFT JOIN NSUBUNIT SUB   ON SUB.CODSUBUNIT = P.CODSUBUNIT
        LEFT JOIN NGEST    G     ON P.CODGEST      = G.CODGEST
        LEFT JOIN (
                    SELECT sold.CODPERS , SUM(sold.soldlei) soldlei
                    FROM nperssoldluna sold
                    WHERE sold.luna = getlunalucru() AND sold.an = getanlucru()
                    GROUP BY sold.codpers
                  ) NPS ON P.CODPERS = NPS.CODPERS' || gSuplJoins || '
      WHERE P.CODPERS &gt; 0
            AND (EXISTS (SELECT valoare FROM tmp_manevra_liste tmp WHERE filtru = ''CODPERS'' AND valoare = P.CODPERS::varchar) OR
                 current_setting(''PKG_LIST_BASE_NOMPERS.vAllPers'', true)::numeric = 1) ';
    END IF;

    IF  current_setting('PKG_LIST_BASE_NOMPERS.vPerDataPlanif', true)::numeric = 1 THEN
      sInsert := coalesce(sInsert,'') || '
        AND CV.DATAPLAN BETWEEN TO_DATE(''' || CURRENT_SETTING('PKG_LIST_BASE_NOMPERS.vDataIni',true)::varchar || ''', ''DD.MM.YYYY'')
                            AND TO_DATE(''' || CURRENT_SETTING('PKG_LIST_BASE_NOMPERS.vDataFin',true)::varchar || ''', ''DD.MM.YYYY'') ';
    END IF;
  ELSE
    sInsert := 'INSERT INTO ' || tmpName || '(
      MARCA, NUME, PRENUME, CNP, BISERIA, BINR, LOCNASTERE, ADRESA, PRENUMET, PRENUMEM, DATAN,
      SCIVILA,
      STRAINATATE,
      AGENT,
      DELEGAT,
      A_LOCALITATE,
      A_ADRESA, A_TELEFON, A_EMAIL,
      BIELIBERATDE, LADATADE, TARAN,
      CETATENIE,
      Den_IOPers,
      Formatie,
      Functie,
      Den_meserie,
      Schimb ' || gUserFields || ')
    SELECT
      P.MARCA, P.NUME, P.PRENUME, P.CNP, P.BISERIA, P.BINR, LOC.DEN_LOCALIT, P.ADRESA, P.PRENUMET, P.PRENUMEM, PKG_NOMPERS_GETDATAN(P.CNP),
      (Case  When P.SCIVILA=-1 then ''CASATORIT'' else ''NECASATORIT'' end) SCivila,
      CASE WHEN P.STRAINATATE = 1 THEN ''DA'' ELSE ''NU'' END,
      CASE WHEN P.AGENT = 1 THEN ''DA'' ELSE ''NU'' END,
      CASE WHEN P.DELEGAT = 1 THEN ''DA'' ELSE ''NU'' END,
      LOCAG.DEN_LOCALIT, (select getadresa.wme_result from getadresa('''',NAG.SECTOR,NAG.STRADA,NAG.NR1,NAG.NR2,NAG.BLOC,NAG.SCARA,NAG.ETAJ,NAG.APART,NAG.CODPOSTAL)) Adresa, NAG.TELEFON, NAG.EMAIL,
      P.BIELIBERATDE, P.LADATADE, T.DEN_TARA,
      (Case  When P.CETATENIE=0 then ''Stat Extra Comunitar (non UE)'' When P.CETATENIE=1 then ''Stat Comunitar (UE)'' When P.CETATENIE=-1 then ''Romana'' end) Cetatenie,
      IO.Den_IOPers, F.DEN_FORMATIE, FT.DENUMIRE, M.DEN_MESERIE, P1.SCHIMB ' || gUserAlias || '
    FROM NPERS P
      LEFT JOIN NPERS1   P1    ON P.CODPERS      = P1.CODPERS AND '||COALESCE(vAnLunaLucru::varchar,'0')||' BETWEEN P1.ALStart and P1.ALStop
      LEFT JOIN NAGENDA  NAG   ON NAG.CODAGENDA  = P.AGENDA
      LEFT JOIN NLOCALIT LOC   ON P.LOCNASTERE   = LOC.CODLOCALIT
      LEFT JOIN NJUDET   JUD   ON LOC.CODJUDET   = JUD.CODJUDET
      LEFT JOIN NTARI    T     ON P.TARAN        = T.CODTARA
      LEFT JOIN NLOCALIT LOCAG ON NAG.CODLOCALIT = LOCAG.CODLOCALIT
      LEFT JOIN IOPERS   IO    ON P1.CODIOPERS   = IO.CODIOPERS
      LEFT JOIN FORMATII F     ON P1.CODFORMATIE = F.CODFORMATIE
      LEFT JOIN FUNCTII  FT    ON P1.CODFUNCTIE  = FT.CODFUNCTIE
      LEFT JOIN NMESERII M     ON P1.CODMESERIE  = M.CODMESERIE
      LEFT JOIN NSUBUNIT SUB   ON SUB.CODSUBUNIT = P.CODSUBUNIT
      LEFT JOIN NGEST    G     ON P.CODGEST      = G.CODGEST
      LEFT JOIN (
                  SELECT sold.CODPERS , SUM(sold.soldlei) soldlei
                  FROM nperssoldluna sold
                  WHERE sold.luna = GetLUNALUCRU() AND sold.an = GetANLUCRU()
                  GROUP BY sold.codpers
                ) NPS ON P.CODPERS = NPS.CODPERS' || gSuplJoins || '
    WHERE P.CODPERS &gt; 0 ';
  END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  IF  current_setting('PKG_LIST_BASE_NOMPERS.vGDPR', true)::numeric = 0 THEN
    sInsert := 'update ' || tmpName || ' set
                  CNP          = ''***'',
                  BISERIA      = ''***'',
                  BINR         = ''***'',
                  BIELIBERATDE = ''***'',
                  LADATADE     = NULL,
                  LOCNASTERE   = ''***'',
                  SCIVILA      = ''***'',
                  A_EMAIL      = ''***'',
                  A_TELEFON    = ''***'',
                  CETATENIE    = ''***'',
                  TARAN        = ''***''
                   ';
    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_notacont_gsupljoins</obj_name>
  <obj_hashval>ffd50266fbaabdf283650c023f422b93</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notacont_gsupljoins(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_NOTACONT.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_oportunitati_processlist</obj_name>
  <obj_hashval>cc99fea832429a6d6d3b9921a525d872</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_oportunitati_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
  --Adina 06.05.2021 - sinc.Oracle din 06.05.2021
  --Adina 28.04.2021 - sinc.Oracle din 27.04.2021
  --Adina 13.03.2021 - sinc.Oracle din 12.03.2021
  --Adina 04.02.2021 - alte modif.Oracle din 03.02.2021 (add OBS)
  --Adina 03.02.2021 - modif.Oracle din 03.02.2021
  --Bogdan 15.09.2020
  gSuplCols := 'OPORTUNITATI O, NPART P, NPARTCODFISC F, NAGENDA A, NLOCALIT L, DOMENIIACT DA, NMONEDE M, NPERSCONTACT PC, OPORTUNITATI1 O1, CAMPANII C, NPARTTR DEL';

  DELETE FROM TMP_LST_PART1CRM;
  PERFORM pkg_list_base_oportunitati_umpletmplista();

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

  sInsert := 'INSERT INTO ' || TMPNAME || '(
          NAV_CODDOC,NAV_TIPDOC,
          PrefixDoc,
          NrDoc,
          DataDoc,
          DenCampanie,
          Den_Part,
          CodFiscal,
          Den_Localit,
          CifraAfaceri,
          NrAngajati,
          DenDomeniuAct,
          Den_Moneda,
          NumePersC,
          TelefonC,
          EMailC,
          DataSemnare,
          VenitEst,
          VenitProb,
          ProbVanz,
          TipOportunitate,
          Stadiu,
          Potential,
          IndexLocal,
          Delegat,
          Info,
          DataC, Obs ' || coalesce (gUserFields ,'') || ')
        ';

  sSelect := '
      SELECT O.CODOPORTUNITATE, 82, coalesce(O.PrefixDoc,''OP''),
        O.NrDoc,
        O.DataDoc,
        C.DenCampanie,
        P.Den_Part,
        F.CodFiscal,
        L.Den_Localit,
        PP.CifraAfaceri,
        PP.NrAngajati,
        PP.DenDomeniuAct,
        M.Den_Moneda,
        PC.Prenume || '' '' || PC.Nume NumePersC,
        PC.Telefon     TelefonC,
        PC.EMail       EMailC,
        O.DataSemnare,
        O.VenitEst,
        O.VenitProb,
        O.ProbVanz,
        (case O.Tip
            when 0 then ''Vanzare directa''
            when 1 then ''Servicii''
            when 2 then ''prin parteneri''
            else '' - '' end) TipOportunitate,
        (case O1.Stadiu
            when 1 then ''1.Prezentare''
            when 2 then ''2.Ofertare''
            when 3 then ''3.Negociere''
            when 4 then ''4.Vanzare''
            when 0 then ''5.Pierdut''
            when 7 then ''7.Vizita''
         end) Stadiu,
        (case O1.Stadiu
            when  -1 then ''Zero''
            when  0 then ''Fara potential''
            when  1 then ''Scazut''
            when  2 then ''Mediu''
            when  3 then ''Ridicat''
            when  4 then ''Foarte ridicat'' end) Potential,
        O1.IndexLocal,
        DEl.nume ||'' '' ||del.prenume,
        O1.Info,
        O1.DataC, O.Obs ' || coalesce (gUserAlias ,'') || '
      FROM OPORTUNITATI         O
        LEFT JOIN V_NPART       PP  ON PP.CodPart         = O.CodPartener
        LEFT JOIN NPART         P   ON PP.CODPART         = P.CODPART              --P.CodPart = O.CodPartener
        LEFT JOIN NPARTCODFISC  F   ON F.CODPART          = P.CODPART AND F.PRINCIPAL = 1
        LEFT JOIN NAGENDA       A   ON A.CODPART          = P.CODPART AND coalesce (A.Inactiv,0) = 0 AND (BITAND (A.SEDIUSOCIAL, 4) &lt;&gt; 0)
        LEFT JOIN NLOCALIT      L   ON L.CODLOCALIT       = A.CODLOCALIT
          --LEFT JOIN DOMENIIACT    DA  ON DA.CodDomeniuAct = P.CodDomeniuAct
        LEFT JOIN NMONEDE       M   ON M.CodMoneda        = O.CodMoneda
        LEFT JOIN NPERSCONTACT  PC  ON PC.CodPersC        = O.CodAgent
        LEFT JOIN OPORTUNITATI1 O1  ON O1.CodOportunitate = O.CodOportunitate
        LEFT JOIN CAMPANII      C   ON C.CodCampanie      = O.CodCampanie
        LEFT JOIN NPERS         DEL ON DEL.CodPers        = O1.CodAgent ' || coalesce (gSuplJoins ,'') || '
      WHERE
        O.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 ( (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT
                         FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'O', 'CODSUBUNITATE',NULL,NULL)) ::varchar ,'');

  IF current_setting('PKG_LIST_SELECTPERIOADA.vOpt1', true)::NUMERIC = 1 THEN
    sSelect := coalesce (sSelect,'') || ' and not exists (select o2.stadiu from oportunitati1 o2 where o2.codoportunitate = o.codoportunitate and o2.stadiu = 0)';
  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_ordonantari_processlist</obj_name>
  <obj_hashval>13703f792a270c02e407d22dd9d3d00e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ordonantari_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC           RECORD;
  sInsert         varchar := '';
  sInsertAux       varchar := '';
  sSelect         varchar := '';
  aDataIni         varchar := '';
  aDataFin         varchar := '';
  aDataIniSold     date;
  aDataFinSold     date;
  sFiltru         varchar := '';
  sFiltruSold     varchar := '';
  aAn             numeric;
  aLuna           numeric;
  aAnC             numeric;
  aLunaC           numeric;
  aUserID         numeric;
  gSuplCols        VARCHAR := 'plati p, plati1 p1, analiza a, nmonede m, analizanod nod';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 15 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_ORDONANTARI.gSuplCols',gSuplCols,false);
  gUserFields  := coalesce(gUserFields,'');
  gUserAlias   := coalesce(gUserAlias ,'');
  gNullAlias   := coalesce(gNullAlias ,'');
  gSuplJoins   := coalesce(gSuplJoins ,'');
  gSuplCols    := coalesce(gSuplCols  ,'');

  aDataIni     := to_char(pkg_list_selectper_dataini(), 'dd.mm.yyyy');
  aDataFin     := to_char(pkg_list_selectper_datafin(), 'dd.mm.yyyy');
  aDataIniSold := to_date('01.' || coalesce(to_char(pkg_list_selectper_dataini(), 'MM.YYYY'),''), 'DD.MM.YYYY');
  aDataFinSold := DATE_TRUNC('DAY',pkg_list_selectper_dataini())::date - 1;

  SELECT Extract( Year  FROM pkg_list_selectper_dataini()) INTO aAn;
  SELECT Extract( Month FROM pkg_list_selectper_dataini()) INTO aLuna;

  aAnC     := aAn;
  aLunaC   := aLuna;

  IF  aLuna = 1 THEN
    aLuna := 12;
    aAn   := aAn - 1;
  ELSE
    aLuna := aLuna - 1;
  END IF;

  sFiltru := ' and p.data between to_date(''' || coalesce(aDataIni,'') || ''',''dd.mm.yyyy'') and to_date(''' || coalesce(aDataFin,'') || ''',''dd.mm.yyyy'') ';

  sInsert :=
  'INSERT INTO ' || TMPNAME || '(
     NAV_CodDoc,
     NAV_TipDoc,
     CodAnalizaNod,
     Banca,
     Cont,
     Moneda,
     NrDoc,
     DataDoc,
     Aprobat,
     PrjAnaliza,
     Destinatar,
     DocP,
     NrDocP,
     ValDoc,
     Termen,
     Platit,
     SimbolNod,
     DenNod,
     TipLinie,
     Rest,
     SoldLinie ' || gUserFields || ')';

  sSelect := '
  select p.codplata, 105, nod.codanalizanod,
       bk.simbol, bc.nrcont, m.simbol, p.nrdoc, p.data, case when coalesce(p.aprobat,0) = 1 then ''DA'' else ''NU'' end,
       a.den_analiza, pa.den_part, i.prefixdoc, i.nrdoc, o.valoare, o.termen, p1.valoare, nod.simbolnod, nod.dennod,
       '' '' TipLinie, p1.valoare - coalesce((select sum(s.valoare) from stingere s where s.codplata1 = p1.codplata1),0), - p1.valoare
        ' || gUserAlias || '
  from plati p
       inner join plati1    p1  on p1.codplata       = p.codplata
       inner join obligpif  o   on o.codobligpif     = p1.codobligpif
       inner join general   g   on g.codgeneral      = o.codgeneral and g.tipdoc &lt;&gt; 5
       inner join intrari   i   on g.tipdoc          = i.tipdoc     and g.coddoc = i.codintr
       inner join npart     pa   on pa.codpart        = o.codpart
       left join nbankcont  bc   on bc.codbankcont    = p.codbankcont
       left join nbank      bk   on bc.codbank        = bk.codbank
       left join nmonede    m   on m.codmoneda       = bc.codmoneda
       left join analiza    a   on a.codanaliza      = p.codanaliza
       left join analizanod nod on nod.codanalizanod = o.codanalizanod
       ' || gSuplJoins || '
  where coalesce(p.TipDoc,0) = 1 ' || coalesce(chr(13),'') || coalesce(sFiltru,'') || coalesce(chr(13),'') || '
  union all
  select p.codplata, 105, nod.codanalizanod,
         bk.simbol, bc.nrcont, m.simbol, p.nrdoc, p.data, case when coalesce(p.aprobat,0) = 1 then ''DA'' else ''NU'' end,
         a.den_analiza, pa.den_part, ''DVOT'' prefixdoc, d.nrdoc, o.valoare, o.termen, p1.valoare, nod.simbolnod, nod.dennod,
         '' '' TipLinie, p1.valoare - coalesce((select sum(s.valoare) from stingere s where s.codplata1 = p1.codplata1),0), - p1.valoare ' || gUserAlias || '
  from plati p
       inner join plati1    p1   on p.codplata        = p1.codplata
       inner join obligpif  o   on o.codobligpif     = p1.codobligpif
       inner join general   g   on g.codgeneral      = o.codgeneral and g.tipdoc = 5
       inner join dvi       d   on g.coddoc          = d.coddvi
       inner join intrari   i   on d.codintr         = i.codintr
       inner join npart     pa   on pa.codpart        = o.codpart
       left join analizanod nod on nod.codanalizanod = o.codanalizanod
       left join nbankcont  bc   on bc.codbankcont    = p.codbankcont
       left join nbank      bk   on bc.codbank        = bk.codbank
       left join nmonede    m   on m.codmoneda       = bc.codmoneda
       left join analiza    a   on a.codanaliza      = p.codanaliza
       ' || gSuplJoins || '
  where coalesce(p.TipDoc,0) = 1 ' || coalesce(chr(13),'') || coalesce(sFiltru,'') || coalesce(chr(13),'') || '
  union all
  select p.codplata, 105, nod.codanalizanod,
         bk.simbol, bc.nrcont, m.simbol, p.nrdoc, p.data, case when coalesce(p.aprobat,0) = 1 then ''DA'' else ''NU'' end,
         a.den_analiza,
         Case when P1.CODOBLIGPIF = 0 then PA.DEN_PART
              when P1.CODOBLIGPIF = 1 then AN.NUME ||'' ''|| AN.PRENUME
              when P1.CODOBLIGPIF = 2 then C.Simbol
         end, null, null, 0, null, p1.valoare, nod.simbolnod, nod.dennod,
         case P1.CODOBLIGPIF + 1
           when 0 then ''Plata obligatie''
           when 1 then ''Avans furnizor''
           when 2 then ''Avans decont''
           when 3 then ''Direct pe cont''
         end TipLinie, p1.valoare - coalesce((select sum(t1.valdoc) from trezor1 t1 where t1.codplata1 = p1.codplata1),0), - p1.valoare ' || gUserAlias || '
  from plati p
       inner join plati1    p1   on p1.codplata       = p.codplata
       left join analizanod nod on nod.codanalizanod = p1.codanalizanodx
       left join nbankcont  bc   on bc.codbankcont    = p.codbankcont
       left join nbank      bk   on bc.codbank        = bk.codbank
       left join nmonede    m   on m.codmoneda       = bc.codmoneda
       left join analiza    a   on a.codanaliza      = p.codanaliza
       left join npart      pa   on pa.codpart        = p1.codpart
       left join npers      an   on an.codpers        = p1.codpers
       left join ncont      c   on c.codcont         = p1.codcont
       ' || gSuplJoins || '
  where coalesce(p.TipDoc,0) = 1 and p1.codobligpif &lt; 10 ' || coalesce(chr(13),'') || coalesce(sFiltru,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

  aUserID := current_setting('PKG_GLOBALS.USERID', true)::numeric;

  DELETE FROM tmp_cmd WHERE  userid = aUserID;

  INSERT INTO tmp_cmd(codobiect, cantc, userid)
  SELECT a.codanalizanod, COALESCE(x.buget, 0), aUserID
  FROM   analizanod a
        LEFT JOIN (  SELECT b.codanalizanod, b.buget
                    FROM bugetanaliza b
                    WHERE b.an * 12 + b.luna = (SELECT max(t.an * 12 + t.luna)
                                                FROM bugetanaliza t
                                                WHERE t.codanalizanod = b.codanalizanod and  t.an * 12 + t.luna &lt;= aAnC * 12 + aLunaC
                                               )
                  ) x ON  x.codanalizanod = a.codanalizanod;

  FOR v_rec IN (SELECT sum(Buget) BUGET, CodAnalizaNod
                FROM (SELECT COALESCE(R1.CodNodDest, 0) CODANALIZANOD, R1.VCredit BUGET
                      FROM   Bugetrectif1 R1
                            INNER JOIN Bugetrectif R ON  R.Codbugetrectif = R1.CODBUGETRECTIF
                      WHERE R.DataDoc &lt; pkg_list_selectper_dataini() and  r.an = aAnC and  COALESCE(R1.CodNodDest, 0) &gt; 0 and  COALESCE(R1.VCredit, 0) &gt; 0
                      union ALL
                      SELECT COALESCE(R1.CodNodSursa, 0) CODANALIZANOD, -R1.VCredit BUGET
                      FROM   Bugetrectif1 R1
                            INNER JOIN Bugetrectif R ON  R.Codbugetrectif = R1.CODBUGETRECTIF
                      WHERE R.DataDoc &lt; pkg_list_selectper_dataini() and  r.an = aAnC and  COALESCE(R1.CodNodSursa, 0) &gt; 0 and  COALESCE(R1.VCredit, 0) &gt; 0
                     ) A_PG
                GROUP BY CodAnalizaNod
               )
  LOOP
    UPDATE tmp_cmd
      SET cantc = cantc + v_rec.buget
    WHERE codobiect = v_rec.codanalizanod;
  END LOOP;

  FOR v_rec IN (SELECT nod.codanalizanod, p1.valoare
                FROM   plati p
                      INNER JOIN plati1    p1   ON  p1.codplata       = p.codplata
                      INNER JOIN obligpif  o     ON  o.codobligpif     = p1.codobligpif
                      INNER JOIN general   g     ON  g.codgeneral      = o.codgeneral
                      INNER JOIN intrari   i     ON  g.tipdoc          = i.tipdoc and  g.coddoc = i.codintr and  g.tipdoc &lt;&gt; 5
                      INNER JOIN npart     pa   ON  pa.codpart        = o.codpart
                      LEFT JOIN nbankcont  bc   ON  bc.codbankcont    = p.codbankcont
                      LEFT JOIN nbank      bk   ON  bc.codbank        = bk.codbank
                      LEFT JOIN nmonede    m     ON  m.codmoneda       = bc.codmoneda
                      LEFT JOIN analiza    a     ON  a.codanaliza      = p.codanaliza
                      LEFT JOIN analizanod nod   ON  nod.codanalizanod = o.codanalizanod
                WHERE COALESCE(p.TipDoc, 0) = 1 and  p.data &lt; pkg_list_selectper_dataini() and  p.an = aAnC
                union ALL
                SELECT nod.codanalizanod, p1.valoare
                FROM   plati p
                      INNER JOIN plati1    p1   ON  p.codplata        = p1.codplata
                      INNER JOIN obligpif  o     ON  o.codobligpif     = p1.codobligpif
                      INNER JOIN general   g     ON  g.codgeneral      = o.codgeneral and  g.tipdoc = 5
                      INNER JOIN dvi       d     ON  g.coddoc          = d.coddvi
                      INNER JOIN intrari   i     ON  d.codintr         = i.codintr
                      INNER JOIN npart     pa   ON  pa.codpart        = o.codpart
                      LEFT JOIN analizanod nod   ON  nod.codanalizanod = o.codanalizanod
                      LEFT JOIN nbankcont  bc   ON  bc.codbankcont    = p.codbankcont
                      LEFT JOIN nbank      bk   ON  bc.codbank        = bk.codbank
                      LEFT JOIN nmonede    m     ON  m.codmoneda       = bc.codmoneda
                      LEFT JOIN analiza    a     ON  a.codanaliza      = p.codanaliza
                WHERE COALESCE(p.TipDoc, 0) = 1 and  p.data &lt; pkg_list_selectper_dataini() and  p.an = aAnC
                union ALL
                SELECT nod.codanalizanod, p1.valoare
                FROM   plati p
                      INNER JOIN plati1    p1   ON  p1.codplata       = p.codplata
                      LEFT JOIN analizanod nod   ON  nod.codanalizanod = p1.codanalizanodx
                      LEFT JOIN nbankcont  bc   ON  bc.codbankcont    = p.codbankcont
                      LEFT JOIN nbank      bk   ON  bc.codbank        = bk.codbank
                      LEFT JOIN nmonede    m     ON  m.codmoneda       = bc.codmoneda
                      LEFT JOIN analiza    a     ON  a.codanaliza      = p.codanaliza
                      LEFT JOIN npart      pa   ON  pa.codpart        = p1.codpart
                      LEFT JOIN npers      an    ON  an.codpers        = p1.codpers
                      LEFT JOIN ncont      c     ON  c.codcont         = p1.codcont
                WHERE COALESCE(p.TipDoc, 0) = 1 and  p1.codobligpif &lt; 10 and  p.data &lt; pkg_list_selectper_dataini() and  p.an = aAnC
               )
  LOOP
    UPDATE tmp_cmd
    SET cantc = cantc - v_rec.valoare
    WHERE codobiect = v_rec.codanalizanod;
  END LOOP;

  sInsertAux :=
  'INSERT INTO ' || TMPNAME || '(
     NAV_CodDoc,
     NAV_TipDoc,
     DataDoc,
     CodAnalizaNod,
     Destinatar,
     Platit,
     SoldLinie,
     SimbolNod,
     DenNod ' || gUserFields || ')
   select 0, 0, to_date(''' || coalesce(aDataIni,'') || ''',''dd.mm.yyyy''), tmp.codobiect, ''Sold initial'', tmp.cantc, tmp.cantc, nod.simbolnod, nod.dennod ' || gNullAlias || '
   from tmp_cmd tmp
        left join analizanod nod on nod.codanalizanod = tmp.codobiect
   where userid = ' || coalesce(aUserID::varchar,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsertAux, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_parcauto_processlist</obj_name>
  <obj_hashval>cb45da03d0db81c216e7c9586df7501c</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_parcauto_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  gSuplCols   VARCHAR := 'nparcaut pa, npers s, mifix mf, nirstoc ns, ngest g, nartobj o ';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 31.10.2025 - sinc. Oracle
  --Florin 16.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_PARCAUTO.gSuplCols', gSuplCols, FALSE);

  sInsert := 'INSERT INTO ' || tmpName || '(
        NAV_CodDoc,
        NAV_TipDoc,
        Den, NrInv, Sofer, GestMifix, GestExploat, Tip,
        NrInreg, DataInreg, Marca, Model, AnFab, SerieC, Culoare, Lung, Lat, Inalt,
        TipMotor, SerieMotor, Combustibil, Cilindree, Putere, Rezervor, CMM, CMU, CME,
        TipIncarc, Greutate, MasaMax, MasaUtil, MasaURDF, MasaURFDF,
        VolumUtil, LocTot, LocFata, LocSpate, LocPic, Status,
        PartLeas,
        MONEDA, DATAACHIZ, DATAENDLEAS, NRCONTR,
        RataLeas, RataCasco, RataRCA, KMBORD, DATABORD ' || gUserFields || ')
        WITH mf1 AS (SELECT codmifix, Max(codnirstoc) codnirstoc FROM mifix1 GROUP BY codmifix)
        SELECT
        pa.codnparcaut, 505,
        o.denumire, pa.nrinv, (s.nume||'' ''||s.prenume) sofer, g.den_gest, gt.den_gest,(CASE WHEN pa.tip = 0 THEN ''MOTORIZAT'' ELSE ''TRACTAT'' END) tip,
        pa.nrinreg, pa.datainreg, ma.marca, mo.model, pa.anf, pa.seriec, pa.culoareC, pa.lung, pa.lat, pa.inalt,
        pa.tipmotor, pa.seriem, pa.sursae, pa.cilindree, pa.putere, pa.rezervor, pa.cmm, pa.cmu, pa.cme,
        (CASE WHEN tipincarc = 1 THEN ''Marfa'' WHEN tipincarc = 2 THEN ''Persoane'' WHEN tipincarc = 3 THEN ''Mixta'' END) tipincarc, pa.greutate, pa.masam, pa.masau, pa.masaurdf, pa.masaurfdf,
        pa.volumu, pa.loct, pa.locf, pa.locs, pa.locp,
        (CASE WHEN PA.INACTIV = 0 THEN ''Activ'' WHEN PA.INACTIV = 2 THEN ''Conservare'' WHEN PA.INACTIV = 3 THEN ''Dauna totala'' WHEN PA.INACTIV = 4
        THEN ''La vanzare'' WHEN PA.INACTIV = 1 THEN ''Vandut'' WHEN PA.INACTIV = 5 THEN ''Radiat'' END) Status,
        NP.Den_part,
        M.Simbol, PA.DATAACHIZ, PA.DATAENDLEAS, PA.NRCONTR,
        PA.RataLeas, PA.RataCasco,PA.RataRca,p0.kmbord,p0.databord ' || gUserAlias || '
      FROM nparcaut pa
        LEFT JOIN NMonede     M  on M.CodMoneda      = PA.Moneda
        LEFT JOIN npers       s  on s.codpers        = pa.sofer
        LEFT JOIN NPART       NP on NP.CodPart       = PA.PartLeas
        LEFT JOIN (select nrinventar, max(codmifix) codmifix from mifix where tip = ''MF'' group by nrinventar) mfx ON mfx.nrinventar = pa.nrinv
        left join mifix mf on mf.codmifix = mfx.codmifix
        LEFT JOIN (select distinct CodMifix, CodNirStoc from mifix1) 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 ngest       gt ON gt.codgest       = pa.codgest
        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
        LEFT JOIN (SELECT codnparcaut, Max(databord) databord, Max(kmbord) kmbord
                   FROM (SELECT codnparcaut, databord, kmbord, dense_rank() over(Partition by codnparcaut Order by kmbord desc) nr
                         FROM nparc0
                         WHERE COALESCE(kmbord,0) &lt;&gt; 0
                        ) xx
                   WHERE xx.nr=1
                   GROUP BY codnparcaut
                  ) p0 ON p0.codnparcaut = pa.codnparcaut
        ' || gSuplJoins;
--    INSERT INTO x(view_name, test) VALUES ('parc', sinsert);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_pfsdv_setparams</obj_name>
  <obj_hashval>05b998ba2cb715af918b9fb36ebbc152</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pfsdv_setparams(pcodprogramf numeric DEFAULT NULL::numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.10.2020
  perform set_config('PKG_LIST_BASE_PFSDV.vCodProgramF',(pCodProgramF)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_planachiz_setjoinuri</obj_name>
  <obj_hashval>9190e212300ea08ec84b2e9e0292e499</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_planachiz_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01 octombrie 2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_PLANACHIZ.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_planifcmd_setjoinuri</obj_name>
  <obj_hashval>74dc565e2f2964ec80d794e9f06d8725</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_planifcmd_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_PLANIFCMD.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_postcalcul_processlist</obj_name>
  <obj_hashval>a57f79dda4d00a487875b5a0cf0db83b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_postcalcul_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, COMANDA CLI, COMANDA1 CLI1, NGEST G, PRODCOMP PC, NARTOBJ OBJ, NARTOBJ1 OBJ1, NART ART, NUM UM, IOART IOA, NPART PCLI';
  gUserFields  VARCHAR := '';
  gUserAlias   VARCHAR := '';
  gNullAlias   VARCHAR := '';
  gSuplJoins   VARCHAR := '';
  vCodPC       varchar := coalesce(current_setting('PKG_LIST_BASE_POSTCALCUL.vCodPC', true) ,'');
BEGIN
  --Florin 25.07.2025 - sinc. Oracle
  --Laura 29.09.2021 - sinc Oracle (28.09.2021)
  --Florin 12.08.2021 - sinc. Oracle (36397)
  --Adina 27.04.2021 - alstart, alstop
  --Adina 14 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_POSTCALCUL.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 || '(
     ARTICOL,
     DENUM,
     CANT,
     VAL,
     VALS,
     VALi,
     VALa,
     ValG,
     ValC,
     MAT,
     SECTIE,
     COEF,
     MAN,
     VALMAN,
     REST,
     PUCALC,
     PretMat,
     PUNCTE,
     CENTRU,
     DENIOART,
     PRETREFERINTA,
     PRETRETETA,
     PUMEDINREG ' || gUserFields || ' )
   with PUMED As (
     select sum(i1.cant * ns.pret)/sum(i1.cant) Pret, PCA.CodCmd1
     from intrari1 i1
          inner join PCART   PCA on PCA.CodCmd1 = i1.CodCmdInt1
          inner join nirstoc ns  on ns.codintr1 = i1.codintr1
     where PCA.CODPC = ' || vCodPC || '
     group by PCA.CodCmd1
   )
   SELECT
     OBJ.DENUMIRE,
     Substr(UM.DEN_UM,1,15),
     coalesce(PCA.CANT, 0),
     PCA.VAL,
     PCA.VALS,
     PCA.VALi,
     PCA.VALa,
     PCA.ValG,
     PCA.ValC,
     PCA.MAT,
     G.DEN_GEST,
     PCA.COEF,
     PCA.MAN,
     PCA.VALMAN,
     MAT.REST,
     Round(CASE WHEN coalesce(PCA.CANT, 0) = 0 THEN 0 ELSE (coalesce(PCA.MAT, 0)+coalesce(PCA.MAN, 0)+coalesce(PCA.VALS, 0))/coalesce(PCA.CANT, 0) END,5),
     Round(CASE WHEN coalesce(PCA.CANT, 0) = 0 THEN 0 ELSE coalesce(PCA.MAT, 0)/coalesce(PCA.CANT, 0) END,5),
     PCA.PUNCTE,
     CC.Simbol,
     Substr(IOA.DEN_IOART,1,50),
     OBJ1.PRETREFERINTA,
     PC.PRET,
     coalesce(PUMED.Pret,0) ' || gUserAlias || '
   FROM PCART PCA
        INNER JOIN PCALCUL    PCC  ON PCC.CODPC         = PCA.CODPC
        INNER JOIN COMANDA1   C1   ON PCA.CODCMD1       = C1.CODCOMANDA1
        INNER JOIN COMANDA    C    ON C.CODCOMANDA      = C1.CODCOMANDA
        LEFT  JOIN CMDLINK    L    ON L.CODCOMANDA1     = C1.CODCOMANDA1
        LEFT  JOIN COMANDA1   CLI1 ON L.CODLINIECOMANDA = CLI1.CODCOMANDA1
        LEFT  JOIN COMANDA    CLI  ON CLI1.CODCOMANDA   = CLI.CODCOMANDA
        LEFT  JOIN NPART      PCLI ON PCLI.CODPART      = CLI.PARTENER
        LEFT  JOIN PUMED           on PUMED.CodCmd1     = PCA.CodCmd1
        LEFT  JOIN NGEST      G    ON G.CODGEST         = PCA.CODGEST
        LEFT  JOIN CENTRECOST CC   ON CC.CODCENTRU      = PCA.CODCC
        LEFT  JOIN CMDPRODMAT MAT  ON MAT.CODCOMANDA1   = C1.CODCOMANDA1 AND MAT.TIP = 0
        LEFT  JOIN PRODCOMP   PC   ON PC.CODPRODCOMP    = C1.CODRETETA
        LEFT  JOIN CMDPRODMAT PCM  ON PCM.CODCMDPRODMAT = PCA.CODCMDPRODMAT
        LEFT  JOIN NARTOBJ    OBJ  ON OBJ.CODOBIECT     = COALESCE(PCM.CODOBIECT,C1.CODOBIECT)
        LEFT  JOIN NARTOBJ1   OBJ1 ON OBJ1.CODOBIECT    = OBJ.CODOBIECT AND (PCC.AN*12+PCC.LUNA) BETWEEN OBJ1.ALStart and OBJ1.ALStop
        LEFT  JOIN NART       ART  ON OBJ.CODARTICOL    = ART.CODARTICOL
        LEFT  JOIN NUM        UM   ON UM.CODUM          = ART.UM
        LEFT  JOIN IOART      IOA  ON PCA.CODIOART      = IOA.CODIOART
        LEFT JOIN PCDIR       PCD  ON PCC.CODPC         = PCD.CODPC AND PCD.CODNEST = 742
        LEFT JOIN PCDIR       PCD1 ON PCC.CODPC         = PCD1.CODPC AND PCD1.CODNEST = 934' || gSuplJoins ||
   ' WHERE PCA.CODPC = '||vCodPC;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_prodetichete_setjoinuri</obj_name>
  <obj_hashval>59326bc20882c9cde4b7683d8244c527</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_prodetichete_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_PRODETICHETE.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_promo_processlist</obj_name>
  <obj_hashval>1975c10087e49011f5bb5958a2697cb4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_promo_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;
  sInsTmp1 varchar;
  sAuxTmp1 varchar := '';
  sDelTmp1 varchar;
  sUpdTmp1 varchar;
  sInsTmp2 varchar;
  sGrpTMP  varchar;
  vFiltruPart varchar := '';
BEGIN
  --Florin 27.01.2022 - sin. Oracle
  --Florin 19.10.2021 - fixat 51683
  --Florin 11.10.2021 - sinc. Oracle (50704)
  --Adina 17.12.2020 - tichet 41650
  --Bogdan 10.09.2020
  gSuplCols := 'TMP_LST_PROMOPART PP, PROMO P, PROMO1 P1, NARTOBJ O, NART A, NUM1 UM, NCLASEA CA';

  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs (gSuplCols , 'TMP_LST_PROMO', 'TP'  , 'TP.CODPROMO = P.CODPROMO'    ,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 , 'PROMO1CADOU'  , 'PC'  , 'PC.CODCADOU = TMP.CODCADOU'  , 1);
  call pkg_list_struct_addsupltabs (gSuplCols , 'PROMOPRAG'    , 'PRAG', 'PRAG.CODPRAG = TMP.CODPRAG'  , 1);
  call pkg_list_struct_addsupltabs (gSuplCols , 'NARTOBJ'      , 'OC'  , 'OC.CODOBIECT = PC.CODOBIECT' , 1);
  call pkg_list_struct_addsupltabs (gSuplCols , 'PRETM'        , 'PM'  , 'PM.CODOBIECT = O.CODOBIECT AND PM.SUBUNITATEA = TMP.SUBUNITATEA AND PM.IMPLICIT = 1',NULL);
  CALL pkg_list_struct_getsuplcols( aLISTID, aLISTVER, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  perform set_config ('PKG_LIST_BASE_PROMO.gSuplCols',gSuplCols,false);

  IF getsubunitate() &lt;&gt; 1 THEN
    sAuxTmp1 := '
            WHERE Subunitatea IN (1, '|| coalesce (getsubunitate() ::varchar,'')|| ')';
  END IF;

  sInsTmp1 := '
          INSERT INTO TMP_LST_PROMO (CodPromo, Subunitatea, NrSubunit)
          SELECT CodPromo,
                 CASE WHEN Count (1) &gt; 1 THEN 0 ELSE Max (Subunitatea) END,
                 Max (NrSubunit)
          FROM (SELECT CodPromo, Subunitatea, NrSubunit
                FROM (SELECT P.CodPromo,
                             Coalesce (PS.Subunitatea, P.Subunitatea, 1) Subunitatea,
                             Count (1) Over (PARTITION BY P.CodPromo)    NrSubunit
                      FROM PROMO P LEFT JOIN PROMOSUB PS ON PS.CodPromo = P.CodPromo
                      WHERE
                            P.DATASTART &lt;= To_Date ('''|| current_setting ('PKG_LIST_BASE_PROMO.vDataFin', true)|| ''',''dd.mm.yyyy'')
                        AND P.DATAEND   &gt;= To_Date ('''|| current_setting ('PKG_LIST_BASE_PROMO.vDataIni', true)|| ''',''dd.mm.yyyy'')
                     ) a_pg '
            || coalesce (sAuxTmp1,'')
            || ') b_pg
          GROUP BY CodPromo';

  sDelTmp1 := '
          DELETE FROM TMP_LST_PROMO WHERE NOT CodPromo IN (SELECT DISTINCT CODPROMO FROM TMP_LST_PROMOPART) ';
  sUpdTmp1 := '
          UPDATE TMP_LST_PROMO T
          SET LISTSUBUNIT =
            CASE
              WHEN T.NrSubunit = 1 THEN (SELECT S.DEN_SUBUNIT FROM NSubunit S WHERE S.CodSubunit = T.Subunitatea)
              ELSE (SELECT fnc_array_to_vc3200 (ARRAY_AGG(S.Den_Subunit ORDER BY S.Den_Subunit) )
                    FROM PROMOSUB PS, NSubunit  S
                    WHERE PS.CodPromo = T.CodPromo AND S.CodSubunit = PS.Subunitatea)
            END';
  sInsTmp2 := '
        INSERT INTO TMP_LST_PROMOPART (CodPromo,
            Den_Part,
            Den_ClaseP,
            CIF,
            Autorizatie,
            RegCom,
            Den_Localit,
            Cod_Part)
        SELECT P.CodPromo,  ';
  IF current_setting ('PKG_LIST_BASE_PROMO.vGrupPart', true)::numeric = 1 THEN
    sInsTmp2 := coalesce (sInsTmp2,'')||
    ' fnc_array_to_vc3200 (ARRAY_AGG (NP.Den_Part   ORDER BY pp.codpromopart) ) Den_Part,
      fnc_array_to_vc3200 (ARRAY_AGG(CP.Den_ClaseP  ORDER BY pp.codpromopart) )                                                                                                                     Den_ClaseP,
      fnc_array_to_vc3200 (ARRAY_AGG (PCF.CodFiscal ORDER BY pp.codpromopart) )                                                                                                                     CIF,
      fnc_array_to_vc3200 (ARRAY_AGG(NP.Autorizatie ORDER BY pp.codpromopart) )                                                                                                                    Autorizatie,
      fnc_array_to_vc3200 (ARRAY_AGG(NP.RegCom     ORDER BY pp.codpromopart) )                                                                                                                         RegCom,
      fnc_array_to_vc3200 (ARRAY_AGG(L.Den_Localit  ORDER BY pp.codpromopart) ) Den_Localit,
      substr(fnc_array_to_vc3200 (ARRAY_AGG(NP.CODPart::varchar ORDER BY pp.codpromopart)), 50) Cod_Part ';
  ELSE
    sInsTmp2 := coalesce (sInsTmp2,'')
    || 'NP.Den_Part,
      CP.Den_ClaseP,
      PCF.CodFiscal CIF,
      NP.Autorizatie,
      NP.RegCom,
      L.Den_Localit,
      NP.CodPart::varchar';
  END IF;
  sInsTmp2 := coalesce (sInsTmp2,'')
        || '
          FROM TMP_LST_PROMO                   TP
            LEFT JOIN PROMO                    P   ON P.CodPromo        = TP.CodPromo
            LEFT JOIN Promopart                PP  ON PP.CodPromo       = TP.CodPromo
            LEFT JOIN NPART                    NP  ON NP.CodPart        = Coalesce (P.Partener, PP.Partener)
            LEFT JOIN NPARTCODFISC             PCF ON PCF.Cod_CodFiscal = CASE WHEN P.Partener IS NULL THEN PP.CodFiscal  ELSE P.CODFISCAL  END
            LEFT JOIN NAGENDA                  AG  ON AG.CodAgenda      = CASE WHEN P.Partener IS NULL THEN PP.CodLocatie ELSE P.CodLocatie END
            LEFT JOIN NLOCALIT                 L   ON L.CodLocalit      = AG.CodLocalit
            LEFT JOIN NCLASEP                  CP  ON CP.CodClaseP      = PP.CodClaseP';
  IF NOT (current_setting ('PKG_LIST_BASE_PROMO.vTotiPart', true)::numeric = 1) THEN
    sInsTmp2 := coalesce (sInsTmp2,'')
          || ' AND CASE WHEN (SELECT Count (1) FROM promopart pp WHERE pp.codpromo = p.codpromo) = 0 AND Coalesce (P.Partener, 0) = 0 THEN 1
                        WHEN Coalesce (P.TIPCLASEP,0) = 0 THEN (SELECT COUNT (1) FROM TMP_MANEVRA_LISTE TF
                                                                WHERE TF.FILTRU = ''CODPART'' AND TF.VALOARE::numeric = Coalesce (P.Partener, PP.Partener))
                        ELSE (SELECT COUNT (1) FROM NPART XP
                              WHERE XP.CODPART IN (SELECT VALOARE ::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPART'') AND XP.CODCLASA = CP.CodClaseP)
                   END &gt; 0';
       vFiltruPart := ' WHERE PP.COD_PART IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE TML WHERE FILTRU = ''CODPART'' AND TML.VALOARE = PP.COD_PART)';
    END IF;
  sGrpTMP := '
        GROUP BY P.CodPromo';

  IF current_setting ('PKG_LIST_BASE_PROMO.vGrupPart', true)::numeric = 1 THEN
    sInsTmp2 := coalesce (sInsTmp2,'')|| coalesce (sGrpTMP,'');
  END IF;
  sInsert := '
        INSERT INTO '|| TMPNAME
            || ' (NAV_CodDoc,
            NAV_TipDoc,
            NrDoc,
            DataStart,
            DataEnd,
            Obs,
            Moneda,
            Tip,
            ExclAltePromo,
            In_functie_de,
            Influenteaza,
            Praguri,
            Tip_sediu_client,
            PeClasePart,
            Den_Part,
            Den_ClaseP,
            CIF,
            Autorizatie,
            RegCom,
            Den_Localit,
            ART,
            UM,
            CANT,
            PRET,
            PRETAMANUNT,
            DISC,
            ZILEC,
            TIPLIMITA,
            TG_MAX,
            ZILE_EXP,
            SERII,
            CADOU,
            ORDINE'
            || coalesce (gUserFields ,'')
            || ')
        WITH TMP AS
          ( SELECT P1.CODPROMO,
              P1.CODPROMO1,
              0                        CODCADOU,
              Coalesce (PP.CODPRAG, 0) CODPRAG,
              0                        ORD1,
              CASE WHEN Coalesce (PP.CODPRAG, 0) = 0 THEN P1.CODPROMO1 ELSE PP.CODPRAG END  ORD2,
              COALESCE (P1.CodObiect,0) CodObiect,
              Coalesce (P1.UMSec, 0)    UMSec,
              P1.Cant,
              P1.Pret,
              P1.PretAmanunt,
              Coalesce (PP.ProcDisc, P1.ProcDisc) ProcDisc,
              P1.ZileC,
              P1.TipLimita,
              P1.TG_Max,
              P1.Zile_Exp,
              (SELECT fnc_array_to_string_ml  (ARRAY_AGG (s.serie order by s.serie) ) serii FROM PROMO1SER S WHERE S.CodPROMO1 = P1.CodPROMO1) Serii,
              TP.Subunitatea
            FROM TMP_LST_PROMO    TP
              INNER JOIN PROMO    P  ON P.CodPromo  = TP.CodPromo
              INNER JOIN PROMO1   P1 ON P1.CodPROMO = P.CodPROMO
              LEFT JOIN PROMOPRAG PP ON PP.CodPROMO = P.CodPROMO
            UNION ALL
            SELECT P1.CODPROMO,
              P1.CODPROMO1,
              PC.CODCADOU,
              0            CODPRAG,
              0            ORD1,
              P1.CODPROMO1 ORD2,
              PC.CodObiect,
              Coalesce (PC.UMSec, 0) UMSec,
              PC.Cant,
              0    Pret,
              0    PretAmanunt,
              NULL ProcDisc,
              NULL ZileC,
              PC.TipLimita,
              PC.TG_Max,
              PC.Zile_Exp,
              (SELECT fnc_array_to_string_ml  (ARRAY_AGG (s.serie order by s.serie) ) serii FROM PROMO1CADOUSER S WHERE S.CodCADOU = PC.CodCADOU) Serii,
              TP.Subunitatea
            FROM TMP_LST_PROMO       TP
              INNER JOIN PROMO       P  ON P.CodPromo  = TP.CodPromo
              INNER JOIN PROMO1      P1 ON P1.CodPROMO = P.CodPROMO
              INNER JOIN PROMO1CADOU PC ON PC.CodPromo = P.CodPROMO AND PC.CodPROMO1 = CASE WHEN P.DEMANA IN (0,3) THEN P1.CodPROMO1 ELSE 0 END
            WHERE P.DEMANA IN (0,3)
            UNION ALL
            SELECT P.CODPROMO,
              0 CODPROMO1,
              PC.CODCADOU,
              0 CODPRAG,
              1 ORD1,
              0 ORD2,
              PC.CodObiect,
              Coalesce (PC.UMSec, 0) UMSec,
              PC.Cant,
              0    Pret,
              0    PretAmanunt,
              NULL ProcDisc,
              NULL ZileC,
              PC.TipLimita,
              PC.TG_Max,
              PC.Zile_Exp,
              (SELECT fnc_array_to_string_ml  (ARRAY_AGG (s.serie order by s.serie)) serii FROM PROMO1CADOUSER S WHERE S.CodCADOU = PC.CodCADOU) Serii,
              TP.Subunitatea
            FROM TMP_LST_PROMO       TP
              INNER JOIN PROMO       P  ON P.CodPromo  = TP.CodPromo
              INNER JOIN PROMO1CADOU PC ON PC.CodPromo = P.CodPROMO
            WHERE NOT P.DEMANA IN (0,3)
          )
        SELECT TMP.CodPromo,
          56,
          P.NrDoc,
          P.DataStart,
          P.DataEnd,
          P.Obs,
          M.Simbol,
          CASE P.DeMana
            WHEN 0 THEN ''Articole individuale''
            WHEN 1 THEN ''Pachet PROMO''
            WHEN 2 THEN ''Optional PROMO''
            WHEN 3 THEN ''Clase de articole''
            WHEN 4 THEN ''Toate articolele''
          END TIP,
          CASE WHEN P.ExclAltePromo = 1 THEN ''Da'' ELSE ''Nu'' END ExclAltePromo,
          CASE P.TipConditie
            WHEN 0 THEN ''neconditionat''
            WHEN 1 THEN ''cantitate minima de livrare''
            WHEN 2 THEN ''zile credit''
            WHEN 3 THEN ''valoare minima de livrare''
          END In_functie_de,
          CASE P.TipPromotie
            WHEN 1 THEN ''marime pret''
            WHEN 2 THEN ''%% discount''
            WHEN 3 THEN ''articole promotionale (cadou) ''
            WHEN 4 THEN ''valoare discount''
          END Influenteaza,
          CASE WHEN P.Praguri = 1 THEN ''Da'' ELSE ''Nu'' END Praguri,
          CASE P.TipServire
            WHEN 0 THEN ''orice sediu''
            WHEN 1 THEN ''cu servire indirecta''
            WHEN 2 THEN ''cu servire directa''
          END Tip_sediu_client,
          CASE WHEN P.TipClaseP = 1 THEN ''Da'' ELSE ''Nu'' END PeClasePart,
          CASE WHEN P.TipClaseP = 1 THEN PP.Den_ClaseP ELSE PP.Den_Part END,
          PP.Den_ClaseP,
          PP.CIF,
          PP.Autorizatie,
          PP.RegCom,
          PP.Den_Localit,
          CASE
            WHEN P.DeMana = 3 AND TMP.CodCadou = 0 THEN CA.DEN_CLASEA
            WHEN P.DeMana = 4 AND TMP.CodCadou = 0 THEN ''Toate articolele''
            ELSE O.Denumire
          END ART,
          UM.Den_UM1,
          TMP.Cant        / UM.Paritate CANT,
          TMP.Pret        * UM.Paritate PRET,
          TMP.PretAmanunt * UM.Paritate PRETAMANUNT,
          TMP.ProcDisc,
          TMP.ZileC,
          CASE TMP.TipLimita
            WHEN 3 THEN ''Serie''
            WHEN 2 THEN ''Zile expirare &lt;= ''||TMP.Zile_Exp
            WHEN 1 THEN ''Data expirare &lt;= ''||To_Char (TMP.TG_Max,''dd.mm.yyyy'')
            ELSE ''Stoc disponibil''
          END TIPLIMITA,
          TMP.TG_Max,
          TMP.Zile_Exp,
          TMP.Serii,
          CASE WHEN TMP.CodCadou = 0 THEN ''Nu'' ELSE ''Da'' END CADOU,
          DENSE_RANK() OVER (PARTITION BY TMP.CodPromo ORDER BY TMP.ORD1, TMP.ORD2, TMP.CodCadou) ORDINE'
            || coalesce (gUserAlias ,'')|| '
        FROM TMP
          LEFT JOIN PROMO             P  ON P.CodPromo   = TMP.CodPromo
          LEFT JOIN PROMO1            P1 ON P1.CodPromo1 = TMP.CodPromo1
          LEFT JOIN TMP_LST_PROMOPART PP ON PP.CodPromo  = TMP.CodPromo
          LEFT JOIN NARTOBJ           O  ON O.CodObiect  = TMP.CodObiect
          LEFT JOIN NART              A  ON A.CodArticol = O.CodArticol
          LEFT JOIN NUM1              UM ON UM.CodUM1    = TMP.UMSec
          LEFT JOIN NMONEDE           M  ON M.CodMoneda  = P.Moneda
          LEFT JOIN NCLASEA           CA ON CA.CodClaseA = CASE P.DeMana WHEN 3 THEN P1.CODCLASEA ELSE A.Clasa END'
            || coalesce (gSuplJoins ,'') || vFiltruPart;
  PERFORM LIST_EXECUTE_IMMEDIATE ('TRUNCATE TABLE TMP_LST_PROMO', aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE ('TRUNCATE TABLE TMP_LST_PROMOPART', aListID, aListVer);

  PERFORM LIST_EXECUTE_IMMEDIATE (sInsTmp1, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE (sInsTmp2, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE (sDelTmp1, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE (sUpdTmp1, 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_rac_detinfolg_processlist</obj_name>
  <obj_hashval>e2f02a5f2ba5f4e12f979bbdce124934</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rac_detinfolg_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
BEGIN
  --Adina 14.08.2021 - sinc.Oracle
  --Adina 15.10.2020
  sInsert :=
  'INSERT INTO ' || tmpName || '(Cod,Subunitate, Gestiune, Locatie, Clasa, NRAuto,Marca,Model,DataSosire,Status)
   SELECT Cod,Subunitate, Gestiune, Locatie, Clasa, NRAuto,Marca,Model,DataSosire,Status
   FROM TMP_RACDetaliereInfoG ORDER BY COD asc';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rac_detinfolg_setparams</obj_name>
  <obj_hashval>0c87b6bdf439b5ee7a33bda4803ddb37</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rac_detinfolg_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  perform set_config('PKG_LIST_BASE_RAC_DETINFOLG.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rac_masinioc_ce_processlist</obj_name>
  <obj_hashval>919020355ed857966c426abf3f102155</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rac_masinioc_ce_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
  sSelect varchar := '';
  gDataS  varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true);
  gDataF  varchar := current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true);
  sALMin   varchar := (Extract( Year FROM to_date(gDataS, 'dd.mm.yyyy')) * 12 + Extract( Month FROM to_date(gDataS, 'dd.mm.yyyy')))::varchar;
  sALMax   varchar := (Extract( Year FROM to_date(gDataF, 'dd.mm.yyyy')) * 12 + Extract( Month FROM to_date(gDataF, 'dd.mm.yyyy')))::varchar;
  sZIMin   varchar := (Extract( DAY  FROM to_date(gDataS, 'dd.mm.yyyy')))::varchar;
  sZIMax   varchar := (Extract( DAY  FROM to_date(gDataF, 'dd.mm.yyyy')))::varchar;
BEGIN
  --Florin 15.02.2023 - fixat 57205
  --Florin 10.02.2023 - fixat 57082
  --Adina 15.10.2020
  sInsert :=
  'INSERT INTO ' || tmpName || '(
          AN        ,
          LUNA      ,
          ZI        ,
          DATA            ,
          GESTIUNE        ,
          SUBUNITATE      ,
          MARCA           ,
          MODEL           ,
          CLASA           ,
          Judet           ,
          CUSTOMER        ,
          SHUTTLE         ,
          COURTESY        ,
          UZINTERN        ,
          REPARATII       ,
          ABONAMENT       ,
          TRANSFER )';

  sSelect := '
  WITH recursive q(Codcomanda, TipRezervare, NIVEL, DATA) as (
    SELECT R.Codcomanda, R.TipRezervare, 1 NIVEL, Date_Trunc(''day'',R.DATASTART)::date as DATA
    FROM RAC_REZ R
    UNION ALL
    SELECT R.Codcomanda, R.TipRezervare, Q.NIVEL + 1, Date_Trunc(''day'', add_days(R.DATASTART::date, Q.NIVEL::integer))::date
    FROM RAC_REZ R, q
    WHERE R.Codcomanda = q.Codcomanda AND Q.DATA &lt; add_days(Date_Trunc(''day'',R.DATASTART)::date, Q.NIVEL)
    AND add_days(Date_Trunc(''day'',R.DATASTART)::date, Q.NIVEL::integer) &lt;= Case when coalesce(R.Predat,0) = 0 then Date_Trunc(''day'',R.DATASTOP) else Least(Date_Trunc(''day'',R.DATASTOP), Date_Trunc(''day'',R.DATAPRED)) end
    ),
  t as (
    SELECT
      q.Codcomanda, q.TipRezervare, q.NIVEL, q.DATA,
      Extract(Year from q.Data) An,
      Extract(Month from q.Data) Luna,
      Extract(Day from q.Data) Zi
    FROM q
  )
  Select An, Luna, Zi, Data, Gestiune, Subunitate, Marca, Model, Clasa, Judet,
    Sum( Customer ) Customer ,
    Sum( Shuttle  ) Shuttle  ,
    Sum( Courtesy ) Courtesy ,
    Sum( UzIntern ) UzIntern ,
    Sum( Reparatii) Reparatii,
    Sum( Abonament) Abonament,
    Sum( Transfer ) Transfer
  FROM (
        Select t.An, t.Luna, t.Zi,
          (case when t.TipRezervare= 0 then 1 else 0 end) Customer,
          (case when t.TipRezervare= 1 then 1 else 0 end) Shuttle,
          (case when t.TipRezervare= 3 then 1 else 0 end) Courtesy,
          (case when t.TipRezervare= 4 then 1 else 0 end) UzIntern,
          (case when t.TipRezervare= 5 then 1 else 0 end) Reparatii,
          (case when t.TipRezervare= 6 then 1 else 0 end) Abonament,
          (case when t.TipRezervare= 7 then 1 else 0 end) Transfer,
          t.DATA, G.DEN_GEST Gestiune, S.Den_subunit Subunitate, Coalesce(Ma.Marca, ''?'') Marca, Coalesce(Mo.Model, ''?'') Model,
          Gr.DENUMIRE Clasa, J.SIMBAUTO Judet
        from   t
              inner join comanda     c   on c.codcomanda          = t.codcomanda
              inner join Rac_Rez     r   on r.codcomanda          = c.codcomanda
              inner join NParcAut    P   on P.CODNPARCAUT         = Coalesce(C.MijlTransp, 0)
              inner join NEchiv      E   on E.Codobiect           = P.CodArt
              inner join GrEchiv     Gr  on Gr.CODGRECHIV         = E.CodGrupa
              inner join NGest       G   on G.codGest             = R.CodGestSursa
              inner join NAGENDA     A   on Coalesce(A.CodGest,0) = G.CODGEST
              inner join NLocalit    L   on L.CodLocalit          = A.Codlocalit
              inner join NJudet      J   on J.CodJudet            = L.CodJudet
              inner join Nsubunit    S   on S.codSubunit          = G.CodSubunit
              left  join Nmodeleauto Mo  on Mo.CODMODELEAUTO      = Coalesce(p.Model,0)
              left  join Nmarciauto  Ma  on Ma.CODMarciAuto       = Coalesce(p.Marca,0)
            where c.tipdoc = 94  and Coalesce(C.Mijltransp,0) &gt; 0 and Coalesce(E.Generic,0) = 0
              and t.An*12+t.LUNA between ' || coalesce(sALMin,'') || ' and ' || coalesce(sALMax,'') || '
              and t.zi between ' || coalesce(sZIMin,'') || ' and ' || coalesce(sZIMax,'') || '
       ) A_PG
  GROUP BY An, Luna, Zi, Data, Gestiune, Subunitate, Marca, Model, Clasa, Judet';
  PERFORM PKG_RAC_REZ_SET_RAC_DATASTART(gDataS);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_raportpdoc_setjoinuri</obj_name>
  <obj_hashval>5d9954fdd91f0a6583963bb469cb9d6e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportpdoc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_RAPORTPDOC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_receptii_processlist</obj_name>
  <obj_hashval>1864fef8fab69ed2332a672d338983df</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_receptii_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar;
  sSelect     varchar;
  sFrom       varchar;
  sFiltruN    varchar;
  sFiltruL    varchar;
  sFiltruT    varchar;
  sFiltruI    varchar;
  sInsTmp     varchar;
  sSelTmpT    varchar;
  sSelTmpI    varchar;
  sSelTmpL    varchar;
  g_data1     varchar := To_Char(fnc_current_setting_date('PKG_LIST_SELECTGEST.vDataIni'), 'dd.mm.yyyy');
  g_data2     varchar := To_Char(fnc_current_setting_date('PKG_LIST_SELECTGEST.vDataFin'), 'dd.mm.yyyy');
  vDupaData   BOOLEAN := current_setting('PKG_LIST_SELECTGEST.vDupaData' , TRUE)::NUMERIC = 1;
  vLunaAnIni  NUMERIC := current_setting('PKG_LIST_SELECTGEST.vLunaAnIni', TRUE);
  vLunaAnFin  NUMERIC := current_setting('PKG_LIST_SELECTGEST.vLunaAnFin', TRUE);
  vDataDoc    BOOLEAN := current_setting('Pkg_List_Selectgest.bDataDoc'  , TRUE)::NUMERIC = 1;
  vJoinSeriiN varchar;
  vJoinSeriiL varchar;
  vColSeriiN  varchar;
  vColSeriiL  varchar;
  sInsertDC   varchar;
  sSelectDC   varchar;
  sSelectDCN  varchar;
  sSelectDCL  varchar;
  sJoinDC     varchar;
  sCodNirSerL varchar;
  gSuplCols   varchar := 'TMP_LST_RECEPTII R, NLOCATII NLOC, NARTOBJ OBJ, NPART NP, NPART FURN, NCONT NCSTOC, NSUBUNIT NSUB, NGEST GESTPROD, IOART IO, NPART PROD, COMANDA CF, NCLASEAS NCLS, ' || 'NCLASEA NCA, INTRARI I, INTRARI1 I1';
  gUserFields varchar;
  gUserAlias  varchar;
  gNullAlias  varchar;
  gSuplJoins  varchar;
  sFiltruDoc  VARCHAR(50);
  sFiltruDocM VARCHAR(50);
  sOperat     VARCHAR(50);
BEGIN
  --Florin 25.09.2024 - sinc. Oracle
  --Florin 22.07.2024 - sinc. 62759
  --Florin 03.07.2024 - sinc. Oracle
  --Florin 12.02.2024 - sinc. Oracle
  --Florin 07.10.2022 - fixat 55907
  --Florin 06.10.2022 - sinc. Oracle
  --Florin 02.12.2021 - fixat 52184
  --Adina 09.03.2021 - prc_al_check
  --Adina 19.02.2021 - PKG_LIST_BASE_UTILS_UMA_UTILS
  --Florin 11.08.2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NGEST'          , 'NG'      , 'NG.CODGEST         = R.GEST'                ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPARTDET'      , 'PD'      , 'PD.CODPART         = NP.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, 'INTRARIF'      , 'INTRF'    , 'INTRF.CODINTR       = I.CODINTR'            ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARIF1'      , 'INTRF1'  , 'INTRF1.CODINTR1     = I1.CODINTR1'          ,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'      , 'LOCSOC'  , 'LOCSOC.CODLOCALIT   = SSOC.CODLOCALIT'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTARI'          , 'TARASOC'  , 'LOCSOC.CODTARA     = TARASOC.CODTARA'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPART'          , 'TRANSP'  , 'TRANSP.CODPART     = I.TRANSPORTATOR'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRASTEPTLINK', 'WLINK'    , 'WLINK.CODINTR1     = I1.CODINTR1'          ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARI1'      , 'IW1'      , 'IW1.CODINTR1       = WLINK.CODLINIEFACTURA',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'INTRARI'        , 'FASTEPT'  , 'FASTEPT.CODINTR     = IW1.CODINTR'          ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NART'          , 'N'        , 'N.CODARTICOL       = R.CODARTICOL'          ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NTVA'          , 'T'        , 'T.CODTVA           = R.CODTVA'              ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NIRSTOC'        , 'NS'      , 'NS.CODNIRSTOC       = R.CODNIRSTOC'          ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NPERS'          , 'OPERATOR', 'OPERATOR.LOGONNAME = R.USERID'              ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTAMB'        , 'AA'      , 'AA.CODOBIECT       = R.CODOBIECT AND AA.UMSEC = R.CODUMNIR',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'FORMATII'      , 'FORM'    , 'I.CODFORMATIE       = FORM.CODFORMATIE AND I.TIPDOC = 7'    ,NULL);
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_RECEPTII.gSuplCols', gSuplCols, false);

  SELECT sinsertuma, sselectuma, sjoinuma
  INTO   sInsertDC, sSelectDC, sJoinDC
  FROM PKG_LIST_BASE_UTILS_UMA_UTILS('xxxcantxxx', 'r.codobiect', sInsertDC, sSelectDC, sJoinDC,NULL);
  --PERFORM PKG_LIST_BASE_UTILS_UMA_UTILS('xxxcantxxx', 'r.codobiect', sInsertDC, sSelectDC, sJoinDC,NULL);


  CALL PRC_AL_CHECK('nart1');
  CALL PRC_AL_CHECK('ntaxe1');

  IF current_setting('pkg_list_selectgest.bAduSerii', TRUE)::numeric = 1 THEN
    sSelectDCN := REPLACE(sSelectDC, 'xxxcantxxx', 'COALESCE(nser.cantnir,r.cantfurn)');
  ELSE
    sSelectDCN := REPLACE(sSelectDC, 'xxxcantxxx', 'r.cantfurn');
  END IF;

  sSelectDCL := REPLACE(sSelectDC, 'xxxcantxxx', 'r.cantnir');
  vColSeriiN := ',
        R.CANTFURN/UMDOC.PARITATE CANT,
        R.CANTNIR/UMNIR.PARITATE CANTNIR,
        CASE WHEN R.TIPNIR IN (12,13) THEN 0 WHEN COALESCE(I1.RESTFACT,0) = I1.CANT THEN 0 WHEN I1.CANT = 0 THEN 0 ELSE R.CANTFURN*(I1.CANT-COALESCE(I1.RESTFACT,0))/I1.CANT/UMDOC.PARITATE END CANTFACT,
        R.TG, NULL SERIE, NULL CANTSER,NULL OBSSER, NULL NRCERTIFSER, NULL DATAPRIMIRE, NULL DATAPROD, NULL PROVENIENTA, NULL DEN_TARA, NULL OBSCERTIF ';
  vColSeriiL := ',
        R.CANTFURN/UMDOC.PARITATE CANT,
        R.CANTNIR/UMNIR.PARITATE CANTNIR,
        0 CANTFACT,
        R.TG, NULL SERIE, NULL CANTSER,NULL OBSSER, NULL NRCERTIFSER, NULL DATAPRIMIRE, NULL DATAPROD, NULL PROVENIENTA, NULL DEN_TARA, NULL OBSCERTIF ';

  IF current_setting('pkg_list_selectgest.bAduSerii', TRUE)::numeric = 1 THEN
    vJoinSeriiN := '
        LEFT JOIN NIRSER NSER ON NSER.CODNIRSTOC = R.CODNIRSTOC
        LEFT JOIN NSERII SER  ON SER.CODSERIE    = NSER.CODSERIE
        LEFT JOIN CERTIF C    ON C.CODCERTIF     = NSER.CODCERTIF
        LEFT JOIN NTARI  CT   ON CT.CODTARA      = C.CODTARA ';
    vColSeriiN := ',
        CASE WHEN R.TIPSERIE &lt;&gt; 0 THEN (CASE WHEN R.CANTFURN * NSER.CANTNIR IS NULL THEN 0  WHEN R.CANTFURN * NSER.CANTNIR = 0 THEN 0 ELSE R.CANTFURN * NSER.CANTNIR /
          SUM(NSER.CANTNIR) OVER (PARTITION BY R.CODNIRSTOC) END) ELSE R.CANTFURN/UMDOC.PARITATE END CANT,
        CASE WHEN R.TIPSERIE &lt;&gt; 0 THEN NSER.CANTNIR / UMNIR.PARITATE ELSE R.CANTNIR/UMNIR.PARITATE END CANTNIR,
        CASE WHEN R.TIPNIR IN (12,13) THEN 0 WHEN COALESCE(I1.RESTFACT,0) = I1.CANT THEN 0 WHEN I1.CANT = 0 THEN 0 WHEN R.TIPSERIE &lt;&gt; 0 THEN NSER.CANTNIR*(I1.CANT-COALESCE(I1.RESTFACT,0))/I1.CANT/UMDOC.PARITATE ELSE R.CANTFURN*(I1.CANT-COALESCE(I1.RESTFACT,0))/I1.CANT/UMDOC.PARITATE END CANTFACT,
        COALESCE(R.TG,NSER.TG) TG, SER.SERIE, NSER.CANTNIR CANTSER, NSER.OBS OBSSER, C.NRCERTIF NRCERTIFSER, C.DATAPRIMIRE, NSER.DATAPROD, C.PROVENIENTA, CT.DEN_TARA, C.OBS OBSCERTIF ';
    vJoinSeriiL := '
        LEFT JOIN NIRSER NSER ON NSER.CODNIRSER = R.CODNIRSER
        LEFT JOIN NSERII SER  ON SER.CODSERIE   = NSER.CODSERIE
        LEFT JOIN CERTIF C    ON C.CODCERTIF    = NSER.CODCERTIF
        LEFT JOIN NTARI  CT   ON CT.CODTARA     = C.CODTARA ';
    sCodNirSerL := ', l1.codnirser';
    vColSeriiL := ',
        R.CANTFURN/UMDOC.PARITATE CANT,
        R.CANTNIR/UMNIR.PARITATE CANTNIR,
        0 CANTFACT,
        COALESCE(R.TG,NSER.TG) TG, SER.SERIE, NSER.CANTNIR CANTSER, NSER.OBS OBSSER, C.NRCERTIF NRCERTIFSER, C.DATAPRIMIRE, NSER.DATAPROD, C.PROVENIENTA, CT.DEN_TARA, C.OBS OBSCERTIF ';
  END IF;

  sFiltruDoc := '';
  sFiltruDocM := '';
  if not current_setting('PKG_LIST_SELECTGEST.bAllTipDoc', TRUE)::NUMERIC = 1 THEN
    sFiltruDoc := ' and n.tipnir in ('||current_setting('PKG_LIST_SELECTGEST.bDocs', TRUE)||') ';
    sFiltruDocM := ' and i.tipdoc in ('||current_setting('PKG_LIST_SELECTGEST.bDocs', TRUE)||') ';
  end if;

  IF vDupaData AND vDataDoc AND g_data1 = g_data2 THEN
    sFiltruT := ' AND t.datadoc = To_Date(''' || COALESCE(g_data1,'') || ''',''dd.mm.yyyy'')';
    sFiltruI := ' AND i.datadoc = To_Date(''' || COALESCE(g_data1,'') || ''',''dd.mm.yyyy'')';
  ELSIF vDupaData AND vDataDoc THEN
    sFiltruT := ' AND t.datadoc between To_Date(''' || COALESCE(g_data1,'') || ''',''dd.mm.yyyy'') and
      To_Date(''' || COALESCE(g_data2,'') || ''',''dd.mm.yyyy'')';
    sFiltruI := ' AND i.datadoc between To_Date(''' || COALESCE(g_data1,'') || ''',''dd.mm.yyyy'') and To_Date(''' || COALESCE(g_data2,'') || ''',''dd.mm.yyyy'')';
  ELSIF vDupaData AND g_data1 = g_data2 THEN
    sFiltruN := '
    AND n.datanir = To_Date('''||coalesce(g_data1,'')||''',''dd.mm.yyyy'')';
    sFiltruL := '
    AND l.datalivr = To_Date('''||coalesce(g_data1, '')||''',''dd.mm.yyyy'')';
  ELSIF vDupaData THEN
    sFiltruN := '
    AND n.datanir between To_Date('''||coalesce(g_data1, '')||''',''dd.mm.yyyy'') and To_Date('''||coalesce(g_data2, '')||''',''dd.mm.yyyy'')';
    sFiltruL := '
    AND l.datalivr between To_Date('''||coalesce(g_data1, '')||''',''dd.mm.yyyy'') and To_Date('''||coalesce(g_data2, '')||''',''dd.mm.yyyy'')';
  ELSIF vLunaAnIni = vLunaAnFin THEN
    sFiltruT := '
    AND T.AN*12+T.LUNA = '||COALESCE(vLunaAnIni::varchar,'');
    sFiltruI := '
    AND I.AN*12+I.LUNA = '||COALESCE(vLunaAnIni::varchar,'');
  ELSE
    sFiltruT := ' AND T.AN*12+T.LUNA BETWEEN ' || COALESCE(vLunaAnIni::varchar,'') || ' AND ' || COALESCE(vLunaAnFin::varchar,'');
    sFiltruI := ' AND I.AN*12+I.LUNA BETWEEN ' || COALESCE(vLunaAnIni::varchar,'') || ' AND ' || COALESCE(vLunaAnFin::varchar,'');
  END IF;

  IF current_setting('PKG_LIST_SELECTGEST.vAllGest', true)::NUMERIC = 0 THEN
    sFiltruN := COALESCE(sFiltruN,'') || ' AND N.GEST::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'')';
    sFiltruL := COALESCE(sFiltruL,'') || ' AND N.GEST::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'')';
  END IF;

  sOperat := '';
  IF current_setting('pkg_list_selectgest.bExtra2', TRUE)::numeric = 0 THEN
    sOperat := ' AND N.OPERAT = 1 ';
  END IF;

  sInsTmp := 'INSERT INTO TMP_LST_RECEPTII (
       coddoc, tipdoc, prefixdoc, nrdoc, datadoc, codnirstoc, codnirser, userid,
       codnir, tipnir, codintr, codtransf, codies, carnetnir, nrnir, datanir, gest, den_gest, codclaseg,
       codlocatie, codumnir, cantnir, cantfurn, cantum1, cantum2, tg, pumaximal, codobiect, codioart, pret, adaos, tva,
       tipserie, procentadaos, supliment, serielot, codintr1, codtransf1, coddvi1, furn, dataachiz,
       aretvaneex, difpret, cont, codtva, proctva,
       codarticol, codclasea, codum1, codum2, clasastatist, an, luna, operat)';

  sSelTmpT := '
     SELECT
       t.codtransf coddoc, t.tipdoc, t.prefixdoc, t.nrdoc, t.datadoc, ns.codnirstoc, null::numeric codnirser, t.userid,
       n.codnir, n.tipnir, n.codintr, n.codtransf, n.codies, n.carnetnir, n.nrnir, n.datanir, n.gest, ng.den_gest, ng.codclasa codclaseg,
       ns.codlocatie, ns.umsec codumnir, ns.cantnir, ns.cantfurn, ns.cantum1, ns.cantum2, ns.tg, ns.pumaximal, ns.codobiect, ns.codioart, ns.pret, ns.adaos, ns.tva,
       ns.tipserie, ns.procentadaos, ns.supliment, ns.serielot, ns.codintr1, ns.codtransf1, ns.coddvi1, ns.furn, ns.dataachiz,
       io1.aretvaneex, io1.difpret, io1.cont, a1.codtva, t1.procent proctva,
       a.codarticol, a.clasa codclasea, a.um1 codum1, a.um2 codum2, a.clasastatist, t.an, t.luna,
       case when n.operat = 1 then ''DA'' else ''NU'' end
     FROM TRANSF T
        INNER JOIN NIR            N   ON N.CODTRANSF   = T.CODTRANSF    AND N.TIPNIR = T.TIPDOC
        INNER JOIN NIRSTOC        NS  ON NS.CODNIR     = N.CODNIR
        INNER JOIN NGEST          NG  ON NG.CODGEST    = N.GEST
        INNER JOIN NARTOBJ        OBJ ON OBJ.CODOBIECT = NS.CODOBIECT
        INNER JOIN NART           A   ON A.CODARTICOL  = OBJ.CODARTICOL
        LEFT  JOIN NART1          A1  ON A1.CODARTICOL = OBJ.CODARTICOL AND T.AN*12+T.LUNA BETWEEN A1.ALSTART AND A1.ALSTOP
        LEFT  JOIN IOART1         IO1 ON IO1.CODIOART  = NS.CODIOART    AND T.AN*12+T.LUNA BETWEEN IO1.ALSTART AND IO1.ALSTOP
        LEFT  JOIN NTVA1          T1  ON T1.CODTVA     = A1.CODTVA      AND T.AN*12+T.LUNA BETWEEN T1.ALSTART AND T1.ALSTOP
      WHERE T.TIPDOC = 12 AND T.OPERAT = 1 AND T.ANULAT = 0
        AND N.TIPNIR = 12 '||sOperat||' AND N.ANULAT = 0
        AND N.CODTRANSF IS NOT NULL ' || COALESCE(sFiltruDoc, '') || COALESCE(sFiltruT,'') || COALESCE(sFiltruN,'') ||
          coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'T',NULL,NULL,NULL)),'') ||
          coalesce((SELECT PKG_LIST_BASE_UTILS_COND_USERID.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_USERID(NULL,'T',NULL,NULL)),'');

  sSelTmpI := '
      SELECT
        i.codintr coddoc, i.tipdoc, i.prefixdoc, i.nrdoc, i.datadoc, ns.codnirstoc, null::numeric codnirser, i.userid,
        n.codnir, n.tipnir, n.codintr, n.codtransf, n.codies, n.carnetnir, n.nrnir, n.datanir, n.gest, ng.den_gest, ng.codclasa codclaseg,
        ns.codlocatie, ns.umsec codumnir, ns.cantnir, ns.cantfurn, ns.cantum1, ns.cantum2, ns.tg, ns.pumaximal, ns.codobiect, ns.codioart, ns.pret, ns.adaos, ns.tva,
        ns.tipserie, ns.procentadaos, ns.supliment, ns.serielot, ns.codintr1, ns.codtransf1, ns.coddvi1, ns.furn, ns.dataachiz,
        io1.aretvaneex, io1.difpret, io1.cont, a1.codtva, t1.procent proctva,
        a.codarticol, a.clasa codclasea, a.um1 codum1, a.um2 codum2, a.clasastatist, i.an, i.luna, case when n.operat = 1 then ''DA'' else ''NU'' end
      FROM INTRARI I
        INNER JOIN NIR            N   ON N.CODINTR     = I.CODINTR      AND N.TIPNIR = I.TIPDOC
        INNER JOIN NIRSTOC        NS  ON NS.CODNIR     = N.CODNIR
        INNER JOIN NGEST          NG  ON NG.CODGEST    = N.GEST
        INNER JOIN NARTOBJ        OBJ ON OBJ.CODOBIECT = NS.CODOBIECT
        INNER JOIN NART           A   ON A.CODARTICOL  = OBJ.CODARTICOL
        LEFT  JOIN NART1          A1  ON A1.CODARTICOL = OBJ.CODARTICOL AND I.AN*12+I.LUNA BETWEEN A1.ALSTART AND A1.ALSTOP
        LEFT  JOIN IOART1         IO1 ON IO1.CODIOART  = NS.CODIOART    AND I.AN*12+I.LUNA BETWEEN IO1.ALSTART AND IO1.ALSTOP
        LEFT  JOIN NTVA1          T1  ON T1.CODTVA     = A1.CODTVA      AND I.AN*12+I.LUNA BETWEEN T1.ALSTART AND T1.ALSTOP
      WHERE I.OPERAT = 1 AND I.ANULAT = 0
        AND N.OPERAT = 1 AND N.ANULAT = 0
        AND N.CODINTR IS NOT NULL
        AND N.TIPNIR BETWEEN 1 AND 9' || COALESCE(sFiltruDoc, '') || COALESCE(sFiltruI,'') || COALESCE(sFiltruN,'') || COALESCE((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL)),'') ||
          COALESCE((SELECT PKG_LIST_BASE_UTILS_COND_USERID.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_USERID(NULL,'I',NULL,NULL)),'');

  sSelTmpL := '
      SELECT
        i.codintr coddoc, i.tipdoc, i.prefixdoc, i.nrdoc, i.datadoc, ns.codnirstoc' || COALESCE(sCodNirSerL, ',NULL::numeric codnirser') || ', i.userid,
        l.codlivr codnir, l.tiplivr tipnir, l.codintr, 0 codtransf, 0 codies, l.carnetlivr carnetnir, l.nrlivr nrnir, l.datalivr datanir, n.gest, ng.den_gest, ng.codclasa codclaseg,
        ns.codlocatie, ns.umsec codumnir, -SUM(l1.cant) cantnir, -SUM(l1.cant) cantfurn, -SUM(l1.cantum1) cantum1, -SUM(l1.cantum2) cantum2, ns.tg, ns.pumaximal, ns.codobiect, ns.codioart, ns.pret, ns.adaos, ns.tva,
        ns.tipserie, ns.procentadaos, ns.supliment, ns.serielot, l1.codintr1, 0 codtransf1, l1.coddvi1, ns.furn, ns.dataachiz,
        io1.aretvaneex, io1.difpret, io1.cont, a1.codtva, t1.procent proctva,
        a.codarticol, a.clasa codclasea, a.um1 codum1, a.um2 codum2, a.clasastatist, i.an, i.luna, ''DA''
      FROM INTRARI I
        INNER JOIN LIVR           L   ON L.CODINTR     = I.CODINTR      AND L.TIPLIVR = I.TIPDOC
        INNER JOIN LIVR1          L1  ON L1.CODLIVR    = L.CODLIVR
        INNER JOIN INTRARI1       I1  ON I1.CODINTR1   = L1.CODINTR1    AND I1.CODINTR = I.CODINTR
        INNER JOIN NIRSTOC        NS  ON NS.CODNIRSTOC = L1.CODNIRSTOC
        INNER JOIN NIR            N   ON N.CODNIR      = NS.CODNIR
        INNER JOIN NGEST          NG  ON NG.CODGEST    = N.GEST
        INNER JOIN NARTOBJ        OBJ ON OBJ.CODOBIECT = I1.CODOBIECT
        INNER JOIN NART           A   ON A.CODARTICOL  = OBJ.CODARTICOL
        LEFT  JOIN NART1          A1  ON A1.CODARTICOL = OBJ.CODARTICOL AND I.AN*12+I.LUNA BETWEEN A1.ALSTART AND A1.ALSTOP
        LEFT  JOIN IOART1         IO1 ON IO1.CODIOART  = NS.CODIOART    AND I.AN*12+I.LUNA BETWEEN IO1.ALSTART AND IO1.ALSTOP
        LEFT  JOIN NTVA1          T1  ON T1.CODTVA     = A1.CODTVA      AND I.AN*12+I.LUNA BETWEEN T1.ALSTART AND T1.ALSTOP
      WHERE I.OPERAT = 1 AND I.ANULAT = 0 AND L.OPERAT = 1 AND I1.CANT &lt; 0 '
      || COALESCE(sFiltruDocM, '')
      || COALESCE(sFiltruI, '')
      || COALESCE(sFiltruL, '')
      || COALESCE((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL)),'')
      || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_USERID.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_USERID(NULL,'I',NULL,NULL)),'') || '
  GROUP BY
    i.codintr, i.tipdoc, i.prefixdoc, i.nrdoc, i.datadoc, i.userid, l.codlivr, l.tiplivr, l.codintr, l.carnetlivr, l.nrlivr, l.datalivr,
    ns.codnirstoc'||COALESCE(sCodNirSerL, '')||',ns.codlocatie, ns.umsec, ns.tg, ns.pumaximal, ns.codobiect, ns.codioart, ns.pret, ns.adaos, ns.tva,
    ns.tipserie, ns.procentadaos, ns.supliment, ns.serielot, l1.codintr1, l1.coddvi1, ns.furn, ns.dataachiz, n.gest, ng.den_gest, ng.codclasa,
    io1.aretvaneex, io1.difpret, io1.cont, a1.codtva, t1.procent, a.codarticol, a.clasa, a.um1, a.um2, a.clasastatist, i.an, i.luna
  union all
  SELECT
    i.codintr coddoc, i.tipdoc, i.prefixdoc, i.nrdoc, i.datadoc, ns.codnirstoc'|| COALESCE(sCodNirSerL,',NULL::numeric codnirser') ||', i.userid,
    l.codlivr codnir, l.tiplivr tipnir, l.codintr, 0 codtransf, 0 codies, l.carnetlivr carnetnir, l.nrlivr nrnir, l.datalivr datanir, n.gest, ng.den_gest, ng.codclasa codclaseg,
    ns.codlocatie, ns.umsec codumnir, -SUM(l1.cant) cantnir, -SUM(l1.cant) cantfurn, -SUM(l1.cantum1) cantum1, -SUM(l1.cantum2) cantum2, ns.tg, ns.pumaximal, ns.codobiect, ns.codioart, ns.pret, ns.adaos, ns.tva,
    ns.tipserie, ns.procentadaos, ns.supliment, ns.serielot, l1.codintr1, 0 codtransf1, l1.coddvi1, ns.furn, ns.dataachiz,
    io1.aretvaneex, io1.difpret, io1.cont, a1.codtva, t1.procent proctva,
    a.codarticol, a.clasa codclasea, a.um1 codum1, a.um2 codum2, a.clasastatist, i.an, i.luna, ''DA''
  FROM INTRARI I
    INNER JOIN LIVR L ON L.CODINTR = I.CODINTR AND L.TIPLIVR = I.TIPDOC
    INNER JOIN LIVR1 L1 ON L1.CODLIVR = L.CODLIVR
    INNER JOIN DVI D ON D.CODINTR = I.CODINTR
    INNER JOIN DVI1 D1 ON D1.CODDVI1 = L1.CODDVI1 AND D1.CODDVI = D.CODDVI
    INNER JOIN NIRSTOC NS ON NS.CODNIRSTOC = L1.CODNIRSTOC
    INNER JOIN NIR N ON N.CODNIR = NS.CODNIR
    INNER JOIN NGEST NG ON NG.CODGEST = N.GEST
    INNER JOIN NARTOBJ OBJ ON OBJ.CODOBIECT = D1.CODOBIECT
    INNER JOIN NART A ON A.CODARTICOL = OBJ.CODARTICOL
    LEFT JOIN NART1 A1 ON A1.CODARTICOL = OBJ.CODARTICOL AND I.AN*12+I.LUNA BETWEEN A1.ALSTART AND A1.ALSTOP
    LEFT JOIN IOART1 IO1 ON IO1.CODIOART = NS.CODIOART AND I.AN*12+I.LUNA BETWEEN IO1.ALSTART AND IO1.ALSTOP
    LEFT JOIN NTVA1 T1 ON T1.CODTVA = A1.CODTVA AND I.AN*12+I.LUNA BETWEEN T1.ALSTART AND T1.ALSTOP
  WHERE I.OPERAT = 1 AND I.ANULAT = 0 AND L.OPERAT = 1 AND D1.CANT &lt; 0 '
        || COALESCE(sFiltruDoc, '')
        || COALESCE(sFiltruI, '')
        || COALESCE(sFiltruL, '')
        || COALESCE((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL)),'')
        || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_USERID.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_USERID(NULL,'I',NULL,NULL)),'') || '
      GROUP BY
        i.codintr, i.tipdoc, i.prefixdoc, i.nrdoc, i.datadoc, i.userid, l.codlivr, l.tiplivr, l.codintr, l.carnetlivr, l.nrlivr, l.datalivr,
        ns.codnirstoc' || COALESCE(sCodNirSerL::varchar ,'') || ',ns.codlocatie, ns.umsec, ns.tg, ns.pumaximal, ns.codobiect, ns.codioart, ns.pret, ns.adaos, ns.tva,
        ns.tipserie, ns.procentadaos, ns.supliment, ns.serielot, l1.codintr1, l1.coddvi1, ns.furn, ns.dataachiz, n.gest, ng.den_gest, ng.codclasa,
        io1.aretvaneex, io1.difpret, io1.cont, a1.codtva, t1.procent, a.codarticol, a.clasa, a.um1, a.um2, a.clasastatist';

  sInsert := 'INSERT INTO ' || tmpName || '(
        NAV_CODDOC,NAV_TIPDOC,NAV_NIRSTOC,OPERATOR,
        NRNIR,DATANIR,GESTIUNE,LOCATIE,UMSEC,ARTICOL,PRET,
        ADAOS,
        TVA_NIR,
        CONT,PROC_TVA,
        PU,TVA_INTR,
        DATADOC,NRDOC,PREFIXDOC,STIPDOC,PARTENER, UMDOC,
        ValIntr,
        ValNIR,
        ValAdaos,
        VALINTRTVA,
        ValNIRTVA,
        procadaos,
        CARNETNIR,DEN_IOART,CODINTERN,CODEXTERN,CODVAMAL,MASA,VOLUM,
        AdaosFurn,
        AdaosMaximal,
        pumaximal,nrcertif,producator,CLASA_ART, CLASA_PART,CLASA_GEST,tipserie,UM_ALT1,UM_ALT2,CANTUM1, CANTUM2,
        supliment,serielot,pretachiznir,valachiznir,procadaosnir,DocNir,Document,MONDOC,CURSDOC,CLASAS,PRETFARATVA,
        NRDVI,DATADVI,FURNIZOR,CMDFURN,
        ANDOC,LUNADOC,LUNA,
        CANT,CANTNIR,CANTFACT,
        TG,SERIE,CANTSER,OBSSER,NRCERTIFSER,DATAPRIMIRE,DATAPROD,PROVENIENTA,DEN_TARA,OBSCERTIF' || coalesce(sInsertDC,'') || gUserFields || ')';

  sSelect := '
      SELECT
        R.CODDOC NAV_CODDOC, R.TIPDOC NAV_TIPDOC, R.CODNIRSTOC NAV_NIRSTOC, U.USERNAME AS OPERATOR,
        R.NRNIR, R.DATANIR, R.DEN_GEST GESTIUNE, COALESCE(NLOC.DENUMIRE,''...'') LOCATIE,
        COALESCE(umnir.den_um1,''nedef.'') UMSEC, COALESCE(obj.denumire,''nedef.'') ARTICOL, r.pret*umnir.paritate PRET,
        CASE WHEN r.aretvaneex = 1 THEN r.adaos - ((r.pret*r.proctva)/(Case When 100+r.proctva=0 then 1 else 100+r.proctva end)) ELSE r.adaos END * umnir.paritate ADAOS,
        CASE WHEN r.aretvaneex = 1 THEN (r.pret*r.proctva)*r.cantnir/(Case When 100+r.proctva=0 then 1 else 100+r.proctva end) ELSE 0 END TVA_NIR,
        ncstoc.simbol CONT, r.proctva PROC_TVA,
        CASE WHEN R.TIPNIR = 3 AND i1.cant &lt;&gt; 0 THEN i1.pu-(i1.tva/i1.cant) WHEN R.TIPNIR = 12 THEN TR1.PU WHEN R.TIPNIR = 5 THEN I1.PU ELSE I1.PU END * umdoc.paritate PU,
        CASE WHEN R.tipnir = 12 AND tr1.cant &lt;&gt; 0 THEN tr1.tva*r.cantfurn/tr1.cant WHEN NOT R.tipnir IN (5,12) AND i1.cant &lt;&gt; 0 THEN i1.tva*r.cantfurn/i1.cant ELSE 0 END TVA_INTR,
        r.datadoc, r.nrdoc, r.prefixdoc, pkg_list_base_utils_Decode_tipdoc_scurt(r.tipdoc) STIPDOC,
        (Case When r.tipdoc=6 then nsub.den_subunit When r.tipdoc=7 then gestprod.den_gest else np.den_part end) DEN_PART, umdoc.den_um1 UMDOC,
        (Case  When r.tipnir=3 then i1.pu-(Case  When i1.cant=0 then 0 else i1.tva/i1.cant end) When r.tipnir=12 then tr1.pu else i1.pu end) * r.cantfurn  ValIntr,
        r.pret * r.cantnir - (CASE WHEN r.aretvaneex = 1 THEN (r.pret*r.proctva)*r.cantnir/(100+r.proctva) ELSE 0 END) ValNir,
        CASE WHEN r.aretvaneex = 1 THEN r.adaos -((r.pret*r.proctva)/(Case  When 100+r.proctva=0 then 1 else 100+r.proctva end)) ELSE r.adaos END * r.cantnir ValAdaos,
        (Case When R.tipnir=12 then tr1.pu else i1.pu end)  * r.cantfurn + CASE WHEN COALESCE(i1.pu*i1.cant,0) &lt;&gt; 0 and R.tipnir not in(3,5) then i1.tva/(i1.pu*i1.cant) *
          (Case When R.tipnir=12 then tr1.pu else i1.pu end) * r.cantfurn ELSE 0 END VALINTRTVA,
        r.cantnir * r.pret ValNIRTVA,
        CASE
          WHEN r.difpret = 1 THEN round(100*
            CASE
              WHEN r.aretvaneex = 0 THEN r.adaos/(Case When r.pret-r.adaos=0 then 1 else r.pret-r.adaos end)
              WHEN r.aretvaneex = 1 THEN (r.pret/(1+(r.proctva/100))-(r.pret - r.adaos))/(Case  When (r.pret-r.adaos)=0 then 1 else (r.pret-r.adaos) end)
              WHEN r.aretvaneex = 2 THEN ((r.pret-(r.pret - (Case  When r.tipnir=5 then dvi1.pretimport When r.tipnir=12 then tr1.pu else i1.pu end))* 100/
                (Case  When 100+r.proctva=0 then 1 else 100+r.proctva end)) - (Case  When R.tipnir=5 then dvi1.pretimport else i1.pu end)) /
              (Case  When ( (Case When R.tipnir=5 then dvi1.pretimport else i1.pu end))=0 then 1 else ((Case  When R.tipnir=5 then dvi1.pretimport else i1.pu end)) end)
            END,2)
          ELSE 0
        END procadaos,
        CARNET.DENUMIRE CARNETNIR, IO.DEN_IOART, OBJ.CODINTERN, OBJ.CODEXTERN, OBJ.CODVAMAL, OBJ.MASA, OBJ.VOLUM ,
        CASE WHEN r.pret = 0 THEN 0 ELSE (1-( (r.pret - r.adaos)/( r.pret -
          (Case  When r.aretvaneex=1 then (r.pret*r.proctva)/(Case  When 100+r.proctva=0 then 1 else 100+r.proctva end) else 0 end) ) ) )*100 END AdaosFurn,
        CASE WHEN r.pret = 0 THEN 0 ELSE (((r.pumaximal * 100 / (Case  When 100+r.proctva=0 then 1 else 100+r.proctva end)) - ( r.pret-
          (Case  When r.aretvaneex=1 then (r.pret*r.proctva)/(Case When 100+r.proctva=0 then 1 else 100+r.proctva end) else 0 end)) ) / ( r.pret -
          (Case  When r.aretvaneex=1 then (r.pret*r.proctva)/(Case When 100+r.proctva=0 then 1 else 100+r.proctva end) else 0 end)) )*100 END AdaosMaximal,
         r.pumaximal, i1.NRCERTIF,prod.den_part producator,NCA.DEN_CLASEA, NCP.DEN_CLASEP, NCG.DEN_CLASEG,
         (Case  When r.TIPSERIE=0 then ''Fara serie'' When r.TIPSERIE=1 then ''Serie pe bucata'' When r.TIPSERIE=2 THEN ''Serie pe lot'' END) tipserie,
        UM1.DEN_UM UM_ALT1, UM2.DEN_UM UM_ALT2,' || coalesce(chr(13),'');
  IF current_setting('pkg_list_selectgest.bAduSerii', TRUE)::numeric = 1 THEN
    sSelect := coalesce(sSelect,'') || 'case when NSER.CODNIRSER IS NULL THEN R.CANTUM1 ELSE NSER.CANTUM1 END,CASE WHEN NSER.CODNIRSER IS NULL THEN R.CANTUM2 ELSE NSER.CANTUM2 END,' || coalesce(chr(13),'');
  ELSE
    sSelect := coalesce(sSelect,'') || 'R.CANTUM1,R.CANTUM2,' || coalesce(chr(13),'');
  END IF;
  sSelect := coalesce(sSelect,'') || 'r.supliment, r.serielot,
        (r.pret- r.adaos ) * umnir.PARITATE, (r.pret - r.adaos )*r.cantfurn ,r.procentadaos ,
        ''NIR''||R.nrnir||''/''|| to_char(R.datanir,''dd.mm.yyyy'') DocNir,
        (Case When R.tipnir=12 then coalesce(tr.prefixdoc, '''') else coalesce(i.prefixdoc, '''') end)|| (Case  When R.tipnir=12 then tr.nrdoc else i.nrdoc end) ||''/''
          ||to_char((Case  When R.tipnir=12 then tr.datadoc else i.datadoc end),''dd.mm.yyyy'')||''-''
          ||(Case  When R.tipnir=6 then NSUB.DEN_SUBUNIT When R.tipnir=7 then GESTPROD.DEN_GEST else coalesce(np.den_part, '''') end) AS Document,
        MONDOC.DEN_MONEDA MONDOC,COALESCE(I.CURS,1) CURSDOC,NCLS.DEN_CLASEAS,
        (r.pret - (CASE WHEN r.aretvaneex = 1 THEN (r.pret*r.proctva)/(100+r.proctva) ELSE 0 END)) * umdoc.paritate pretfaratva,
        DVI.NRDOC, DVI.DATADOC,FURN.DEN_PART,CF.PREFIXDOC||CF.NRDOC||''/''||TO_CHAR(CF.DATADOC,''dd.mm.yyyy'' ),
        COALESCE(i.an,tr.an) andoc, COALESCE(i.luna,tr.luna) lunadoc, to_char(COALESCE(i.an,tr.an),''fm0000'')||''.''||to_char(COALESCE(i.luna,tr.luna),''fm00'')||''.''||pkg_list_base_utils_Decode_luna(COALESCE(i.luna,tr.luna)) luna';
  sFrom := '
      FROM TMP_LST_RECEPTII R
        LEFT JOIN NARTOBJ           OBJ      ON OBJ.CODOBIECT     = R.CODOBIECT
        LEFT JOIN IOART             IO       ON IO.CODIOART       = R.CODIOART
        LEFT JOIN NCONT             NCSTOC   ON NCSTOC.CODCONT     = R.CONT
        LEFT JOIN DOCCARNETE        CARNET   ON CARNET.CODCARNET   = R.CARNETNIR
        LEFT JOIN NUM1              UMNIR    ON UMNIR.CODUM1       = R.CODUMNIR
        LEFT JOIN INTRARI           I        ON I.CODINTR         = R.CODINTR
        LEFT JOIN NPART             NP       ON NP.CODPART         = I.PARTENER
        LEFT JOIN DVI1                       ON DVI1.CODDVI1       = R.CODDVI1
        LEFT JOIN INTRARI1          I1       ON I1.CODINTR1       = (Case When R.TIPNIR=5 then DVI1.CODINTR1 else R.CODINTR1 end) AND I1.CODINTR = I.CODINTR
        LEFT JOIN TRANSF            TR       ON TR.CODTRANSF       = R.CODTRANSF
        LEFT JOIN TRANSF1           TR1      ON TR1.CODTRANSF1     = R.CODTRANSF1
        LEFT JOIN NLOCATII          NLOC     ON NLOC.CODLOCATIE   = R.CODLOCATIE
        LEFT JOIN NUM1              UMDOC    ON UMDOC.CODUM1       = COALESCE(DVI1.UMSEC,TR1.UMSEC,I1.UMSEC)
        LEFT JOIN NSUBUNIT          NSUB     ON NSUB.CODSUBUNIT   = I.CODSUBUNIT
        LEFT JOIN NGEST             GESTPROD ON GESTPROD.CODGEST   = I.CODGESTPROD
        LEFT JOIN NPART             PROD     ON OBJ.CODPRODUCATOR = PROD.CODPART
        LEFT JOIN NCLASEA           NCA      ON NCA.CODCLASEA     = R.CODCLASEA
        LEFT JOIN NCLASEP           NCP      ON NCP.CODCLASEP     = NP.CODCLASA
        LEFT JOIN NCLASEG           NCG      ON NCG.CODCLASEG     = R.CODCLASEG
        LEFT JOIN TMP_MANEVRA_SERII TMP      ON TMP.CODNIRSTOC     = R.CODNIRSTOC
        LEFT JOIN NUM               UM1      ON UM1.CODUM         = R.CODUM1
        LEFT JOIN NUM               UM2      ON UM2.CODUM         = R.CODUM2
        LEFT JOIN NMONEDE           MONDOC   ON MONDOC.CODMONEDA   = COALESCE(I.MONEDA,0)
        LEFT JOIN NCLASEAS          NCLS     ON NCLS.CODCLASEAS   = R.CLASASTATIST
        LEFT JOIN DVI               DVI      ON DVI.CODDVI         = DVI1.CODDVI
        LEFT JOIN NPART             FURN     ON FURN.CODPART       = r.furn
        LEFT JOIN TMP_UTILIZATOR    U        ON U.CODUTILIZATOR   = R.USERID
        LEFT JOIN INTRLINK          IL       ON IL.CODINTR1       = I1.CODINTR1
        LEFT JOIN COMANDA1          CF1      ON CF1.CODCOMANDA1   = IL.CODLINIECOMANDA
        LEFT JOIN COMANDA           CF       ON CF.CODCOMANDA     = CF1.CODCOMANDA ' || COALESCE(sJoinDC,'') || gSuplJoins;

  CALL PRC_AL_CHECK('NART1');
  CALL PRC_AL_CHECK('NTVA1');
  CALL PRC_AL_CHECK('IOART1');

  DELETE FROM TMP_LST_RECEPTII;

  PERFORM LIST_EXECUTE_IMMEDIATE(COALESCE(sInsTmp,'') || COALESCE(sSelTmpT,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(COALESCE(sInsert,'') || COALESCE(sSelect,'') || COALESCE(vColSeriiN,'') || COALESCE(sSelectDCN,'') || gUserAlias || COALESCE(sFrom,'') || COALESCE(vJoinSeriiN,''), aListID, aListVer);

  DELETE FROM TMP_LST_RECEPTII;

  PERFORM LIST_EXECUTE_IMMEDIATE(COALESCE(sInsTmp,'') || coalesce(sSelTmpI,''), aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(COALESCE(sInsert,'') || coalesce(sSelect,'') || coalesce(vColSeriiN,'') || COALESCE(sSelectDCN,'') || gUserAlias || COALESCE(sFrom,'') || COALESCE(vJoinSeriiN,''), aListID, aListVer);

  DELETE FROM TMP_LST_RECEPTII;

  IF current_setting('pkg_list_selectgest.bExtra1', TRUE)::numeric = 1 THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(COALESCE(sInsTmp,'') || COALESCE(sSelTmpL,''), aListID, aListVer);
    PERFORM LIST_EXECUTE_IMMEDIATE(COALESCE(sInsert,'') || COALESCE(sSelect,'') || COALESCE(vColSeriiL,'') || COALESCE(sSelectDCL,'') || gUserAlias || COALESCE(sFrom,'') || COALESCE(vJoinSeriiL,''), aListID, aListVer);
    DELETE FROM TMP_LST_RECEPTII;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regjurnal_isindex</obj_name>
  <obj_hashval>a80451d786187643e1ce4dd6461c35a1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_isindex()
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
begin
  return current_setting('PKG_LIST_BASE_REGJURNAL.p_Index', true);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regjurnal_plan</obj_name>
  <obj_hashval>178807c89a41e106dff2a8492f7d75f2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_plan(INOUT wme_result numeric, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
WME_Result := current_setting('PKG_LIST_BASE_REGJURNAL.p_Plan')::numeric ;
RETURN;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regjurnal_setgnullalias</obj_name>
  <obj_hashval>346d0c129978d93f192dc8141b0bf282</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regjurnal_setgnullalias(agnullalias character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_REGJURNAL.gNullAlias',agNullAlias,false);
end;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_regreev_setjoinuri</obj_name>
  <obj_hashval>9fbdd3c676788c222140315cce3a6a53</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_regreev_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_REGREEV.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rezdoc_setjoinuri</obj_name>
  <obj_hashval>44801188f6c5bba75ac1fc16acead822</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rezdoc_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_REZDOC.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitfin_getcod</obj_name>
  <obj_hashval>1f69b30ef53ac22ad666c07cdd3e30e5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitfin_getcod()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  RETURN current_setting('PKG_LIST_BASE_SITFIN.p_CodSitFin', true)::numeric;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitfin_inchid665cu473</obj_name>
  <obj_hashval>5cecb01d6db2c43dbf4eb7c01cd38888</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitfin_inchid665cu473()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSelect varchar := '';
  vRez     numeric;
BEGIN
  --Adina 15.10.2020
  vRez := 0;

  sSelect := '
  WITH
    r as (
      SELECT
        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, rs.subunitatea, r.an, r.luna
      FROM ncontrul r
        INNER JOIN ncontrulsub rs ON rs.codcontrul = r.codcontrul
      WHERE r.an*12+r.luna = ' || coalesce(getANLUCRU()::varchar,'') || '*12+1 AND r.luna &gt; 1),
    n AS (
--          SELECT c.codcont
--          FROM ncont c
--          WHERE EXISTS (SELECT 1 FROM ncont1 c1 WHERE c1.codcont = c.codcont AND c1.anstart*12+c1.lunastart &lt;= getANLUCRU()*12)
--          START WITH c.codcont IN (SELECT codcont from ncont where simbol = ''665'')
--          CONNECT BY PRIOR c.codcont = c.codparinte
          WITH RECURSIVE aa  AS(
            SELECT n.codcont, n.codparinte
            FROM ncont n
            where n.codcont IN (SELECT codcont from ncont where simbol = ''665'')
            UNION ALL
            SELECT o.codcont, o.codparinte
            FROM ncont O  inner join AA a ON a.codcont = o.codparinte
          )
          SELECT codcont FROM AA c WHERE EXISTS (SELECT 1 FROM ncont1 c1 WHERE c1.codcont = c.codcont AND c1.anstart*12+c1.lunastart &lt;= ' || coalesce(getANLUCRU()::varchar,'') || '*12)
         )
    select sum(coalesce(debit,0)) from (
    SELECT
      0 nav_coddoc, 0 nav_tipdoc, sc.codcont, 0 codcoresp,
      0 debit, 0 credit, 0 debitv, 0 creditv, 0 valoare, 0 valoarev,
      coalesce(s.soldid,0) - coalesce(s.soldic,0) sold, coalesce(s.soldvid,0) - coalesce(s.soldvic,0) soldv,
      coalesce(s.soldi_ifrs,0) ifrs,  coalesce(s.soldvi_ifrs,0) ifrsv, coalesce(s.soldi_ifrs,0) sold_ifrs, coalesce(s.soldvi_ifrs,0) sold_ifrsv,
      coalesce(s.soldi_grup,0) grup,  coalesce(s.soldvi_grup,0) grupv, coalesce(s.soldi_grup,0) sold_grup, coalesce(s.soldvi_grup,0) sold_grupv,
      ''Sold initial'' obs, null as document, to_date(''01.''||sc.luna||''.''||sc.an,''dd.mm.yyyy'')  datadoc, s.subunitatea, 0 gest, sc.an, sc.luna,
      -1 ordine,
      0 codcentru, 0 indexlocal
    FROM ncontsold sc
      INNER JOIN ncontsoldsub s ON s.codcontsold = sc.codcontsold
      INNER JOIN n              ON n.codcont     = sc.codcont
    WHERE sc.an * 12 + sc.luna = ' || coalesce(getANLUCRU()::varchar,'') || '*12+1
    UNION ALL
    SELECT
      0 nav_coddoc, 0 nav_tipdoc, r.codcont, 0 codcoresp,
      coalesce(r.rulajpd,0) debit, coalesce(r.rulajpc,0) credit, coalesce(r.rulajvpd,0) debitv, coalesce(r.rulajvpc,0) creditv, 0 valoare, 0 valoarev,
      coalesce(r.rulajpd,0) - coalesce(r.rulajpc,0) sold, coalesce(r.rulajvpd,0) - coalesce(r.rulajvpc,0) soldv,
      coalesce(r.rulajp_ifrs,0) ifrs, coalesce(r.rulajvp_ifrs,0) ifrsv, coalesce(r.rulajp_ifrs,0) sold_ifrs, coalesce(r.rulajvp_ifrs,0) sold_ifrsv,
      coalesce(r.rulajp_grup,0) grup, coalesce(r.rulajvp_grup,0) grupv, coalesce(r.rulajp_grup,0) sold_grup, coalesce(r.rulajvp_grup,0) sold_grupv,
      ''Rulaj precedent'' obs, null as document, 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 indexlocal
    FROM r
      INNER JOIN n ON n.codcont = r.codcont
    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.valoarev= 0 then  1 else j.valoare/j.valoarev end),0) grupv, coalesce(j.valoaregrup,0) sold_grup, coalesce(j.valoaregrup/(case when j.valoarev= 0 then 1 else j.valoare/j.valoarev end),0) sold_grupv,
      j.obs, j.document, j.datadoc, j.subunitatea, j.gest, j.an, j.luna,
      CASE
        WHEN j.tipdoc = 81                                       THEN 10000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''SINCRONIZARE%'') THEN 20000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''INCHIDERE%'')    THEN 30000000000000000000
        ELSE 0
      END + j.codjurnal ordine,
      j.codcentru, j.indexlocal
    FROM jurnal j
      INNER JOIN n ON n.codcont = j.contd
    WHERE j.an *12 + j.luna BETWEEN ' || coalesce(getANLUCRU()::varchar,'') || '*12+1 AND ' || coalesce(getANLUCRU()::varchar,'') || '*12+12  and j.contc in (select codcont from ncont where simbol like ''473.02%'')
    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.valoarev= 0 then 1 else j.valoare/j.valoarev end),0) grupv, -coalesce(j.valoaregrup,0) sold_grup, -coalesce(j.valoaregrup/(case when j.valoarev= 0 then 1 else j.valoare/j.valoarev end),0) sold_grupv,
      j.obs, j.document, j.datadoc, j.subunitatea, j.gest, j.an, j.luna,
      CASE
        WHEN j.tipdoc = 81                                       THEN 10000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''SINCRONIZARE%'') THEN 20000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''INCHIDERE%'')    THEN 30000000000000000000
        ELSE 0
      END + j.codjurnal ordine,
      j.codcentru, j.indexlocal
    FROM jurnal j
      INNER JOIN n ON n.codcont = j.contc
    WHERE j.an *12 + j.luna BETWEEN ' || coalesce(getANLUCRU()::varchar,'') || '*12+1 AND ' || coalesce(getANLUCRU()::varchar,'') || '*12+12  and j.contd in (select codcont from ncont where simbol like ''473.02%'')
    ) AA_PG';

  BEGIN
    EXECUTE sSelect INTO vRez;
  EXCEPTION WHEN others THEN
    vRez := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitoninv_umpletmp</obj_name>
  <obj_hashval>684bd72542d5609f0851ef66cca7c9a4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitoninv_umpletmp(ptotanul boolean)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsTMP    varchar;
  sAnLunaIni numeric;
  sAnIni     numeric;
  sCondTmp   varchar := (SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT (NULL,'I',NULL,NULL,NULL));
begin
  --Adina 18.12.2020 tichet 41648 - in Oracle ptotanul e default true
  --Bogdan 08.09.2020

  pTotAnul := coalesce(pTotAnul,true);  -- add 18.12.2020

  IF pTotAnul THEN
    sAnLunaIni := Trunc ( ( PKG_LIST_SELPARTART_AnLunaIni() - 1) / 12) * 12 + 1;
  ELSE
    sAnLunaIni := PKG_LIST_SELPARTART_AnLunaIni();
  END IF;

  sAnIni := Trunc ( ( PKG_LIST_SELPARTART_AnLunaIni() - 1) / 12);

  IF NOT (PKG_LIST_SELPARTART_IsAllPart()) THEN
    sCondTmp := coalesce (sCondTmp,'')
    || '  AND I.PARTENER IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPART'')';
  END IF;

  IF NOT ( PKG_LIST_SELPARTART_IsAllArt()) THEN
    sCondTmp := coalesce (sCondTmp,'')
    || ' AND I1A.CODOBIECT IN (SELECT VALOARE::numeric FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'')';
  END IF;

  sInsTMP := 'INSERT INTO  tmp_list_sitoninv (  codpart, codobiect, codcriteriu, codcont, subunitatea, proc, bazadisc, valdisc, valdiscant, valdiscfin, codmoneda )
         WITH recursive x AS
          (   SELECT i1a.codies1,
              i1d.codies1 codiesd,
              Row_NUMBER() OVER (PARTITION BY i1a.codies1 ORDER BY i1d.indexlocal) Idx,
              (CASE WHEN t.tip = 2 THEN i1a.pu    ELSE i1a.pu * i1a.cant END) pu,
              (CASE WHEN t.tip = 2 THEN i1a.cant ELSE 1 END)  cant,
              i1d.cant    proc,
              COALESCE (cd.codcriteriu,0)  CodCriteriu,
              COALESCE (cd.cumulat,0)      cumulat,
              CASE WHEN cd.codcriteriu IS NULL THEN COALESCE (i1d.ContDiscount,0) ELSE 0 END  ContDiscount,
              COALESCE (i.moneda,0)  codmoneda
            FROM iesiri                  i
              inner join iesiri1         i1d ON i1d.codies = i.codies AND i1d.tiplinie     IN (''G'',''T'')
              inner join iesiri1         i1a ON i1a.codies = i.codies AND i1a.tiplinie NOT IN (''G'',''T'') AND i1a.indexlocal &lt; i1d.indexlocal
              left join criteriidisc     cd  ON cd.codcriteriu = i1d.codcriteriu
              left join (
                    with recursive rec as(
                      select 1 as level
                      union all
                      select level+1
                      from rec
                      where level+1&lt;=' || coalesce ( ( PKG_LIST_SELPARTART_AnLunaFin() - sAnLunaIni) ::varchar,'') ||'
                    )
                    select level luna, COALESCE ((select wme_result from pkg_categconst_GetValConstanta (null,''ModAplicProcDisc'' ,0,'
                                        || coalesce (sAnLunaIni::VARCHAR,'') || '::numeric + level))::numeric ,1) Tip from rec
                    ) t ON t.luna = i.luna
            WHERE
              i.tipdoc IN (19,26)
              AND i.an  * 12 + i.luna BETWEEN '|| coalesce ( (sAnLunaIni) ::varchar,'')|| ' AND '|| coalesce ( ( PKG_LIST_SELPARTART_AnLunaFin()) ::varchar,'')
              || coalesce (sCondTmp,'')|| '
              AND
              CASE
                WHEN i1d.tiplinie &lt;&gt; ''G'' THEN 0
                WHEN (SELECT Max (x.indexlocal)
                      FROM iesiri1 x
                      WHERE
                        x.codies = i.codies
                        AND x.tiplinie NOT IN (''G'',''T'')
                        AND x.indexlocal &gt;= i1a.indexlocal
                        AND x.indexlocal &lt; i1d.indexlocal)
                  &gt; (SELECT Min (y.indexlocal)
                     FROM iesiri1 y
                     WHERE
                       y.codies = i.codies
                       AND y.tiplinie IN (''G'',''T'')
                       AND y.indexlocal &gt; i1a.indexlocal
                       AND y.indexlocal &lt;= i1d.indexlocal) THEN 1
                  ELSE 0
              END = 0
              AND I.OPERAT = 1
              AND COALESCE (I.ANULAT,0) = 0
            ORDER BY
              i.an * 12 + i.luna,
              i.codies,
              i1a.codies  ),
          y(
            codies1,
            codcriteriu,
            contdiscount,
            idx,
            proc,
            cumulat,
            bd,
            d,
            d0,
            d1,
            d2,
            codmoneda
          ) AS
          ( SELECT x.codies1,
              x.codcriteriu,
              x.contdiscount,
              x.idx,
              x.proc,
              x.cumulat,
              x.cant * x.pu                          bd,
              x.cant * Round (x.pu * x.proc / 100,2) d,
               (CASE WHEN x.cumulat = 0 THEN Round (x.pu * x.proc / 100,2) ELSE 0 END) d0,
               (CASE WHEN x.cumulat = 1 THEN Round (x.pu * x.proc / 100,2) ELSE 0 END) d1,
               (CASE WHEN x.cumulat = 2 THEN Round (x.pu * x.proc / 100,2) ELSE 0 END) d2,
              x.codmoneda
            FROM x
            WHERE idx = 1
            UNION ALL
            SELECT x.codies1,
              x.codcriteriu,
              x.contdiscount,
              x.idx,
              x.proc,
              x.cumulat,
              x.cant *  (case x.cumulat
                         when 0 then x.pu + y.d0 + y.d1 + y.d2
                         when 1 then x.pu
                         when 2 then x.pu + y.d0 + y.d1
                         else 0 end) bd,
              x.cant * (case x.cumulat
                         when 0 then Round ( (x.pu + y.d0 + y.d1 + y.d2) * x.proc / 100,2)
                         when 1 then Round (x.pu * x.proc / 100,2)
                         when 2 then Round ( (x.pu + y.d0 + y.d1) * x.proc / 100,2)
                         else 0 end) d,
              y.d0 +  (case when x.cumulat = 0 then Round ( (x.pu + y.d0 + y.d1 + y.d2) * x.proc / 100,2) else 0 end) d0,
              y.d1 +   (case when x.cumulat = 1 then Round (x.pu * x.proc / 100,2) else 0 end) d1,
              y.d2 +   (case when x.cumulat = 2 then Round ( (x.pu + y.d0 + y.d1) * x.proc / 100,2) else 0 end) d2,
              y.codmoneda
            FROM y
              INNER JOIN x ON x.codies1 = y.codies1 AND x.idx = y.idx + 1
          )
         SELECT i.partener,
          i1.codobiect,
          y.codcriteriu,
          y.contdiscount,
          i.subunitatea,
          y.proc,
          Sum (
            CASE
              WHEN i.luna &lt; '|| coalesce ( PKG_LIST_SELPARTART_AnLunaIni()::varchar ,'')|| ' THEN 0
              ELSE y.bd
            END)
          BazaDisc,
          Sum (
            CASE
              WHEN i.luna &lt; '|| coalesce ( PKG_LIST_SELPARTART_AnLunaIni()::varchar ,'')|| ' THEN 0
              ELSE y.d
            END)
                Disc,
          Sum (y.d) DiscAnt,
          Sum (
            CASE
              WHEN i.luna &lt;&gt; '|| coalesce ( PKG_LIST_SELPARTART_AnLunaFin()::varchar ,'')|| ' THEN 0
              ELSE y.d
            END)
          DiscFin,
          y.codmoneda
         FROM y
          left join iesiri1 i1 ON i1.codies1 = y.codies1
          left join iesiri  i  ON i.codies   = i1.codies
         GROUP BY
          i.partener,
          i1.codobiect,
          y.codcriteriu,
          y.contdiscount,
          i.subunitatea,
          y.proc,
          y.codmoneda';
  EXECUTE 'TRUNCATE TABLE tmp_list_sitoninv';
  PERFORM LIST_EXECUTE_IMMEDIATE (sInstmp, 0, 0);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_soldpartini_processlist</obj_name>
  <obj_hashval>28c59535ae97f3196cfe0dbcacceb21d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_soldpartini_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert    varchar := '';
  AnLunaIni  numeric;
  filtruPart varchar := '';
BEGIN
  --Adina 11 septembrie 2020
  SELECT aninitial * 12 + lunainitiala INTO AnLunaIni FROM firmaluni;

  filtruPart := ' ';

  IF  NOT pkg_list_selpart_IsAllPart() THEN
    filtruPart := '
      AND O.CODPART::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODPART'' ) ';
  END IF;

  sInsert := 'INSERT INTO ' || TMPNAME || '(
    DEN_PART,DATADOC,NRDOC,MONEDA,SIMBOL,TERMEN,DEN_GEST,
    SOLDLEI,SOLDVALUTA,PROVLEI,PROVVALUTA,
    DEN_SUBUNIT,DIN_CARE_TVA,CURS,AGENT)
  WITH crs_soldini AS (
    SELECT
      o.codpart, o.termen, o.codgest, o.semnificatie, o.icont, coalesce(o.coefprovizion,0) coefprovizion, coalesce(g.moneda,0) moneda,
      Coalesce(NULLIF(coalesce(g.curs,0),0),1) curs,
      COALESCE(dvi.datadoc, intr.datadoc, ies.datadoc, t1.datadoc, nc.datadoc, c.datadoc) datadoc,
      COALESCE(dvi.nrdoc, intr.nrdoc, ies.nrdoc, t1.nrdoc, nc.nrdoc, c.nrdoc) nrdoc,
      COALESCE(intr.subunitatea, ies.subunitatea, t.subunitatea, nc.subunitatea, c.subunitatea) subunitatea,
      COALESCE(ies.agent, t1.agent,t.agent,0) agent,
      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 = 120                                                                                      THEN -(OL.REST - coalesce(OL.RESTTVA, 0))
        WHEN O.SEMNIFICATIE = 200                                                                                      THEN  OL.REST
        WHEN O.SEMNIFICATIE = 240                  AND G.TIPDOC = 20                                                   THEN  OL.REST
        WHEN O.SEMNIFICATIE = 210                                                                                      THEN -(OL.REST - coalesce(OL.RESTTVA, 0))
        WHEN O.SEMNIFICATIE = 220                                                                                      THEN (OL.REST  - coalesce(OL.RESTTVA, 0))
        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, 25, 26, 27, 28, 29)  THEN -OL.REST
        WHEN O.SEMNIFICATIE IN (1200, 1201)        AND O.ICONT IN (3, 4, 7,10, 11, 12, 13, 14, 19, 30, 31, 32, 33, 34) THEN  OL.REST
        WHEN O.SEMNIFICATIE IN (1301, 1351, 1303)  AND O.ICONT IN (2, 5, 8, 9, 15, 18)                                 THEN -OL.REST
        WHEN O.SEMNIFICATIE IN (1301, 1351, 1303)  AND O.ICONT IN (3, 4, 6, 7, 10, 11, 12, 13, 14, 17)                 THEN  OL.REST
      END SOLD,
      CASE
        WHEN O.SEMNIFICATIE = 110         THEN coalesce(OL.RESTTVA, 0)
        WHEN O.SEMNIFICATIE = 120         THEN -coalesce(OL.RESTTVA, 0)
        WHEN O.SEMNIFICATIE = 210         THEN -coalesce(OL.RESTTVA, 0)
        WHEN O.SEMNIFICATIE = 220         THEN  coalesce(OL.RESTTVA, 0)
        WHEN O.SEMNIFICATIE IN (310, 330) THEN coalesce(OL.RESTTVA, 0)
        WHEN O.SEMNIFICATIE IN (410, 430) THEN -coalesce(OL.RESTTVA, 0)
        ELSE 0
      END TVA
    FROM OBLIGPIFLUNA OL
      INNER JOIN OBLIGPIF O    ON O.CODOBLIGPIF = OL.CODOBLIGPIF
      INNER JOIN GENERAL  G    ON G.CODGENERAL  = O.CODGENERAL
      LEFT  JOIN DVI           ON DVI.CODDVI    = G.CODDOC AND G.TIPDOC = 5 AND O.SEMNIFICATIE = 130
      LEFT  JOIN INTRARI  INTR ON INTR.CODINTR  = coalesce(DVI.CODINTR,G.CODDOC) AND INTR.TIPDOC = G.TIPDOC AND O.SEMNIFICATIE IN (100, 110, 120, 130, 140)
      LEFT  JOIN IESIRI   IES  ON IES.CODIES    = G.CODDOC AND IES.TIPDOC = G.TIPDOC AND O.SEMNIFICATIE IN (200, 210, 220, 240)
      LEFT  JOIN TREZOR1  T1   ON T1.CODTREZOR1 = G.CODDOC AND O.SEMNIFICATIE IN (310, 330, 410, 430)
      LEFT  JOIN TREZOR   T    ON T.CODTREZOR   = T1.CODTREZOR
      LEFT  JOIN NC1           ON NC1.CODNC1    = G.CODDOC AND O.SEMNIFICATIE IN (1200, 1201)
      LEFT  JOIN NC            ON NC.CODNC      = NC1.CODNC
      LEFT  JOIN COMPENS  C    ON C.CODCOMPENS  = G.CODDOC AND O.SEMNIFICATIE IN (1301, 1351, 1303)
    WHERE OL.REST &lt;&gt; 0
      AND O.SEMNIFICATIE IN (100, 110, 120, 130, 140, 200, 210, 220, 240, 310, 330, 410, 430, 1200, 1201, 1301, 1351, 1303)
      AND OL.AN *12+OL.LUNA+1 = ' || coalesce(AnLunaIni::varchar,'') || coalesce(filtruPart,'') || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('', 'COALESCE(intr.subunitatea, ies.subunitatea, t.subunitatea, nc.subunitatea, c.subunitatea)'),'') || '
  )
  SELECT
    np.den_part, crs.datadoc, crs.nrdoc, mon.simbol moneda, nc.simbol, crs.termen, ng.den_gest,
    crs.sold*crs.curs, crs.sold, crs.sold*crs.curs*crs.coefprovizion, crs.sold*crs.coefprovizion,
    sub.den_subunit, crs.tva, crs.curs,
    (case when crs.agent=0 then ag.nume else ag.nume||'' ''||ag.prenume end) agent
  FROM crs_soldini crs
    LEFT JOIN npart    np  ON np.codpart      = crs.codpart
    LEFT JOIN ngest    ng  ON crs.codgest     = ng.codgest
    LEFT JOIN nsubunit sub ON crs.subunitatea = sub.codsubunit
    LEFT JOIN nmonede  mon ON mon.codmoneda   = crs.moneda
    LEFT JOIN ncont    nc  ON nc.codcont      = PKG_LIST_BASE_UTILS_iCont_CodCont(crs.icont,crs.codpart,' || coalesce(AnLunaIni::varchar,'') || ',crs.semnificatie)
    LEFT JOIN npers    ag  ON ag.codpers      = crs.agent';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocep_getvtoatafirma</obj_name>
  <obj_hashval>ca10207b21e0069c8ed4d8ef6611c07e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_getvtoatafirma(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.vToataFirma'));
  RETURN ;
  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_stocep_vtoategest</obj_name>
  <obj_hashval>970c42239a30c7f88dae05a329915da4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocep_vtoategest(INOUT wme_result boolean, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_STOCEP.vToateGest'));
  RETURN ;
  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_syncpretretail_setjoinuri</obj_name>
  <obj_hashval>a0e2b76a814acfcea4ea12f4fa70c0d3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_syncpretretail_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Florin 18.04.2022
  PERFORM pkg_list_struct_SetTableSpec( (current_setting('PKG_LIST_BASE_SYNCPRETRETAIL.gSuplCols', true)));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_taskuri_processlist</obj_name>
  <obj_hashval>ad581616fe810ed1f00e9a6a1ba763fa</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_taskuri_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSterse         varchar := '';
  sInterval       varchar := '';
  LocTask         varchar := '';
  TaskFirma       numeric;
  gSuplCols        VARCHAR := '';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  g_includSterse  boolean := current_setting('PKG_LIST_BASE_TASKURI.g_includSterse', true)::boolean;
  g_areInterval    boolean := current_setting('PKG_LIST_BASE_TASKURI.g_areInterval' , true)::boolean;
  g_includLog      boolean := current_setting('PKG_LIST_BASE_TASKURI.g_includLog'   , true)::boolean;
  g_dataIni        varchar := current_setting('PKG_LIST_BASE_TASKURI.g_dataIni', true);
  g_dataFin        varchar := current_setting('PKG_LIST_BASE_TASKURI.g_dataFin', true);
BEGIN
  --Adina 11 septembrie 2020
  SELECT COALESCE(fnc_GetValConstanta('TaskFirma', getANLUCRU(), getlunalucru()), '0')::NUMERIC INTO TaskFirma;

  IF  TaskFirma = 2 THEN
    LocTask := '';
    gSuplCols := 'SETTASK ST, SETTASKLOG L';
  ELSE
    LocTask := 'WINMADMIN.';
    gSuplCols := 'LST_SETTASK ST, LST_SETTASKLOG L';
  END IF;

  gSuplCols := gSuplCols||', NMONEDE MON';
  call pkg_list_struct_startsuplcols();
  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_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_TASKURI.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  sInsert := 'INSERT INTO ' || tmpName || '(
    NAV_CODDOC,NAV_TIPDOC,ORDINE,CREATOR,EXECUTANT,PROBLEMA,DESTINATAR,TERMEN,
    DATATASK,ORATASK,DATAREZ,ORAREZ,
    DOMENIU,TIP,REZOLVARE,OBSERVATII,
    PRIORITATE,REZOLVAT,MODIFICAT,STERS,PROIECT,
    DELA,CATRE,DATA_TRMITERE,
    FACTURABIL,FACTURAT,VALOARE,
    MONEDA, ARTASOC, SERIIASOC, OBSASOC' || gUserFields || ')
  SELECT
    ST.CODTASK, 54 NAV_TIPDOC, ST.CODTASK, ST.USERNAME CREATOR, ST.EXECUTANT, SUBSTR(ST.PROBLEMA,1,3200), ST.DESTINATAR, ST.TERMEN,
    Date_Trunc(''day'',ST.DATATASK), TO_CHAR(ST.DATATASK,''HH24:MI:SS''), Date_Trunc(''day'',ST.DATAREZ), TO_CHAR(ST.DATAREZ,''HH24:MI:SS''),
    ST.DOMENIU, ST.TIP, SUBSTR(ST.REZOLVARE,1,3200),SUBSTR(ST.OBSERVATII,1,3200), ST.PRIORITATE,
    (case when ST.DONE=1 then ''DA'' else ''NU'' end) REZOLVAT, (case when ST.MODIFICAT=1 then ''DA'' else ''NU'' end) MODIFICAT,
    (case when ST.STERS=1 then ''DA'' else ''NU'' end) STERS , ST.PROIECT,
    L.USER_SRC DELA, L.USER_DST CATRE, TO_CHAR(L.DATA,''DD.MM.YYYY HH24:MI:SS'') DATA_TRMITERE,
    (case when ST.FACTURABIL=1 then ''DA'' else ''NU'' end) FACTURABIL, (case when ST.FACTURAT=1 then ''DA'' else ''NU'' end) FACTURAT, ST.VALOARE, MON.DEN_MONEDA,
    ASOC.DENUMIRE, ASOC.SERII, ASOC.OBSERVATII ' || gUserAlias || '
  FROM ' || LocTask || 'SETTASK ST
    LEFT JOIN ' || LocTask || 'SETTASKLOG L ON L.CODTASK    = ST.CODTASK' || coalesce(CASE WHEN g_includLog THEN NULL ELSE ' AND L.CODLOG = 0' END ::varchar ,'') || '
    LEFT JOIN NMONEDE MON                   ON ST.CODMONEDA = MON.CODMONEDA
    LEFT JOIN (
      SELECT ASOC.CODTASK,
             string_agg(O.DENUMIRE,'''    ||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' ) DENUMIRE,
             string_agg(ASOC.SERII,'''    ||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' ) SERII,
             string_agg(ASOC.CODINTERN,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||''' ) OBSERVATII
      FROM ' || LocTask || 'SETTASKOBJASOC ASOC INNER JOIN NARTOBJ O ON O.CODOBIECT = ASOC.CODOBIECT
      GROUP BY ASOC.CODTASK
    ) ASOC ON ASOC.CODTASK = ST.CODTASK' || gSuplJoins || '
  WHERE 1=1';

  IF  TaskFirma = 2 THEN
    sInsert := sInsert || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('ST',NULL,NULL,NULL),'');
  END IF;

  IF  NOT g_includSterse THEN
    sInsert := sInsert || '
    AND coalesce(ST.STERS,0) = 0 ';
  END IF;

  IF g_areInterval THEN
    sInsert := sInsert || '
    AND ST.DATATASK BETWEEN TO_DATE(''' || coalesce(G_DATAINI,'') || ''',''DD.MM.YYYY'') AND TO_DATE(''' || coalesce(G_DATAFIN,'') || ''',''DD.MM.YYYY'') ';
  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_topclienti_processlist</obj_name>
  <obj_hashval>ee15a7944228c4b117296c56102c4fc4</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topclienti_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 := '';

  sInsTmp     varchar;
  sUpdTmp     varchar;
  sInsert     varchar;
  vCondData   varchar;
  sCust       varchar := '';
  sTipDocS    varchar := '19';
  sTipDocX    varchar := '19';
  sCondCls    varchar := '';
  sJoinCls    varchar := '';
  sCondIOA    varchar := '';
  eCondIOA    varchar := '';
  vMonedaSitV numeric(20,0);
  vBancaSitV  numeric(20,0);
  sMonedaSitV varchar;
begin
  --Stef 14.11.2022
  --Laura 27.10.2021 - sinc Oracle (27.10.2021)
  --Bogdan 02.09.2020
  gSuplCols := 'TMP_TOPCLI T, NSUBUNIT S, NPART CLI, NAGENDA SLIVR, NPERS AGENT, NARTOBJ NAO, NART NA, NUM UM';

  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_TOPCLIENTI.gSuplCols',gSuplCols,false);

  vCondData := 'BETWEEN TO_DATE (''' || coalesce(current_setting('PKG_LIST_BASE_TOPCLIENTI.vDataINI', true),'') || ''',''DD.MM.YYYY'')
                    AND TO_DATE (''' || coalesce(current_setting('PKG_LIST_BASE_TOPCLIENTI.vDataFIN', true),'') || ''',''DD.MM.YYYY'')';
  IF  NOT (current_setting('PKG_LIST_BASE_TOPCLIENTI.vAduCust', true)::numeric = 1) THEN
    sCust := ' AND coalesce(I.Custodie,0) = 0 ';
  END IF;
  IF  NOT (current_setting('PKG_LIST_BASE_TOPCLIENTI.vAllCls', true)::numeric = 1) THEN
    sJoinCls := '
              INNER JOIN NARTOBJ O ON o.codobiect  = i1.codobiect
              INNER JOIN NART    A ON a.codarticol = o.codarticol ';
    sCondCls := '
          AND a.clasa IN (SELECT valoare::numeric FROM tmp_manevra_liste WHERE filtru = ''CODCLASEA'')';
  END IF;
  IF  NOT (current_setting('PKG_LIST_BASE_TOPCLIENTI.vAllIOA', true)::numeric = 1) THEN
    sCondIOA := '
          AND Coalesce(ns.codioart, lv.codioart) IN (SELECT valoare::numeric FROM tmp_manevra_liste WHERE filtru = ''CODIOART'')';
    eCondIOA := '
          AND i1.codioart IN (SELECT valoare::numeric FROM tmp_manevra_liste WHERE filtru = ''CODIOART'')';
  END IF;
  IF current_setting('PKG_LIST_BASE_TOPCLIENTI.vAvize', true)::numeric = 1 THEN
    sTipDocS := coalesce(sTipDocS,'') || ', 20';
    sTipDocX := coalesce(sTipDocX,'') || ', 20';
  ELSE
    sTipDocS := coalesce(sTipDocS,'') || ', 26';
  END IF;

  DELETE FROM TMP_TOPCLI;
  sInsTmp := '
        INSERT INTO TMP_TOPCLI (
                      codsubunit, codclient, codlocatie, codagent, codobiect,
                      coddoc, tipdoc, coddoc1, idxloc, tiplinie, nrdoc, datadoc, cant,
                      val,
                      tva,
                      valachiz
                    )

        SELECT
          i.subunitatea, Coalesce(i.partener,0), i.codlocatie, Coalesce(i.agent,0), i1.codobiect,
          i.codies, i.tipdoc, i1.codies1, i1.indexlocal, i1.tiplinie, i.nrdoc, i.datadoc, i1.cant,
          i1.cant*i1.pretorig*Coalesce(i1.coefdiscmaj,1)*CASE WHEN Coalesce(I.MONEDA, 0) = 1 THEN 1 ELSE Coalesce(I.CURS,1) END Val,
          CASE WHEN i1.pu = 0 THEN 0
               ELSE i1.tva*i1.pretorig*Coalesce(i1.coefdiscmaj,1)/i1.pu END*CASE WHEN Coalesce(I.MONEDA, 0) = 1 THEN 1 ELSE Coalesce(I.CURS,1)
          END tva,
          case when i1.tiplinie = ''S'' then 0 else i1.cant*i1.pretorig*Coalesce(i1.coefdiscmaj,1) end*CASE WHEN Coalesce(I.MONEDA, 0) = 1 THEN 1 ELSE Coalesce(I.CURS,1) END valachiz
        FROM iesiri i
          INNER JOIN iesiri1 i1 ON i1.codies = i.codies' || coalesce(sJoinCls,'') || '
        WHERE I.DATADOC ' || vCondData
                  || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL)),'') || '
            AND I.TipDoc IN (' || coalesce(sTipDocS,'') || ') AND coalesce(I.Anulat, 0) = 0 AND I.Operat = 1 AND coalesce(I.Initializari, 0) = 0 ' || coalesce(sCust,'') || '
            AND I1.TIPLINIE IN (''S'', ''V'')' || coalesce(sCondCls,'');

  IF current_setting('PKG_LIST_BASE_TOPCLIENTI.vAllIOA', true)::numeric = 1 THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsTmp, aListID, aListVer);
  END IF;
  sInsTmp := '
        INSERT INTO TMP_TOPCLI (
          codsubunit, codclient, codlocatie, codagent, codobiect,
          coddoc, tipdoc, coddoc1, idxloc, tiplinie, nrdoc, datadoc, cant,
          val,
          tva,
          valachiz
        )
        SELECT
          i.subunitatea, Coalesce(i.partener,0), i.codlocatie, Coalesce(i.agent,0), i1.codobiect,
          i.codies, i.tipdoc, i1.codies1, i1.indexlocal, i1.tiplinie, i.nrdoc, i.datadoc, l1.cant,
          l1.cant*i1.pretorig*Coalesce(i1.coefdiscmaj,1)*CASE WHEN Coalesce(I.MONEDA, 0) = 1 THEN 1 ELSE Coalesce(I.CURS,1) END Val,
          CASE WHEN i1.pu*i1.cant = 0 THEN 0
               ELSE i1.tva*i1.pretorig*Coalesce(i1.coefdiscmaj,1)*l1.cant/i1.pu/i1.cant END*CASE WHEN Coalesce(I.MONEDA, 0) = 1 THEN 1 ELSE Coalesce(I.CURS,1)
          END tva,
          Coalesce(lv.pretachiz,ns.pret-ns.adaos,0)*L1.cant valachiz
        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
          LEFT  JOIN nirstoc ns on ns.codnirstoc = l1.codnirstoc
          LEFT  JOIN livrval lv on lv.codlivr1   = l1.codlivr1' || coalesce(sJoinCls,'') || '
        WHERE I.DATADOC ' || vCondData
                || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL)),'') || '
          AND I.TipDoc IN (' || coalesce(sTipDocX,'') || ')
          AND coalesce(I.Anulat, 0) = 0 AND I.Operat = 1 AND coalesce(I.Initializari, 0) = 0 ' || coalesce(sCust,'') || '
          AND I1.TIPLINIE = ''=''' || coalesce(sCondCls,'') || coalesce(sCondIOA,'');
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsTmp, aListID, aListVer);
--
  sInsTmp := '
      INSERT INTO TMP_TOPCLI (
        codsubunit, codclient, codlocatie, codagent, codobiect,
        coddoc, tipdoc, coddoc1, idxloc, tiplinie, nrdoc, datadoc, cant,
        val,
        tva,
        valachiz
      )
      SELECT
        i.subunitatea, Coalesce(i.partener,0), i.codlocatie, Coalesce(i.agent,0), i1.codobiect,
        i.codies, i.tipdoc, i1.codies1, i1.indexlocal, i1.tiplinie, i.nrdoc, i.datadoc, l1.cant,
        l1.cant*i1.pretorig*Coalesce(i1.coefdiscmaj,1)*CASE WHEN Coalesce(I.MONEDA, 0) = 1 THEN 1 ELSE Coalesce(I.CURS,1) END Val,
        CASE WHEN i1.pu*i1.cant = 0 THEN 0
             ELSE i1.tva*i1.pretorig*Coalesce(i1.coefdiscmaj,1)*l1.cant/i1.pu/i1.cant END*CASE WHEN Coalesce(I.MONEDA, 0) = 1 THEN 1 ELSE Coalesce(I.CURS,1)
        END tva,
        Coalesce(lv.pretachiz,ns.pret-ns.adaos,0)*L1.cant valachiz
      FROM iesiri i
        INNER JOIN iesiri1 i1 ON i1.codies     = i.codies
        INNER JOIN ieslink il ON il.codies1    = i1.codies1 AND Coalesce(il.codlinieaviz, 0) &lt;&gt; 0
        INNER JOIN livr1   l1 ON l1.codies1    = il.codlinieaviz
        INNER JOIN livr    l  ON l.codlivr     = l1.codlivr AND l.tiplivr = 20
        LEFT  JOIN nirstoc ns on ns.codnirstoc = l1.codnirstoc
        LEFT  JOIN livrval lv on lv.codlivr1   = l1.codlivr1' || coalesce(sJoinCls,'') || '
      WHERE I.DATADOC ' || vCondData
            || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL)),'') || '
        AND I.TipDoc IN (26) AND coalesce(I.Anulat, 0) = 0 AND I.Operat = 1 AND coalesce(I.Initializari, 0) = 0 ' || coalesce(sCust,'') || '
        AND I1.TIPLINIE = ''=''' || coalesce(sCondCls,'') || coalesce(sCondIOA,'');

  IF  NOT (current_setting('PKG_LIST_BASE_TOPCLIENTI.vAvize', true)::numeric = 1) THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsTmp, aListID, aListVer);
  END IF;
  sInsTmp := '
      INSERT INTO TMP_TOPCLI (
        codsubunit, codclient, codlocatie, codagent, codobiect,
        coddoc, tipdoc, coddoc1, idxloc, tiplinie, nrdoc, datadoc, cant,
        val,
        tva,
        valachiz
      )
      SELECT
        c.subunitatea, e.codpart, Coalesce(e.codagent,0), e.codlocatie, i1.codobiect,
        e.codemulare, 64, i1.codemulare1, i1.indexlocal, i1.tiplinie, e.nrbon, e.databon, i1.cant,
        i1.cant * i1.pret - i1.tva,
        i1.tva,
        CASE
          WHEN Coalesce(e.codmonetar,0) = 0 THEN 0
          ELSE (
                 SELECT CASE WHEN SUM(L1.cant) = 0 THEN 0
                             ELSE i1.cant*SUM(Coalesce(lv.pretachiz,ns.pret-ns.adaos,0)*L1.cant)/SUM(L1.cant)
                        END
                 FROM livr l
                   INNER JOIN livr1   l1 ON l1.codlivr    = l.codlivr
                   LEFT  JOIN nirstoc ns on ns.codnirstoc = l1.codnirstoc
                   LEFT  JOIN livrval lv on lv.codlivr1   = l1.codlivr
                 WHERE l.codies = e.codmonetar AND l.tiplivr = 16 AND i1.CodObiect = coalesce(lv.CodObiect, Ns.CodObiect)
               )
        END valachiz
      FROM emulare e
        INNER JOIN ncasemarcat c  ON c.codcasemarcat = e.codcasamarcat
        INNER JOIN emulare1    i1 ON i1.codemulare   = e.codemulare
        LEFT JOIN Iesiri       x  ON x.codies        = e.codIes' || coalesce(sJoinCls,'') || '
      WHERE e.databon '
            || vCondData
            || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'C',NULL,NULL,NULL)),'') || '
        AND (Coalesce(e.CodIes,0) = 0 or Coalesce(x.InfoCM,0) = 1)
        AND Coalesce(e.codpart,0) &gt; 0' || coalesce(sCondCls,'') || coalesce(eCondIOA,'');

  IF current_setting('PKG_LIST_BASE_TOPCLIENTI.vAduEmul', true)::numeric = 1 THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsTmp, aListID, aListVer);
  END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE('DELETE from TMP_TOPCLI WHERE CANT = 0', aListID, aListVer);

  vMonedaSitV := fnc_GetValConstantaLucru('MonedaSitV')::numeric;
  vBancaSitV  := fnc_GetValConstantaLucru('BancaSitV' )::numeric;

  sUpdTmp := 'UPDATE TMP_TOPCLI SET curs = (select wme_result from PKG_LIST_BASE_UTILS_GETCURSREFERINTA(NULL, ' || coalesce(vMonedaSitV::varchar,'') || ' , '
                                          || coalesce(vBancaSitV::varchar,'')
                                          || ', TO_CHAR( datadoc, ''dd.mm.yyyy'')) )';
--
  IF  Coalesce(vMonedaSitV, 0) &lt;&gt; 0 AND  Coalesce(vBancaSitV, 0) &lt;&gt; 0 THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(sUpdTmp, aListID, aListVer);
    sMonedaSitV := (SELECT pkg_monede_get_simbol_moneda.WME_RESULT FROM pkg_monede_get_simbol_moneda(NULL,vMonedaSitV));
  END IF;
--
  sInsert := 'INSERT INTO ' || tmpName || '(
              Subunitatea, Client, SediuL, Agent, DenArt, DenUM,
              Cant, Valoare, ValAchiz, ValAdaos,
              Curs, Valuta' || coalesce(gUserFields,'') || ')
            SELECT
              S.Den_Subunit, CLI.Den_Part, SLIVR.OBS, (SELECT wme_result from NumePrenume(null, AGENT.NUme, AGENT.Prenume)), NAO.Denumire, UM.Den_UM,
              T.CANT, T.Val, T.ValAchiz, CASE WHEN T.TIPLINIE = ''='' THEN T.Val - T.ValAchiz ELSE 0 END ValAdaos,
              T.Curs, ''' || coalesce(sMonedaSitV,'') || '''' || coalesce(gUserAlias,'') || '
            FROM TMP_TOPCLI T
              LEFT JOIN NSUBUNIT S    ON S.COdSubunit    = T.CodSubunit
              LEFT JOIN NPART CLI     ON CLI.CodPart     = T.CodClient
              LEFT JOIN NAGENDA SLIVR ON SLIVR.CodAgenda = T.CodLocatie
              LEFT JOIN NPERS AGENT   ON AGENT.CodPers   = T.CodAgent
              LEFT JOIN NARTOBJ NAO   ON NAO.CodObiect   = T.CodObiect
              LEFT JOIN NART NA       ON NA.CodArticol   = NAO.CodArticol
              LEFT JOIN NUM UM        ON UM.CodUM        = NA.UM' || coalesce(gSuplJoins,'') || '';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
  sInsert := 'update ' || coalesce(tmpName,'') || ' set NrFact = (select count(*) from (select distinct coddoc,tipdoc from TMP_TOPCLI) a_pg)';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
end;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topclientiold_avize</obj_name>
  <obj_hashval>801757a79ef6a146a3c429a208f78a61</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topclientiold_avize()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 19.10.2020
  RETURN current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vAvize',true)::numeric;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topfurn_setnrfact_art</obj_name>
  <obj_hashval>6f719a4c34a5f3ec6d16a58c7c516a63</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topfurn_setnrfact_art()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  aNr numeric(20) := 0;
  aCodSubunit numeric(20);
BEGIN
  --Florin 13.01.2023 - fixat 56791
  --Florin 18.07.2022 - fixat 54942
  --Florin 07.07.2022
  aCodSubunit := GETSUBUNITATE();
  if current_setting('PKG_LIST_BASE_TOPFURN.vAllIOArt', TRUE) then
    INSERT INTO TMP_CMD_TMP1(COD1,VAL,TIP,COD2)
    SELECT PARTENER, COUNT(DISTINCT CODINTR), 'FACTART',CODOBIECT FROM (
    SELECT DISTINCT I.PARTENER, I.CodIntr,I1.CODOBIECT
    FROM INTRARI I
      INNER JOIN INTRARI1 I1 ON I.CodIntr = I1.CodIntr
    WHERE I.TipDoc &lt;&gt; 2 AND coalesce(I.Anulat, 0) = 0 AND coalesce(I.Initializari, 0) = 0 AND I.Operat = 1
      AND I.DataDoc BETWEEN TO_DATE(current_setting('PKG_LIST_BASE_TOPFURN.vDataINI', true),'DD.MM.YYYY') AND TO_DATE (current_setting('PKG_LIST_BASE_TOPFURN.vDataFIN', TRUE),'DD.MM.YYYY')
      AND aCodSubunit = (CASE WHEN aCodSubunit = 1 THEN 1 ELSE I.Subunitatea END)
    ) a_pg GROUP BY PARTENER, CODOBIECT;
    INSERT INTO TMP_CMD_TMP1(COD1,VAL,TIP,COD2)
    SELECT PARTENER, COUNT(DISTINCT CODINTR), '-FACTART',CONTDISCOUNT FROM (
    SELECT DISTINCT I.PARTENER, I.CodIntr,I1.ContDiscount
    FROM INTRARI I
      INNER JOIN INTRARI1 I1 ON I.CodIntr = I1.CodIntr
    WHERE I.TipDoc &lt;&gt; 2 AND coalesce(I.Anulat, 0) = 0 AND coalesce(I.Initializari, 0) = 0 AND I.Operat = 1
      AND I.DataDoc BETWEEN TO_DATE(current_setting('PKG_LIST_BASE_TOPFURN.vDataINI', true),'DD.MM.YYYY') AND TO_DATE (current_setting('PKG_LIST_BASE_TOPFURN.vDataFIN', TRUE),'DD.MM.YYYY')
      AND aCodSubunit = (CASE WHEN aCodSubunit = 1 THEN 1 ELSE I.Subunitatea END)
    ) b_pg GROUP BY PARTENER, CONTDISCOUNT;
  else
    INSERT INTO TMP_CMD_TMP1(COD1,VAL,TIP,COD2)
    SELECT PARTENER,COUNT(DISTINCT CodIntr),'FACTART',CODOBIECT
    FROM (
    SELECT DISTINCT I.PARTENER,I.CODINTR,I1.CODOBIECT
    FROM INTRARI I
      INNER JOIN INTRARI1 I1 ON I.CodIntr = I1.CodIntr
      INNER JOIN NIRSTOC NS ON NS.CODINTR1 = I1.CODINTR1
    WHERE I.TipDoc &lt;&gt; 2 AND coalesce(I.Anulat, 0) = 0 AND coalesce(I.Initializari, 0) = 0 AND I.Operat = 1
      AND I.DataDoc BETWEEN TO_DATE(current_setting('PKG_LIST_BASE_TOPFURN.vDataINI', true),'DD.MM.YYYY') AND TO_DATE (current_setting('PKG_LIST_BASE_TOPFURN.vDataFIN', TRUE),'DD.MM.YYYY')
      AND I1.TIPLINIE = '='
      AND aCodSubunit = (CASE WHEN aCodSubunit = 1 THEN 1 ELSE I.Subunitatea END)
      AND EXISTS (SELECT TMP.VALOARE FROM TMP_MANEVRA_LISTE TMP WHERE TMP.FILTRU = 'CODIOART' AND TMP.VALOARE = NS.CODIOART::varchar)
    UNION ALL
    SELECT I.PARTENER,I.CODINTR,I1.CODOBIECT
    FROM INTRARI I
      INNER JOIN INTRARI1 I1 ON I.CodIntr = I1.CodIntr
      INNER JOIN NIRSTOC NS ON NS.CODINTR1 = I1.CODINTR1
      INNER JOIN NPART P ON I.Partener = P.CodPart
    WHERE I.TipDoc &lt;&gt; 2 AND coalesce(I.Anulat, 0) = 0 AND coalesce(I.Initializari, 0) = 0 AND I.Operat = 1
      AND I.DataDoc BETWEEN TO_DATE(current_setting('PKG_LIST_BASE_TOPFURN.vDataINI', true),'DD.MM.YYYY') AND TO_DATE (current_setting('PKG_LIST_BASE_TOPFURN.vDataFIN', TRUE),'DD.MM.YYYY')
      AND I1.TIPLINIE &lt;&gt; '='
      AND aCodSubunit = (CASE WHEN aCodSubunit = 1 THEN 1 ELSE I.Subunitatea END)
    ) c_pg GROUP BY PARTENER,CODOBIECT;
    INSERT INTO TMP_CMD_TMP1(COD1,VAL,TIP,COD2)
    SELECT PARTENER,COUNT(DISTINCT CodIntr),'-FACTART',CONTDISCOUNT
    FROM (
    SELECT DISTINCT I.PARTENER,I.CODINTR,I1.CONTDISCOUNT
    FROM INTRARI I
      INNER JOIN INTRARI1 I1 ON I.CodIntr = I1.CodIntr
      INNER JOIN NIRSTOC NS ON NS.CODINTR1 = I1.CODINTR1
    WHERE I.TipDoc &lt;&gt; 2 AND coalesce(I.Anulat, 0) = 0 AND coalesce(I.Initializari, 0) = 0 AND I.Operat = 1
      AND I.DataDoc BETWEEN TO_DATE(current_setting('PKG_LIST_BASE_TOPFURN.vDataINI', true),'DD.MM.YYYY') AND TO_DATE (current_setting('PKG_LIST_BASE_TOPFURN.vDataFIN', TRUE),'DD.MM.YYYY')
      AND I1.TIPLINIE = '='
      AND aCodSubunit = (CASE WHEN aCodSubunit = 1 THEN 1 ELSE I.Subunitatea END)
      AND EXISTS (SELECT TMP.VALOARE FROM TMP_MANEVRA_LISTE TMP WHERE TMP.FILTRU = 'CODIOART' AND TMP.VALOARE = NS.CODIOART::varchar)
    UNION ALL
    SELECT DISTINCT I.PARTENER,I.CODINTR,I1.CONTDISCOUNT
    FROM INTRARI I
      INNER JOIN INTRARI1 I1 ON I.CodIntr = I1.CodIntr
      INNER JOIN NIRSTOC NS ON NS.CODINTR1 = I1.CODINTR1
      INNER JOIN NPART P ON I.Partener = P.CodPart
    WHERE I.TipDoc &lt;&gt; 2 AND coalesce(I.Anulat, 0) = 0 AND coalesce(I.Initializari, 0) = 0 AND I.Operat = 1
      AND I.DataDoc BETWEEN TO_DATE(current_setting('PKG_LIST_BASE_TOPFURN.vDataINI', true),'DD.MM.YYYY') AND TO_DATE (current_setting('PKG_LIST_BASE_TOPFURN.vDataFIN', TRUE),'DD.MM.YYYY')
      AND I1.TIPLINIE &lt;&gt; '='
      AND aCodSubunit = (CASE WHEN aCodSubunit = 1 THEN 1 ELSE I.Subunitatea END)
    ) d_pg GROUP BY PARTENER,CONTDISCOUNT;
  end if;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_traduceri_setparams</obj_name>
  <obj_hashval>8a015ac644be855395b3c3e13a80fb96</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_traduceri_setparams()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 17 septembrie 2020
  NULL;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_transfdoc_processparams</obj_name>
  <obj_hashval>5d1f62d2258aedaaaf8a2d4fa2c378f1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_transfdoc_processparams(vcodtransf numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC             RECORD;
  mModificaridepret numeric := 13;
  vValCuTva         numeric := PKG_LIST_BASE_TRANSFDOC_GETVALTVA(vCodTransf);
BEGIN
  --Florin 10.04.2024 - fixat 61640
  --Florin 22.09.2022 - sinc. Oracle (22.09.2022)
  --Bogdan 10.03.2022 - 53419 PG - Lista transferuri intre gestiuni: eroare
  --Florin 04.03.2022 - sinc. Oracle
  --Adina 17 septembrie 2020
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  FOR v_rec IN (SELECT   T.TIPDOC, T.SERIADOC, T.NRDOC, T.DATADOC, T.VALDOC, T.NRAE, T.OBS, CG.Den_Gest CMDGEST,
                        CS.TELEFON CMDTELEFON, CL.DEN_LOCALIT CMDLOCALIT, CJ.Den_Judet CMDJUDET,
                        fnc_GetAdresa(CS.sector, CS.strada, CS.nr1, CS.nr2, CS.bloc, CS.scara, CS.etaj, CS.apart, CS.codpostal) CMDADRESA,
                        CASE WHEN  T.STORNO = 1 AND  T.TipDoc &lt;&gt; mModificaridepret THEN 'DA' ELSE 'NU' END  STORNO,
                        CASE WHEN  T.TipDoc = mModificaridepret THEN 'Proces verbal de modificare de pret' ELSE 'Nota de transfer' END  TIPTRANSF,
                        CASE TIPMODIFPRET
                            WHEN 0 THEN 'PU inreg. nou  fara reevaluare PU achizitie'
                            WHEN 1 THEN 'PU inreg. nou  + reevaluare PU achizitie astfel incat Adaos=0'
                            WHEN 2 THEN 'PU inreg. nou  + reevaluare PU achizitie numai daca Adaos &lt; 0'
                            WHEN 3 THEN 'PU achizitie nou fara afectarea PU inregistrare'
                            ELSE  NULL
                        END  TIPMODIFPRET,
                        COALESCE(U.Nume, '...nedefinit...') UNUME, COALESCE(U.Prenume, '...nedefinit...') UPRENUME,
                        COALESCE(U.CNP, '...nedefinit...') UCNP, coalesce(U.BISERIA,'') || ' ' || coalesce(U.BINR::varchar ,'') UBI,
                        D.Delegat DEL, D.DOC DELDOC, D.NRDOC DELNRDOC, D.SERIEDOC DELSERIEDOC, D.ELIBERAT DELELIBERAT, D.CNP DELCNP, D.DATADOC DELDATADOC,
                        T.MIJLTRANSP DELMIJLTRANSP, T.NRTRANSP DELNRTRANSP, ETRANS.UIT
                FROM   TRANSF T
                      LEFT JOIN NPARTTR D   ON  T.DELEGAT     = D.CODPARTTR
                      LEFT JOIN NGEST CG     ON  CG.CODGEST    = T.CODGESTCMD
                      LEFT JOIN NAGENDA CS   ON  CS.CODGEST    = CG.CODGEST
                      LEFT JOIN NLOCALIT CL ON  CL.CODLOCALIT = COALESCE(CS.CODLOCALIT, 0)
                      LEFT JOIN NJUDET CJ   ON  CJ.CODJUDET   = COALESCE(CL.CODJUDET, 0)
                      LEFT JOIN NPERS U     ON  U.LOGONNAME   = T.USERID
                      LEFT JOIN STATUSDECL ETRANS ON ETRANS.CODDOC = T.CODTRANSF AND ETRANS.TIPDOC = 100 + T.TIPDOC
                WHERE T.CODTRANSF = vCodTransf
               )
  LOOP
    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  AccesGranted(getUSERID(), 'BLIND') &gt; 0 THEN
      PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT TOTAL', TO_CHAR(v_rec.ValDoc, 'fm9G999G999G990D00'));
    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);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COMANDA GESTIUNE',             v_rec.CMDGest);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COMANDA GESTIUNE JUDET',       v_rec.CMDJudet);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COMANDA GESTIUNE LOCALITATE', v_rec.CMDLocalit);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COMANDA GESTIUNE ADRESA',     v_rec.CMDAdresa);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COMANDA GESTIUNE TELEFON',     v_rec.CMDTelefon);

    IF  v_rec.TipDoc = mModificaridepret THEN
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TIP MODIFICARE PRET',       v_rec.TIPMODIFPRET);
    ELSE
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DELEGAT',         v_rec.DEL);
      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.DELSERIEDOC);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DOC ELIBERAT',     v_rec.DELELIBERAT);
      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.DELMIJLTRANSP);
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT NR MIJLOC',       v_rec.DELNRTRANSP);
    END IF;

    PERFORM pkg_list_Struct_ADAUGA_PARAM('TIP DOC',                     v_rec.TipTransf);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('STORNO',                       v_rec.STORNO);
    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('FILTRU',                       '');
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT   SUM(L1.CANT * COALESCE(NS.PRET, 0)) VALLIVR, SUM(L1.CANT * COALESCE(O.VOLUM, 0)) VOLUM,
                        SUM(L1.CANT * COALESCE(O.MASA, 0)) MASA,
                        Sum(L1.CANT * COALESCE(CASE WHEN LV.CODLIVR1 IS NULL THEN NS.PRET ELSE LV.PRETINREG END , 0)) VALINREG,
                        Sum(L1.CANT * COALESCE(CASE WHEN LV.CODLIVR1 IS NULL THEN (NS.PRET - NS.ADAOS) ELSE LV.PRETACHIZ END , 0)) VALACHIZ,
                        Sum(L1.CANT * COALESCE(NS.PUMAXIMAL, 0)) VALMAX,
                        fnc_array_to_vc3200(array_agg(DISTINCT NG.DEN_GEST ORDER BY NG.DEN_GEST)) DGEST,
                        fnc_array_to_vc3200(array_agg(DISTINCT SubStr(NUMEPRENUME(PG.NUME, PG.PRENUME) ,1,300) ORDER BY SubStr(NUMEPRENUME(PG.NUME, PG.PRENUME) ,1,300))) GGEST,  --NUMEPRENUME_OBJ(PG.NUME,PG.Prenume).VC2
                                  fnc_array_to_vc3200(array_agg(DISTINCT L.NRLIVR||'/'||TO_CHAR(L.DATALIVR,'DD.MM.YYYY') ORDER BY L.NRLIVR||'/'||TO_CHAR(L.DATALIVR,'DD.MM.YYYY'))) LLIVR
                    FROM   LIVR L
                      INNER JOIN LIVR1 L1   ON  L1.CODLIVR    = L.CODLIVR
                      LEFT  JOIN NIRSTOC NS ON  NS.CODNIRSTOC = L1.CODNIRSTOC
                      LEFT  JOIN LIVRVAL LV ON  LV.CODLIVR1   = L1.CODLIVR1
                      LEFT  JOIN NARTOBJ O   ON  O.CODOBIECt   = COALESCE(LV.CODOBIECT, NS.CODOBIECT, 0)
                      LEFT  JOIN NIR N       ON  N.CODNIR      = NS.CODNIR
                      LEFT  JOIN NGEST NG   ON  NG.CODGEST    = COALESCE(N.GEST, LV.GEST)
                      LEFT  JOIN NPERS PG   ON  PG.CODPERS    = NG.CODGESTIONAR
                WHERE L.CODTRANSF = vCodTransf
               )
  LOOP
    IF  AccesGranted(getUSERID(), 'BLIND') &gt; 0 THEN
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL LIVRARI',                 TO_CHAR(v_rec.ValLivr, 'fm9G999G999G990D00'));
    ELSE
      PERFORM pkg_list_Struct_ADAUGA_PARAM('TOTAL LIVRARI',                 '***');
    END IF;

    PERFORM pkg_list_Struct_ADAUGA_PARAM('VOLUM TOTAL',                     TO_CHAR(v_rec.Volum, 'fm9G999G999G990D00'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('MASA TOTALA',                     TO_CHAR(v_rec.Masa , 'fm9G999G999G990D00'));
        PERFORM pkg_list_Struct_ADAUGA_PARAM('LIVRARI', v_rec.LLIVR);

    IF  AccesGranted(getUSERID(), 'BLIND') &gt; 0 THEN
      PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE ACHIZITIE',             TO_CHAR(v_rec.valachiz, 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE LA PRET MAXIMAL SURSA', TO_CHAR(v_rec.valmax  , 'fm9G999G999G990D00'));
      PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE LA PRET INREG SURSA',   TO_CHAR(v_rec.valinreg, 'fm9G999G999G990D00'));
    ELSE
      PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE ACHIZITIE',             '***');
      PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE LA PRET MAXIMAL SURSA', '***');
      PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE LA PRET INREG SURSA',   '***');
    END IF;

    PERFORM pkg_list_Struct_ADAUGA_PARAM('GEST. LIVRARE',                   v_rec.DGest);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('GEST. LIVRARE GESTIONAR',         v_rec.GGest);
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT SUM(NS.CANTNIR * NS.PRET) VALINREG
                FROM   TRANSF1 T1
                      LEFT JOIN NIRSTOC NS ON  NS.CODTRANSF1 = T1.CODTRANSF1
                WHERE T1.CODTRANSF = vCodTransf
               )
  LOOP
    IF AccesGranted(getUSERID(), 'BLIND') &gt; 0 THEN
      PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE LA PRET INREG DESTINATIE', TO_CHAR(v_rec.valinreg, 'fm9G999G999G990D00'));
    ELSE
      PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE LA PRET INREG DESTINATIE', '***');
    END IF;

    EXIT ;
  END LOOP;

  IF AccesGranted(getUSERID(), 'BLIND') &gt; 0 THEN
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE LA PRET INREG CU TVA SURSA', TO_CHAR(vValCuTva, 'fm9G999G999G990D00'));
  ELSE
    PERFORM pkg_list_Struct_ADAUGA_PARAM('VALOARE LA PRET INREG CU TVA SURSA', '***');
  END IF;

  FOR v_rec IN (SELECT fnc_array_to_vc3200(array_agg(DISTINCT NG.DEN_GEST ORDER BY NG.DEN_GEST)) DGEST,
                       fnc_array_to_vc3200(array_agg(DISTINCT SubStr(NUMEPRENUME(PG.NUME, PG.PRENUME) ,1,300) ORDER BY SubStr(NUMEPRENUME(PG.NUME, PG.PRENUME) ,1,300))) GGEST
                FROM   TRANSF T
                      LEFT JOIN NIR N ON  N.CODTRANSF   = T.CODTRANSF
                      LEFT JOIN NGEST NG ON  NG.CODGEST = N.GEST
                      LEFT JOIN NPERS PG ON  PG.CODPERS = NG.CODGESTIONAR
                WHERE T.CODTRANSF = VCodTransf
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('GEST. RECEPTIE',            v_rec.DGest);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('GEST. RECEPTIE GESTIONAR', v_rec.GGest);
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_transfdoc_setparams</obj_name>
  <obj_hashval>f5977c542d5325f0f39471134f997ac9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_transfdoc_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 17 septembrie 2020
  perform set_config('PKG_LIST_BASE_TRANSFDOC.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_transfdoc_processlist</obj_name>
  <obj_hashval>a09ed3b725f6277386dc2733c8bcf880</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_transfdoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sSelectOK       varchar := '';
  sSelectNOK       varchar := '';
  sInsertUMA       varchar := '';
  sSelectUMA       varchar := '';
  sJoinUMA         varchar := '';
  vOK             NUMERIC;
  vCodDoc         varchar := current_setting('PKG_LIST_BASE_TRANSFDOC.vCodDoc', true);
  gSuplCols        VARCHAR := 'TRANSF T, TRANSF1 T1, NARTOBJ NAO, PRETM PRETM, NART NA, NUM1 UM, NUM UM1, NUM UM2, NCLASEA NCA, NPART PROD, PRETM PM, NCONT CS, NCONT CD, IOART IOAS, IOART IOAd';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Adina 29.03.2021 - alstart, alstop
  --Adina 18 septembrie 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',       'OPER',  'OPER.LOGONNAME = T.USERID'     ,NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_TRANSFDOC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  PERFORM PKG_LIST_BASE_UTILS_make_config_luna_ioart();

  SELECT CASE WHEN  OPERAT = 1 AND  ANULAT = 0 THEN 1 ELSE 0 END INTO vOK FROM TRANSF WHERE CODTRANSF = vCodDoc::numeric;

  IF  vOk = 1 THEN
    SELECT PKG_LIST_BASE_UTILS_UMA_UTILS.sInsertUMA, PKG_LIST_BASE_UTILS_UMA_UTILS.sSelectUMA, PKG_LIST_BASE_UTILS_UMA_UTILS.sJoinUMA
    INTO sInsertUMA, sSelectUMA, sJoinUMA
    FROM PKG_LIST_BASE_UTILS_UMA_UTILS('tg.cant', 't1.codobiect', sInsertUMA, sSelectUMA, sJoinUMA,NULL);
  ELSE
    SELECT PKG_LIST_BASE_UTILS_UMA_UTILS.sInsertUMA, PKG_LIST_BASE_UTILS_UMA_UTILS.sSelectUMA, PKG_LIST_BASE_UTILS_UMA_UTILS.sJoinUMA
    INTO sInsertUMA, sSelectUMA, sJoinUMA
    FROM PKG_LIST_BASE_UTILS_UMA_UTILS('t1.cant', 't1.codobiect', sInsertUMA, sSelectUMA, sJoinUMA,NULL);
  END IF;

  sInsert :=
  'INSERT INTO ' || tmpName || '(
    Document,PrefixDoc,Nrdoc,DataDoc,ART,
    Cant,CantUM1,CantUM2,CantUM1D,CantUM2D,UM,UMALT1,UMALT2,
    ClasaA,PUAchiz_S,PUAchiz_D,PUInreg_S,PUInreg_D,
    PretMax_S,PretMax_D,
    VALACH_S,VALACH_D,VALINREG_S,VALINREG_D,
    Operat, TIPSERIE,
    SERII,DATAEXP,SERIEDATA,SER,SERTG,SERCANT,
    PROCTVA, PRODUCATOR, PUInregTVA_S, CONT_S, CONT_D, NrUnic,
    COMP_ART, COMP_UM, COMP_CANT, COMP_PRET, TIPRETETA, GESTSURSA, GESTDEST ' || coalesce(sInsertUMA,'') || gUserFields || ') ';

  sSelectOK := '
  WITH
    tg AS (
      SELECT
        (case t.tipdoc when 12 then ''Transf. '' when 13 then ''Modif. pret '' end)||t.prefixdoc||t.nrdoc||'' / ''||to_char(t.datadoc,''dd.mm.yyyy'') as document,
        t.codtransf, t.prefixdoc,t.nrdoc,t.datadoc,(case when t.operat=0 then ''Nu'' else ''Da'' end) operat, t.codpart, t.an, t.luna,
        t1.codtransf1, t1.indexlocal, t1.codobiect, t1.umsec, t1.codcont, MAX(ns_d.tipserie) tipserie, SUM(ns_d.cantnir) cant,
        SUM(coalesce(l1.cantum1,0)) cantum1s, SUM(coalesce(l1.cantum2,0)) cantum2s, SUM(coalesce(ns_d.cantum1,0)) cantum1d, SUM(coalesce(ns_d.cantum2,0)) cantum2d,
        MAX(coalesce(ns_s.pumaximal,0)) pumaximals, MAX(coalesce(ns_d.pumaximal,0)) pumaximald,
        SUM(coalesce(lv.pretinreg,ns_s.pret)*ns_d.cantnir) vis, SUM(coalesce(lv.pretachiz, ns_s.pret - ns_s.adaos)*ns_d.cantnir) vas,
        SUM(ns_d.pret*ns_d.cantnir) vid, SUM((ns_d.pret - ns_d.adaos)*ns_d.cantnir) vad,
        SUM((case when coalesce(io1s.aretvaneex, 0)= 0 then coalesce(lv.pretinreg,ns_s.pret)*ns_d.cantnir else 0 end)) vpinrtvas_ftva,
        SUM((case when coalesce(io1s.aretvaneex, 0)= 0 then 0 else coalesce(lv.pretinreg,ns_s.pret)*ns_d.cantnir end)) vpinrtvas_ctva,
        coalesce(lv.codioart,ns_s.codioart) conts, ns_d.codioart contd, coalesce(n_s.gest,0) gest, coalesce(n_d.gest,0) gestdest
      FROM transf t
        INNER JOIN transf1        t1   ON t1.codtransf    = t.codtransf
        INNER JOIN livr           l    ON l.codtransf     = t.codtransf
        INNER JOIN livr1          l1   ON l1.codlivr      = l.codlivr AND l1.codies1 = t1.codtransf1
        INNER JOIN nartobj        nobj ON nobj.codobiect  = t1.codobiect
        INNER JOIN nirstoc        ns_d ON ns_d.codlivr1   = l1.codlivr1
        INNER JOIN nir            n_d  ON n_d.codnir      = ns_d.codnir
        LEFT  JOIN nirstoc        ns_s ON ns_s.codnirstoc = l1.codnirstoc
        LEFT  JOIN nir            n_s  ON n_s.codnir      = ns_s.codnir
        LEFT  JOIN livrval        lv   on lv.codlivr1     = l1.codlivr1
        LEFT  JOIN tmp_ioart_luna io1s ON io1s.codioart   = coalesce(lv.codioart,ns_s.codioart)
      WHERE L.CODTRANSF = ' || coalesce(vCodDoc ,'') || '
      GROUP BY
        t.codtransf, t.tipdoc, t.prefixdoc, t.nrdoc, t.datadoc, t.codpart, t.operat, t.an, t.luna,
        t1.codtransf1, t1.indexlocal, t1.codobiect, t1.umsec, t1.codcont,
        coalesce(lv.codioart,ns_s.codioart), ns_d.codioart, coalesce(n_s.gest,0), coalesce(n_d.gest,0)
    ),
    ser AS (
      SELECT
        codtransf1, conts, contd, gest,
        fnc_array_to_vc3200(array_agg(serie)                ) serii,
        fnc_array_to_vc3200(array_agg(DISTINCT sertg)       ) tg,
        fnc_array_to_vc3200(array_agg(serie||'' - ''||sertg)) seriedata,
        fnc_array_to_vc3200(array_agg(ser ORDER BY ser)     ) ser,
        fnc_array_to_vc3200(array_agg(sertg ORDER BY ser)   ) sertg,
        fnc_array_to_vc3200(array_agg(sercant ORDER BY ser) ) sercant
      FROM (
        SELECT
          t1.codtransf1, ns_s.codioart conts, ns_d.codioart contd, coalesce(n_s.gest,0) gest,
          S.SERIE||CASE WHEN SUM(L1.CANT) &lt;&gt; 1 THEN '' ( ''||SUM(L1.CANT)||'' )'' END SERIE,
          S.SERIE SER, (SUM(L1.CANT))::varchar SERCANT, TO_CHAR(coalesce(nser.tg, ns_s.tg), ''DD.MM.YYYY'') SERTG
        FROM transf t
          INNER JOIN transf1 t1   ON t1.codtransf    = t.codtransf
          INNER JOIN livr    l    ON l.codtransf     = t.codtransf
          INNER JOIN livr1   l1   ON l1.codlivr      = l.codlivr AND l1.codies1 = t1.codtransf1
          INNER JOIN nirser  nser ON nser.codnirser  = l1.codnirser
          INNER JOIN nserii  s    ON s.codserie      = nser.codserie
          INNER JOIN nirstoc ns_d ON ns_d.codlivr1   = l1.codlivr1
          INNER JOIN nir     n_d  ON n_d.codnir      = ns_d.codnir
          INNER JOIN nirstoc ns_s ON ns_s.codnirstoc = l1.codnirstoc
          INNER JOIN nir     n_s  ON n_s.codnir      = ns_s.codnir
      WHERE L.CODTRANSF = ' || coalesce(vCodDoc,'') || '
      GROUP BY t1.codtransf1, ns_s.codioart, ns_d.codioart, coalesce(n_s.gest,0), s.serie, coalesce(nser.tg,ns_s.tg)
    ) A_PG
    GROUP BY codtransf1, conts, contd, gest
  )
  SELECT
    tg.document, tg.prefixdoc, tg.nrdoc, tg.datadoc, nao.denumire ,
    tg.cant/um.paritate, tg.cantum1s, tg.cantum2s, tg.cantum1d, tg.cantum2d, um.den_um1, um1.den_um, um2.den_um,
    coalesce(nca.den_clasea,''-''),
    (case when tg.cant=0 then 0 else tg.vas*um.paritate/tg.cant end),
    (case when tg.cant=0 then 0 else tg.vad*um.paritate/tg.cant end),
    (case when tg.cant=0 then 0 else tg.vis*um.paritate/tg.cant end),
    (case when tg.cant=0 then 0 else tg.vid*um.paritate/tg.cant end),
    CASE
      WHEN coalesce(nao1.tippretmax,0) IN (1,2,3) AND COALESCE(tg.pumaximals,t1.pumaximal, 0) &gt; 0 THEN coalesce(tg.pumaximals,t1.pumaximal)
      WHEN coalesce(nao1.tippretmax,0) IN (4,5,6) AND coalesce(nao1.pretmaximal,0) &gt; 0            THEN nao1.pretmaximal
      ELSE 0
    END*um.paritate,
    CASE
      WHEN coalesce(nao1.tippretmax,0) IN (1,2,3) AND COALESCE(tg.pumaximald,t1.pumaximal, 0) &gt; 0 THEN coalesce(tg.pumaximald,t1.pumaximal)
      WHEN coalesce(nao1.tippretmax,0) IN (4,5,6) AND coalesce(nao1.pretmaximal,0) &gt; 0            THEN nao1.pretmaximal
      ELSE 0
    END*um.paritate,
    tg.vas, tg.vad, tg.vis, tg.vid,
    tg.operat, (case tg.tipserie when 0 then ''fara serie'' when 1 then ''serie pe bucata'' when 2 then ''serie pe lot'' end),
    coalesce(ser.serii,''-''), coalesce(ser.tg,''-''),  coalesce(ser.seriedata,''-''),  coalesce(ser.ser,''-''),  coalesce(ser.sertg,''-''),  coalesce(ser.sercant,''-''),
    tva1.procent, prod.den_part, (case when tg.cant=0 then 0 else (vpinrtvas_ctva + vpinrtvas_ftva *  (100 + tva1.procent) / 100)*um.paritate/tg.cant end),
    cs.simbol, cd.simbol, row_number() over() as rownum,
    objmat.denumire, ummat.den_um, mat.cant*tg.cant, mat.pret, (case when ret.tipreteta=1 then ''Agregare'' else ''Dezagregare'' end),
    n_gs.den_gest, n_gd.den_gest ' || coalesce(sSelectUMA,'') || gUserAlias || '
  FROM tg
    LEFT JOIN transf         t      ON t.codtransf       = tg.codtransf
    LEFT JOIN transf1        t1     ON t1.codtransf1     = tg.codtransf1
    LEFT JOIN nartobj        nao    ON nao.codobiect     = tg.codobiect
    LEFT JOIN nart           na     ON na.codarticol     = nao.codarticol
    LEFT JOIN num1           um     on um.codum1         = tg.umsec
    LEFT JOIN num            um1    on um1.codum         = na.um1
    LEFT JOIN num            um2    on um2.codum         = na.um2
    LEFT JOIN nclasea        nca    ON nca.codclasea     = na.clasa
    LEFT JOIN nart1          na1    ON na1.codarticol    = nao.codarticol AND (tg.an*12+tg.luna) between  na1.alstart and  na1.alstop
    LEFT JOIN ntva1          tva1   ON tva1.codtva       = na1.codtva     AND (tg.an*12+tg.luna) between tva1.alstart and tva1.alstop
    LEFT JOIN nartobj1       nao1   ON nao1.codobiect    = tg.codobiect   AND (tg.an*12+tg.luna) between nao1.alstart and nao1.alstop
    LEFT JOIN npart          prod   ON prod.codpart      = nao.codproducator
    LEFT JOIN pretm          pm     ON pm.codobiect      = tg.codobiect   AND pm.subunitatea = t.subunitatea AND pm.implicit = 1
    LEFT JOIN tmp_ioart_luna io1s   ON io1s.codioart     = tg.conts
    LEFT JOIN IOART          IOAS   ON IOAS.CODIOART     = IO1S.CODIOART
    LEFT JOIN ncont          cs     ON cs.codcont        = io1s.cont
    LEFT JOIN tmp_ioart_luna io1d   ON io1d.codioart     = tg.contd
    LEFT JOIN IOART          IOAD   ON IOAD.CODIOART     = IO1D.CODIOART
    LEFT JOIN ncont          cd     ON cd.codcont        = io1d.cont
    LEFT JOIN prodcomp       ret    ON ret.codprodcomp   = t1.codreteta
    LEFT JOIN prodmat        mat    ON mat.codprodcomp   = t1.codreteta
    LEFT JOIN nartobj        objmat ON objmat.codobiect  = mat.codobiect
    LEFT JOIN nart           artmat ON objmat.codarticol = artmat.codarticol
    LEFT JOIN num            ummat  ON artmat.um         = ummat.codum
    LEFT JOIN ngest          n_gs   ON n_gs.codgest      = tg.gest
    LEFT JOIN ngest          n_gd   ON n_gd.codgest      = tg.gestdest
    LEFT JOIN ser                   ON ser.codtransf1    = tg.codtransf1 AND ser.conts = tg.conts AND ser.contd = tg.contd AND ser.gest = tg.gest
    LEFT JOIN PRETM          PRETM  ON PRETM.CODOBIECT   = NAO.CODOBIECT AND PRETM.IMPLICIT = 1  and PRETM.SUBUNITATEA = T.SUBUNITATEA' || coalesce(sJoinUMA,'') || gSuplJoins || '
  ORDER BY tg.indexlocal ';

  sSelectNOK := '
  SELECT
    (case t.tipdoc when 12 then ''Transf. '' when 13 then ''Modif. pret '' end)||t.prefixdoc||t.nrdoc||'' / ''||to_char(t.datadoc,''dd.mm.yyyy'') as document,
    t.prefixdoc, t.nrdoc, t.datadoc, nao.denumire,
    t1.cant/um.paritate, NULL CantUM1, NULL CantUM2, NULL CantUM1D, NULL CantUM2D, um.den_um1, um1.den_um, um2.den_um,
    coalesce(nca.den_clasea,''-''), t1.pu * um.paritate, t1.pu * um.paritate, t1.pu * um.paritate, t1.pu * um.paritate,
    CASE WHEN coalesce(nao1.tippretmax,0) IN (1,2,3) AND coalesce(t1.pumaximal, 0) &gt; 0 THEN t1.pumaximal WHEN coalesce(nao1.tippretmax,0) IN (4,5,6) AND coalesce(nao1.pretmaximal,0) &gt; 0 THEN nao1.pretmaximal ELSE 0 END * um.paritate,
    CASE WHEN coalesce(nao1.tippretmax,0) IN (1,2,3) AND coalesce(t1.pumaximal, 0) &gt; 0 THEN t1.pumaximal WHEN coalesce(nao1.tippretmax,0) IN (4,5,6) AND coalesce(nao1.pretmaximal,0) &gt; 0 THEN nao1.pretmaximal ELSE 0 END * um.paritate,
    t1.pu * t1.cant, t1.pu * t1.cant, t1.pu * t1.cant, t1.pu * t1.cant,
    (case when t.operat=0 then ''Nu'' else ''Da'' end) operat,
    (case na.tipserie when 0 then ''fara serie'' when 1 then ''serie pe bucata'' when 2 then ''serie pe lot'' end),
    ''-'' SERII, ''-'' DATAEXP, ''-'' SERIEDATA, ''-'' SER, ''-'' SERTG, ''-'' SERCANT,
    tva1.procent, prod.den_part, 0, cs.simbol, cd.simbol, row_number() over() as rownum,
    objmat.denumire, ummat.den_um, mat.cant*t1.cant, mat.pret,
    (case when ret.tipreteta=1 then ''Agregare'' else ''Dezagregare'' end), null, null ' || coalesce(sSelectUMA,'') || gUserAlias || '
  FROM transf t
    LEFT JOIN transf1  t1     ON t1.codtransf      = t.codtransf
    LEFT JOIN nartobj  nao    ON nao.codobiect     = t1.codobiect
    LEFT JOIN nart     na     ON na.codarticol     = nao.codarticol
    LEFT JOIN num1     um     on um.codum1         = t1.umsec
    LEFT JOIN num      um1    on um1.codum         = na.um1
    LEFT JOIN num      um2    on um2.codum         = na.um2
    LEFT JOIN nclasea  nca    ON nca.codclasea     = na.clasa
    LEFT JOIN nart1    na1    ON na1.codarticol    = nao.codarticol AND (t.an*12+t.luna) between  na1.alstart and  na1.alstop
    LEFT JOIN ntva1    tva1   ON tva1.codtva       = na1.codtva     AND (t.an*12+t.luna) between tva1.alstart and tva1.alstop
    LEFT JOIN nartobj1 nao1   ON nao1.codobiect    = t1.codobiect   AND (t.an*12+t.luna) between nao1.alstart and nao1.alstop
    LEFT JOIN npart    prod   ON prod.codpart      = nao.codproducator
    LEFT JOIN pretm    pm     ON pm.codobiect      = t1.codobiect   AND pm.subunitatea = t.subunitatea AND pm.implicit = 1
    LEFT JOIN IOART    IOAS   ON IOAS.CODIOART     = (t.codtransf - t.codtransf)
    LEFT JOIN IOART    IOAD   ON IOAD.CODIOART     = (t.codtransf - t.codtransf)
    LEFT JOIN ncont    cs     ON cs.codcont        = (t.codtransf - t.codtransf)
    LEFT JOIN ncont    cd     ON cd.codcont        = (t.codtransf - t.codtransf)
    LEFT JOIN prodcomp ret    ON ret.codprodcomp   = t1.codreteta
    LEFT JOIN prodmat  mat    ON mat.codprodcomp   = t1.codreteta
    LEFT JOIN nartobj  objmat ON objmat.codobiect  = mat.codobiect
    LEFT JOIN nart     artmat ON objmat.codarticol = artmat.codarticol
    LEFT JOIN num      ummat  ON artmat.um         = ummat.codum
    LEFT JOIN PRETM    PRETM  ON PRETM.CODOBIECT   = NAO.CODOBIECT AND PRETM.IMPLICIT = 1 and PRETM.SUBUNITATEA = T.SUBUNITATEA' || coalesce(sJoinUMA,'') || gSuplJoins || '
  WHERE T.CODTRANSF =' || coalesce(vCodDoc,'') || '
  ORDER BY t1.indexlocal ';

  IF  vOk = 1 THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelectOK, aListID, aListVer);
  ELSE
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelectNOK, aListID, aListVer);
  END IF;

  PERFORM pkg_list_base_transfdoc_ProcessParams(vCodDoc::numeric);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_livrtransf_processparams</obj_name>
  <obj_hashval>302bd189b2fc78711668b8c5b509ee6e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_livrtransf_processparams()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC       RECORD;
  vDGest       varchar;
  vGGest       varchar;
  vCodGest    NUMERIC := current_setting('PKG_LIST_BASE_LIVRTRANSF.vCodGest',   true)::NUMERIC;
  vCodTransf  NUMERIC := current_setting('PKG_LIST_BASE_LIVRTRANSF.vCodTransf', true)::NUMERIC;
BEGIN
   --Florin 10.04.2024 - fixat 61640
   -- Bogdan 10.03.2022 - corectie sinc oracle 53357
   --Florin 04.03.2022 - sinc. Oracle
  -- Bogdan 01.02.2022 - 52843  parametrii de tip "specific lista"si "Doc.Livr.Numar", "Doc.Livr.Data", "Doc.Livr.Obs"  (ca la livrare iesiri)
  -- Bogdan 19.01.2022
  --Adina 18 septembrie 2020
  PERFORM pkg_list_Struct_GOLESTE_PARAM();

  IF  vCodGest &gt; 0 THEN
    SELECT G.Den_Gest, coalesce(NP.Nume,'') || ' ' || coalesce(NP.Prenume,'')
    INTO vDGest, vGGest
    FROM   NGEST G LEFT JOIN NPERS NP ON  G.CODGESTIONAR = NP.CODPERS
    WHERE G.CODGEST = vCodGest;
  ELSE
    vDGest := '';
    vGGest := '';
  END IF;

  PERFORM pkg_list_Struct_ADAUGA_PARAM('GESTIUNE', vDGest);
  PERFORM pkg_list_Struct_ADAUGA_PARAM('GESTIUNE GESTIONAR', vGGest);

  IF  vCodTransf &gt; 0 THEN
    DELETE FROM tmp_manevra_liste WHERE filtru = 'CODTRANSF';
    INSERT INTO tmp_manevra_liste(FILTRU, VALOARE) VALUES('CODTRANSF', vCodTransf::varchar);
  END IF;

  FOR v_rec IN (SELECT
                  fnc_array_to_vc3200(array_agg(DISTINCT T.PREFIXDOC                     ORDER BY T.PREFIXDOC)) PREFIXDOC,
                  fnc_array_to_vc3200(array_agg(DISTINCT T.NRDOC::varchar                ORDER BY T.NRDOC::varchar)) NRDOC,
                  fnc_array_to_vc3200(array_agg(DISTINCT To_Char(T.DATADOC,'dd.mm.yyyy') ORDER BY To_Char(T.DATADOC,'dd.mm.yyyy'))) DATADOC,
                  fnc_array_to_vc3200(array_agg(DISTINCT T.OBS                           ORDER BY T.OBS)) OBS
                FROM   tmp_manevra_liste tmp LEFT JOIN TRANSF T ON  T.CODTRANSF = tmp.valoare :: numeric
                WHERE tmp.filtru = 'CODTRANSF'
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT',         v_rec.PREFIXDOC);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT NUMAR',   v_rec.NRDOC    );
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT DATA',   v_rec.DataDoc  );
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOCUMENT OBS',     v_rec.OBS      );
    EXIT ;
  END LOOP;

  FOR v_rec IN (SELECT
                  fnc_array_to_vc3200(array_agg(DISTINCT L.NRLIVR||'/'||TO_CHAR(L.DATALIVR,'DD.MM.YYYY')  ORDER BY L.NRLIVR||'/'||TO_CHAR(L.DATALIVR,'DD.MM.YYYY'))) DOCLIVR
                FROM tmp_manevra_liste tmp
                     LEFT JOIN TRANSF T ON  T.CODTRANSF = tmp.valoare :: numeric
                     left join LIVR L on L.CODTRANSF = T.CODTRANSF
                WHERE tmp.filtru = 'CODTRANSF'
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('LIVRARE DOCUMENT', v_rec.DOCLIVR);
    EXIT ;
  END LOOP;

  PERFORM pkg_list_Struct_ADAUGA_PARAM('MASA FACTURATA', '0.00');
  PERFORM pkg_list_Struct_ADAUGA_PARAM('VOLUM FACTURAT', '0.00');
  PERFORM pkg_list_Struct_ADAUGA_PARAM('FILTRU', '');

  FOR v_rec IN (SELECT   T.TIPDOC, T.SERIADOC, T.NRDOC, T.DATADOC, T.VALDOC, T.NRAE, T.OBS,
                        CG.Den_Gest CMDGEST, CS.TELEFON CMDTELEFON, CL.DEN_LOCALIT CMDLOCALIT, CJ.Den_Judet CMDJUDET,
                        fnc_GetAdresa(CS.sector, CS.strada, CS.nr1, CS.nr2, CS.bloc, CS.scara, CS.etaj, CS.apart, CS.codpostal) CMDADRESA,
                        COALESCE(U.Nume, '...nedefinit...') UNUME, COALESCE(U.Prenume, '...nedefinit...') UPRENUME,
                        COALESCE(U.CNP, '...nedefinit...') UCNP, coalesce(U.BISERIA,'') || ' ' || coalesce(U.BINR::varchar ,'') UBI,
                        D.Delegat DEL, D.DOC DELDOC, D.NRDOC DELNRDOC, D.SERIEDOC DELSERIEDOC, D.ELIBERAT DELELIBERAT,
                        D.CNP DELCNP, D.DATADOC DELDATADOC, T.MIJLTRANSP DELMIJLTRANSP, T.NRTRANSP DELNRTRANSP
                FROM   tmp_manevra_liste tmp
                      LEFT JOIN TRANSF T     ON  T.CODTRANSF = tmp.valoare :: numeric
                      LEFT JOIN NPARTTR D   ON  T.DELEGAT     = D.CODPARTTR
                      LEFT JOIN NGEST CG     ON  CG.CODGEST    = T.CODGESTCMD
                      LEFT JOIN NAGENDA CS   ON  CS.CODGEST    = CG.CODGEST
                      LEFT JOIN NLOCALIT CL ON  CL.CODLOCALIT = COALESCE(CS.CODLOCALIT, 0)
                      LEFT JOIN NJUDET CJ   ON  CJ.CODJUDET   = COALESCE(CL.CODJUDET, 0)
                      LEFT JOIN NPERS U     ON  U.LOGONNAME   = T.USERID
                WHERE tmp.filtru = 'CODTRANSF'
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COMANDA GESTIUNE',             v_rec.CMDGest      );
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COMANDA GESTIUNE JUDET',       v_rec.CMDJudet     );
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COMANDA GESTIUNE LOCALITATE', v_rec.CMDLocalit   );
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COMANDA GESTIUNE ADRESA',     v_rec.CMDAdresa    );
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COMANDA GESTIUNE TELEFON',     v_rec.CMDTelefon   );
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DELEGAT',           v_rec.DEL          );
    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.DELSERIEDOC  );
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT DOC ELIBERAT',       v_rec.DELELIBERAT  );
    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.DELMIJLTRANSP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('TRANSPORT NR MIJLOC',         v_rec.DELNRTRANSP  );
    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(NrLivr::varchar,',') as NrLivr,
       STRING_AGG(DataLivr,',') as DataLivr,
       STRING_AGG(ObsLivr,',') as ObsLivr,
       STRING_AGG(ZiLivr::varchar,',') as ZiLivr
    FROM (
      SELECT
        DISTINCT L.NRLIVR, To_Char(L.DATALIVR,'dd.mm.yyyy') DataLivr, L.OBS ObsLivr, EXTRACT(DAY FROM L.DATALIVR) ZiLivr
      FROM LIVR1_MAN tmp
        INNER JOIN livr l ON l.CODLIVR = tmp.CODLIVR
    ) A_PG
  ) LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOC.LIVR.NUMAR', v_rec.NrLivr);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOC.LIVR.DATA',  v_rec.DataLivr);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOC.LIVR.OBS',   v_rec.ObsLivr);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('DOC.LIVR.ZI',    v_rec.ZiLivr);
    EXIT;
  END LOOP;

  FOR v_rec IN (SELECT   PK.NRDOC, DC.SERIE, PK.NRPACHETE, PK.IDENTIFICATORP, PK.DATAP, coalesce(PC.NUME,'') || ' ' || coalesce(PC.PRENUME,'') PCC,
                        coalesce(PV.NUME,'') || ' ' || coalesce(PV.PRENUME,'') PVV, coalesce(PT.NUME,'') || ' ' || coalesce(PT.PRENUME,'') PTT,
                        PK.DATACOLECTARE, PK.DATAVERIFICARE, PK.DATATRANSPORT
                FROM   tmp_manevra_liste tmp
                      LEFT JOIN TRANSF     T   ON  T.CODTRANSF = tmp.valoare :: numeric
                      LEFT JOIN PACHETE1   PK1 ON  T.CODTRANSF      = PK1.CODDOC
                      LEFT JOIN PACHETE    PK  ON  PK1.CODPACHETE   = PK.CODPACHETE
                      LEFT JOIN DOCCARNETE DC  ON  PK.CARNETDOC     = DC.CODCARNET
                      LEFT JOIN NPERS      PC  ON  PK.COLECTOR      = PC.CODPERS
                      LEFT JOIN NPERS      PV  ON  PK.VERIFICATOR   = PV.CODPERS
                      LEFT JOIN NPERS      PT  ON  PK.TRANSPORTATOR = PT.CODPERS
                WHERE tmp.filtru = 'CODTRANSF'
               )
  LOOP
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET SERIE',                   v_rec.SERIE);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET NUMAR',                   v_rec.NRDOC::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET NUMAR PACHETE',           v_rec.NRPACHETE::varchar);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET DATA',                     to_char(v_rec.DATACOLECTARE,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET Identificator',           v_rec.IDENTIFICATORP);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET PERSOANA COLECTARE',       to_char(v_rec.DATACOLECTARE,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET DATA COLECTARE',           v_rec.PCC);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET PERSOANA VERIFICATOARE',   v_rec.PVV);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET DATA VERIFICARE',         to_char(v_rec.DATAVERIFICARE,'dd.mm.yyyy'));
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET TRANSPORT PERSOANA',       v_rec.PTT);
    PERFORM pkg_list_Struct_ADAUGA_PARAM('COLET TRANSPORT DATA',           to_char(v_rec.DATATRANSPORT,'dd.mm.yyyy'));
    EXIT ;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_modifpretdoc_processlist</obj_name>
  <obj_hashval>bb64bbf2c3c4358f8002549f1c8a9bb3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_modifpretdoc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert          varchar := '';
  sSelect          varchar := '';
  vAux             numeric := PKG_LIST_BASE_UTILS_CT_MODIFPRET();

  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          NUMERIC := current_setting('PKG_LIST_BASE_MODIFPRETDOC.vCodDoc', true)::NUMERIC;
BEGIN
  --Stef 14.07.2022
  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_MODIFPRETDOC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  PERFORM pkg_list_base_modifpretdoc_bagaNirCuSerii();

  sInsert :=
  'INSERT INTO ' || tmpName || '(
    Document,PrefixDoc,Nrdoc,DataDoc,ART,
    Cant,CantUM1,CantUM2,UM,UMALT1,UMALT2,
    ClasaA,Gest_Sursa,Cont_sursa,CONTDIFPRET,
    PUAchiz_S,PUAchiz_D,PUInreg_S,PUInreg_D,
    PretMax_S,PretMax_D,
    VALACH_S,VALACH_D,VALINREG_S,VALINREG_D,
    Operat, TIPSERIE,
    SERII,DATAEXP,SERIEDATA,
    PROCTVA, PRODUCATOR, PUInregTVA_S, NrUnic' || gUserFields || ') ';

  sSelect := '
  WITH tg AS (
    SELECT
      CASE
        WHEN t.tipdoc = 12 THEN ''Transf. ''||t.prefixdoc||t.nrdoc::varchar||'' / ''||to_char(t.datadoc,''dd.mm.yyyy'')
        WHEN t.tipdoc = 13 THEN ''Modif. pret ''||t.prefixdoc||t.nrdoc::varchar||'' / ''||to_char(t.datadoc,''dd.mm.yyyy'')
        ELSE t.prefixdoc||t.nrdoc::varchar||'' / ''||to_char(t.datadoc,''dd.mm.yyyy'')
      END as document,
      t.codtransf, t.prefixdoc,t.nrdoc,t.datadoc,(case when t.operat=0 then ''Nu'' else ''Da'' end) operat, t.codpart, t.an, t.luna,
      t1.codtransf1, t1.indexlocal, t1.codobiect, t1.umsec, t1.codcont, coalesce(lv.gest,n_s.gest) gests, coalesce(lv.codioart,ns_s.codioart) codioarts,
      MAX(ns_d.tipserie) tipserie,
      SUM(ns_d.cantnir) cant, SUM(coalesce(ns_d.cantum1,0)) cantum1, SUM(coalesce(ns_d.cantum2,0)) cantum2,
      MAX(coalesce(ns_s.pumaximal,0)) pumaximals, MAX(coalesce(ns_d.pumaximal,0)) pumaximald,
      SUM(coalesce(lv.pretinreg,ns_s.pret)*ns_d.cantnir) valinregs, SUM(coalesce(lv.pretachiz, ns_s.pret - ns_s.adaos)*ns_d.cantnir) valachizs,
      SUM(ns_d.pret*ns_d.cantnir) valinregd, SUM((ns_d.pret - ns_d.adaos)*ns_d.cantnir) valachizd,
      SUM((case when coalesce(io1s.aretvaneex, 0)= 0 then coalesce(lv.pretinreg,ns_s.pret)*ns_d.cantnir else 0 end)) vpinrtvas_ftva,
      SUM((case when coalesce(io1s.aretvaneex, 0)= 0 then 0 else coalesce(lv.pretinreg,ns_s.pret)*ns_d.cantnir end)) vpinrtvas_ctva
    FROM transf t
      INNER JOIN transf1 t1   ON t1.codtransf    = t.codtransf
      INNER JOIN livr    l    ON l.codtransf     = t.codtransf
      INNER JOIN livr1   l1   ON l1.codlivr      = l.codlivr     AND l1.codies1 = t1.codtransf1
      INNER JOIN nartobj nobj ON nobj.codobiect  = t1.codobiect
      LEFT  JOIN nirstoc ns_s ON ns_s.codnirstoc = l1.codnirstoc
      LEFT  JOIN nir     n_s  ON n_s.codnir      = ns_s.codnir
      LEFT  JOIN ioart1  io1s ON io1s.codioart   = ns_s.codioart AND (t.an * 12 + t.luna) between io1s.alstart and io1s.alstop
      LEFT  JOIN livrval lv   on l1.codlivr1     = lv.codlivr1
      INNER JOIN nirstoc ns_d ON ns_d.codlivr1   = l1.codlivr1
      INNER JOIN nir     n_d  ON n_d.codnir      = ns_d.codnir
    WHERE L.CODTRANSF =' || coalesce(vCodDoc::varchar ,'') || '
    GROUP BY
      t.codtransf, t.tipdoc, t.prefixdoc, t.nrdoc, t.datadoc, t.codpart, t.operat, t.an, t.luna,
      t1.codtransf1, t1.indexlocal, t1.codobiect, t1.umsec, t1.codcont,coalesce(lv.gest,n_s.gest), coalesce(lv.codioart,ns_s.codioart)
  )
  SELECT
    tg.document, tg.prefixdoc, tg.nrdoc, tg.datadoc, nao.denumire ,
    tg.cant/um.paritate, tg.cantum1, tg.cantum2, um.den_um1, um1.den_um, um2.den_um,
    coalesce(nca.den_clasea,''-''), ngs.den_gest, ncs.simbol, ncdif.simbol,
    (case when tg.cant=0 then 0 else tg.valachizs*um.paritate/tg.cant end), (case when tg.cant=0 then 0 else tg.valachizd*um.paritate/tg.cant end),
    (case when tg.cant=0 then 0 else tg.valinregs*um.paritate/tg.cant end), (case when tg.cant=0 then 0 else tg.valinregd*um.paritate/tg.cant end),
    tg.pumaximals*um.paritate, tg.pumaximald*um.paritate,
    tg.valachizs, tg.valachizd, tg.valinregs, tg.valinregd,
    tg.operat, (case tg.tipserie when 0 then ''fara serie'' when 1 then ''serie pe bucata'' when 2 then ''serie pe lot'' end),
    coalesce(tmp_s.serii,''-''),  coalesce(tmp_tg.serii,''-''),  coalesce(tmp_stg.serii,''-''),
    tva1.procent, prod.den_part,
    (case when tg.cant=0 then 0 else (vpinrtvas_ctva + vpinrtvas_ftva *  (100 + tva1.procent) / 100)*um.paritate/tg.cant end),
    row_number() over() rownum ' || gUserAlias || '
  FROM tg
    LEFT JOIN transf            t       ON t.codtransf        = tg.codtransf
    LEFT JOIN transf1           t1      ON t1.codtransf1      = tg.codtransf1
    LEFT JOIN nartobj           nao     ON nao.codobiect      = tg.codobiect
    LEFT JOIN nart              na      ON na.codarticol      = nao.codarticol
    LEFT JOIN num1              um      on um.codum1          = tg.umsec
    LEFT JOIN num               um1     on um1.codum          = na.um1
    LEFT JOIN num               um2     on um2.codum          = na.um2
    LEFT JOIN nclasea           nca     ON nca.codclasea      = na.clasa
    LEFT JOIN nart1             na1     ON na1.codarticol     = nao.codarticol AND (tg.an*12+tg.luna) between  na1.alstart and  na1.alstop
    LEFT JOIN ntva1             tva1    ON tva1.codtva        = na1.codtva     AND (tg.an*12+tg.luna) between tva1.alstart and tva1.alstop
    LEFT JOIN npart             prod    ON prod.codpart       = nao.codproducator
    LEFT JOIN ngest             ngs     ON ngs.codgest        = tg.gests
    LEFT JOIN tmp_ioart_luna    io1s    ON io1s.codioart      = tg.codioarts
    LEFT JOIN ncont             ncs     ON ncs.codcont        = io1s.cont
    LEFT JOIN ncont             ncdif   ON ncdif.codcont      = tg.codcont
    LEFT JOIN tmp_manevra_serii tmp_s   ON tmp_s.codnirstoc   = tg.codtransf1 AND tmp_s.codlivr1   = tg.gests AND tmp_s.codaux1   = tg.codioarts AND tmp_s.flag   = ' || coalesce((vAux)::varchar,'') || '
    LEFT JOIN tmp_manevra_serii tmp_tg  ON tmp_tg.codnirstoc  = tg.codtransf1 AND tmp_tg.codlivr1  = tg.gests AND tmp_tg.codaux1  = tg.codioarts AND tmp_tg.flag  = ' || coalesce((vAux + 2000)::varchar,'') || '
    LEFT JOIN tmp_manevra_serii tmp_stg ON tmp_stg.codnirstoc = tg.codtransf1 AND tmp_stg.codlivr1 = tg.gests AND tmp_stg.codaux1 = tg.codioarts AND tmp_stg.flag = ' || coalesce((vAux + 1000)::varchar,'') || gSuplJoins || '
  ORDER BY tg.indexlocal ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
  PERFORM pkg_list_base_transfdoc_ProcessParams(vCodDoc);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_naproviz6_umpletabela6z</obj_name>
  <obj_hashval>deddfecc3d245b23de8796b1581b74f2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_naproviz6_umpletabela6z(adataref character varying, pclasa numeric DEFAULT 0, pclasas numeric DEFAULT 0, pprod numeric DEFAULT 0, pclasaw numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  vAnLunaLucru numeric := getAnLunaLucru();
BEGIN
  --Florin 06.02.2023 - sinc. Oracle
  --Adina 14.07.2021 - sinc.Oracle din 14.07.2021
  --Adina 20.04.2021 - sinc.Oracle
  --Adina 02 septembrie 2020 - netestata pt.ca nu stiu unde e apelata
  --Florin 07.12.2020 - fixat #41270

  DELETE FROM tmp_lst_napr6;
  INSERT INTO tmp_lst_napr6(denumire, stocmin, stoc, codintern, codextern, um, codum1, codobiect, subunitatea, den_subunit, producator,
                            zile, datacmd, codpart, peraproviz, ULTPRACHIZ, codcatalog
                           )
  WITH
  Ach AS
  (
    SELECT  DISTINCT i1.codobiect, i.partener, COALESCE(ps.peraproviz, 0) PERAPROVIZ
    FROM   intrari i
          INNER JOIN intrari1     i1  ON  i1.codintr     = i.codintr
          INNER JOIN npart        p   ON  p.codpart      = i.partener
          INNER JOIN nartobj      obj ON  obj.codobiect  = i1.codobiect
          INNER JOIN nart         art ON  art.codarticol = obj.codarticol
          LEFT  JOIN npartsubunit ps  ON  ps.codpart     = p.codpart and  ps.subunitatea = i.subunitatea
    WHERE i.anulat = 0 and  p.codpart &gt; 0 and  i.subunitatea = current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric and  art.tiparticol = '0'
          and (pClasa = 0 or  art.clasa = pClasa)  and (pClasaS = 0 or  art.clasastatist = pClasaS)
          and (pClasaW = 0 or  art.clasaw = pClasaW)  and (pProd = 0 or  obj.codproducator = pProd)
          and i.tipdoc in (1,2,3,4,5)
    ORDER BY i.partener , i1.codobiect
  ),
  LastCmd AS
  (
    SELECT  DISTINCT partener, codobiect, datadoc, LastPretCmd
    FROM (
          SELECT x.partener, x.codobiect, x.datadoc, min(c1.pu) LASTPRETCMD
          FROM (
                SELECT c.partener, c1.codobiect, max(c.datadoc) DATADOC
                FROM   comanda c INNER JOIN comanda1 c1 ON  c1.codcomanda = c.codcomanda
                WHERE c.tipdoc = 8 and  c.subunitatea = current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric
                GROUP BY c.partener, c1.codobiect
               )  x
                  INNER JOIN comanda  c  ON  c.datadoc     = x.datadoc    and  c.partener   = x.partener
                  INNER JOIN comanda1 c1 ON  c1.codcomanda = c.codcomanda and  c1.codobiect = x.codobiect
          WHERE c.tipdoc = 8 and  c.subunitatea = current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric
          GROUP BY x.partener, x.codobiect, x.datadoc
         ) A_PG
  ),
  Stoc AS
  (
    SELECT
      ns.codobiect,
      sum(CASE WHEN  NS.TIPSERIE &gt; 0 THEN NSE.REST ELSE NS.REST END) CANT
    FROM  nirstoc ns
          INNER JOIN nir                    ON  nir.codnir    = ns.codnir
          INNER JOIN ngest          g       ON  nir.gest      = g.codgest
          LEFT  JOIN nirser         nse     ON  ns.codnirstoc = nse.codnirstoc
          LEFT  JOIN ioart1         io1     ON  io1.codioart = ns.codioart AND vAnLunaLucru BETWEEN io1.ALStart AND io1.ALStop
    WHERE nir.operat = 1 AND g.codsubunit = current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric AND  io1.MG &lt;&gt; 5
    GROUP BY ns.codobiect
  )
  SELECT  obj.denumire, objs.stocmin, stoc.cant, obj.codintern, obj.codextern, num1.den_um1, num1.codum1, obj.codobiect,
          current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric,
          (SELECT den_subunit FROM nsubunit WHERE codsubunit = current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric) DEN_SUBUNIT,
          prod.den_part, to_date(aDataRef, 'dd.mm.yyyy') - lastcmd.datadoc::DATE ZILE, lastcmd.datadoc DATACMD,
          ach.partener CODPART, ach.peraproviz, lastcmd.LastPretCmd,
          CASE
             WHEN art.codexternart   IS NULL  THEN art.sufixcodextern
             WHEN art.sufixcodextern IS NULL  THEN art.codexternart
             ELSE coalesce(art.codexternart,'') || '_' || coalesce(art.sufixcodextern::varchar ,'')
           END
  FROM   Ach
        INNER JOIN nartobj        obj  ON  obj.codobiect    = ach.codobiect
        INNER JOIN nart           art  ON  obj.codarticol   = art.codarticol
        INNER JOIN npart          p    ON  p.codpart        = ach.partener
        INNER JOIN num                 ON  num.codum        = art.um
        INNER JOIN num1                ON  num1.codum       = num.codum and  num1.secundara = 0
        LEFT  JOIN lastcmd             ON  lastcmd.partener = ach.partener and  lastcmd.codobiect = ach.codobiect
        LEFT  JOIN nartobjsubunit objs ON  objs.codobiect   = obj.codobiect
                                           and (objs.codgest is null or objs.codgest = 0)
                                           and  objs.subunitate = current_setting('PKG_GLOBALS.SUBUNITATE', true)::numeric
        LEFT  JOIN stoc                ON  stoc.codobiect   = obj.codobiect
        LEFT  JOIN npart          prod ON  prod.codpart     = COALESCE(obj.codproducator, 0)
  WHERE EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE valoare = ach.partener::varchar and  filtru = 'CODPART');

  UPDATE tmp_lst_napr6 tmp
  SET
    vanzari = ( SELECT sum(i1.cant)
                FROM iesiri1 i1 INNER JOIN iesiri i ON  i.codies = i1.codies
                WHERE i.anulat = 0 and i.datadoc BETWEEN tmp.datacmd + 1 AND TO_DATE(aDataRef, 'DD.MM.YYYY') and  i1.codobiect = tmp.codobiect
                      and  i.subunitatea = current_setting('PKG_GLOBALS.SUBUNITATE', true)::NUMERIC
                      and i.tipdoc in (16,19,20,21)
              );

  UPDATE tmp_lst_napr6
  SET
    rata = COALESCE(vanzari, 0) / zile
  WHERE COALESCE(zile, 0) &gt; 0;

  UPDATE tmp_lst_napr6 tmp
  SET
    necesar = CASE
                 WHEN COALESCE(vanzari, 0) + COALESCE(stocmin, 0) - COALESCE(stoc, 0) &lt; 0 THEN 0
                 ELSE COALESCE(vanzari, 0) + COALESCE(stocmin, 0) - COALESCE(stoc, 0)
               END ;

  UPDATE tmp_lst_napr6 SET necesart = necesar;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nart_guserfields</obj_name>
  <obj_hashval>fad071d12010e01f6938f715503ce4e6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nart_guserfields(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := (current_setting('PKG_LIST_BASE_NART.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_nart_setgnullalias</obj_name>
  <obj_hashval>cd093e79bb43e2204d0edfd61ebde9ff</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nart_setgnullalias(agnullalias character varying)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
perform set_config('PKG_LIST_BASE_NART.gNullAlias',agNullAlias,false);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_nc_processlist</obj_name>
  <obj_hashval>3e1971cfcebfab5666c2d0db4ea0cbf9</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_nc_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;
  sAnLunaLucru varchar;
BEGIN
  --Adina 10.05.2021 - alstart,alstop, sAnLunaLucru
  CALL PRC_AL_CHECK('ncont1',0);
  sAnLunaLucru := coalesce(to_char((select PKG_GLOBALS_AnLunaLucru.WME_RESULT from PKG_GLOBALS_AnLunaLucru(null, null)), 'fm99999'), '0');

  gSuplCols := 'NC N, NC1 N1, NMONEDE M, NGEST G, NPARCAUT PAUT, NPART NPD, NPART NPC, NCONT NCD, NCONT NCC, NCONT1 NC1D, NCONTS CSD, NCONT1 NC1C, NCONTS CSC, CENTRECOST CC, '||
    'ANALIZANOD ANOD, ANALIZA ANALIZ, DESCRIPTORI1 ADESC1, DESCRIPTORI ADESC, NPERS AGENT, FORMATII FORM';

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

  sInsert := 'INSERT INTO ' || coalesce(tmpName, '') || '(
        NAV_CODDOC,NAV_TIPDOC, DOC, NUMAR, DATADOC, Observatii, MONEDA, CURS, NrLinie, TipLTva, SimbContDebit, SimbContCredit, PartDebit, PartCredit,
        Valoare, Gestiune, Obs1, Subunit, SimbContSD, SimbContSC, CentruCost, Transport' || gUserFields || ')
      SELECT
        N.CODNC, 35 as TIPD, N.NRDOC as DOC, N.NRDOC, N.DATADOC, N.OBS, M.SIMBOL, N.CURS, N1.INDEXLOCAL,
        (Case When N1.TIPLINIETVA= 2 then  ''Baza TVA stocuri''
               When N1.TIPLINIETVA= 3 then  ''Val. TVA stocuri''
              When N1.TIPLINIETVA= 4 then  ''Baza TVA servicii''
              When N1.TIPLINIETVA= 5 then  ''Val. TVA servicii''
              else ''-'' end),
        NCD.SIMBOL, NCC.SIMBOL,
        (Case  When N1.PARTD=1 then NPD.DEN_PART else ''--'' end),
        (Case  When N1.PARTC=1 then NPC.DEN_PART else ''--'' end),
        N1.VALOARE, G.DEN_GEST ,N1.Obs, NS.DEN_SUBUNIT, CSD.Simbol, CSC.Simbol, CC.Denumire, PAUT.NRINREG ' || gUserAlias || '
      FROM NC N
        LEFT JOIN NC1          N1     ON N1.CODNC              = N.CODNC
        LEFT JOIN NMONEDE      M      ON M.CODMONEDA           = N.Moneda
        LEFT JOIN NSUBUNIT     NS     ON NS.CODSUBUNIT         = N.SUBUNITATEA
        LEFT JOIN NGEST        G      ON G.CODGEST             = N1.CODGEST
        LEFT JOIN NPARCAUT     PAUT   ON PAUT.CODNPARCAUT      = N1.CODAUTO
        LEFT JOIN NPART        NPD    ON NPD.CODPART           = CASE WHEN COALESCE(N1.PARTD,0) = 0 THEN 0 WHEN COALESCE(N1.CODPART,0) &lt;&gt; 0 THEN N1.CODPART ELSE N.PART END
        LEFT JOIN NCONT        NCD    ON NCD.CODCONT           = CASE WHEN N1.PARTD = 1 THEN ( PKG_LIST_BASE_UTILS_iCont_CodCont(N1.ICONTD, NPD.CODPART, N.AN*12+N.LUNA, 1200::numeric))
                                                                      WHEN N1.PERSD = 1 THEN (PKG_LIST_BASE_UTILS_iCont_CodCont(N1.ICONTD, N1.AGENT,    N.AN*12+N.LUNA, 1100::numeric))
                                                                      ELSE N1.CONTD
                                                                 END
        LEFT JOIN NCONT1       NC1D   ON NC1D.CODCONT          = NCD.CODCONT AND '||sAnLunaLucru||' BETWEEN NC1D.ALSTART and NC1D.ALSTOP
        LEFT JOIN NCONTS       CSD    ON CSD.CODCONTS          = NC1D.CONTSECUNDAR
        LEFT JOIN NPART        NPC    ON NPC.CODPART           = CASE WHEN COALESCE(N1.PARTC,0) = 0 THEN 0 WHEN COALESCE(N1.CODPART,0) &lt;&gt; 0 THEN N1.CODPART ELSE N.PART END
        LEFT JOIN NCONT        NCC    ON NCC.CODCONT           = CASE WHEN N1.PARTC = 1 THEN (PKG_LIST_BASE_UTILS_iCont_CodCont(N1.ICONTC, NPC.CODPART, N.AN*12+N.LUNA, 1201::numeric))
                                                                      WHEN N1.PERSC = 1 THEN (PKG_LIST_BASE_UTILS_iCont_CodCont(N1.ICONTC, N1.AGENT,    N.AN*12+N.LUNA, 1101::numeric))
                                                                      ELSE N1.CONTC
                                                                 END
        LEFT JOIN NCONT1       NC1C   ON NC1C.CODCONT          = NCC.CODCONT AND '||sAnLunaLucru||' BETWEEN NC1C.ALSTART and NC1C.ALSTOP
        LEFT JOIN NCONTS       CSC    ON CSC.CODCONTS          = NC1C.CONTSECUNDAR
        LEFT JOIN CENTRECOST   CC     ON CC.CODCENTRU          = CASE WHEN coalesce(N1.CODCENTRU,0) &gt; 0 THEN N1.CODCENTRU WHEN coalesce(NC1D.CODCENTRU,0) &gt; 0 THEN NC1D.CODCENTRU ELSE coalesce(NC1C.CODCENTRU,0) END
        LEFT JOIN ANALIZANOD   ANOD   ON anod.codanalizanod    = n1.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
        LEFT JOIN NPERS        AGENT  ON AGENT.CODPERS         = N1.AGENT
        LEFT JOIN FORMATII     FORM   ON FORM.CODFORMATIE      = N1.CODFORMATIE' || gSuplJoins || '
      WHERE N.AN*12+N.LUNA = ' || sAnLunaLucru || '
        AND coalesce(N.SABLON,0) = 0 ' || coalesce((select PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT from PKG_LIST_BASE_UTILS_COND_SUBUNIT(null, 'N', null, null, null)), '');

  if not (SELECT pkg_globals_GET_DREPT_SALARIZARE.WME_RESULT FROM pkg_globals_GET_DREPT_SALARIZARE(null, null)) = 1 then
    sInsert := coalesce(sInsert, '') || ' AND N.JurnalTVA &lt;&gt; 5';
  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_ncont_setjoinuri</obj_name>
  <obj_hashval>b6420d5b4b183d88dc5b5fe4ec5ec0d1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_ncont_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_NCONT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_niries_setjoinuri</obj_name>
  <obj_hashval>8c72e524107611ea5d387a1175f2cb40</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_niries_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 16.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_NIRIES.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_notecreditt_setjoinuri</obj_name>
  <obj_hashval>12c61af8874c8e9b5c9e428b3a3c9f93</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_notecreditt_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 01 octombrie 2020
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_NOTECREDITT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_np_m_setjoinuri</obj_name>
  <obj_hashval>d69047a94b6dc3b466022cc152fad75d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_np_m_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  PERFORM Pkg_List_Struct_SetTableSpec( (current_setting('PKG_LIST_BASE_NP_M.gSuplCols', true)));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_pfsdv_setjoinuri</obj_name>
  <obj_hashval>266b22e500cd8c5c97364a8ed89f1f15</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_pfsdv_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.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_planifcmd_centr_setjoinuri</obj_name>
  <obj_hashval>2e199e85146305d3c68a1a26b8cb4ccd</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_planifcmd_centr_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 14.10.2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_PLANIFCMD_CENTR.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_proiect_processlist</obj_name>
  <obj_hashval>7ce91b51685f2316edaec49593b02f0f</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_proiect_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sString          varchar := '';
  aCodComanda      numeric;
  gSuplCols        VARCHAR := 'proiectnod nod, nartobj obj, nart art, num um, nartobjsubunit objsub, nclasea cls, proiect prj, nartobj objprj, prodmat mat';
  gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  p_CodComanda1    NUMERIC := CASE WHEN current_setting('PKG_LIST_BASE_UTILS.p_CodComanda1', TRUE) = '' THEN 0
                                   else current_setting('PKG_LIST_BASE_UTILS.p_CodComanda1', TRUE)::NUMERIC END;
BEGIN
  --Adina 20.04.2021 - sinc.Oracle
  --Adina 15.10.2020
  --Florin 12.01.2021 - fixat 41868
  IF p_CodComanda1 &gt; 0   THEN
    gSuplCols := gSuplCols||',Comanda1 C1';
  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_PROIECT.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF  p_CodComanda1 &gt; 0 THEN
    sString :=
    'insert into ' || tmpName || '( Obiect, UM, Cant, Pozitie, Nivel, ordine, Obs' || gUserFields || ')
    select coalesce(obje.denumire,obj.denumire), coalesce(UME.den_um,UM.den_um), nod.Cant * coalesce(echiv.paritate,1), nod.Pozitie, nod.Nivel, substr(x.ind,5, length(x.ind)-3),
           mat.obs' || gUserAlias || '
    from   comanda1 c1
          inner join proiectnod nod        on nod.codproiect      = c1.codproiect
          inner join proiect prj           on prj.codproiect      = nod.codproiect
          inner join nartobj objprj        on prj.codobiectprod   = objprj.codobiect
          left  join prodmat mat           on mat.codmat          = nod.codprodmat
          left  join nodechiv echiv        on echiv.codproiectnod = nod.codproiectnod and echiv.codcomanda1 = ' || coalesce(p_CodComanda1,0) || '
          left  join nartobj obj           on nod.codobiect       = obj.codobiect
          left  join nartobjsubunit objsub on nod.codobiect       = objsub.codobiect
                                              and (objsub.codgest is null or objsub.codgest = 0)
                                              and objsub.subunitate = getsubunitate()
          left  join nartobj obje          on echiv.codobiect     = obje.codobiect
          left  join nart art              on obj.codarticol      = art.codarticol
          left  join nclasea cls           on cls.codclasea       = art.clasa
          left  join nart arte             on obje.codarticol     = arte.codarticol
          left  join num um                on um.codum            = art.um
          left  join num ume               on ume.codum           = arte.um
          LEFT  JOIN (
                      WITH RECURSIVE tt_w AS
                       ( SELECT CodProiectNod,pozitie,NODORIGINAL,  ''.'' ||COALESCE(LPAD(POZITIE::varchar, 2, ''0''),'''') IND
                          FROM PROIECTNOD
                          WHERE NODORIGINAL=0
                          UNION ALL
                          SELECT n.CodProiectNod,
                                     n.pozitie,
                                     n.NODORIGINAL,
                                     w.IND || ''.'' ||COALESCE(LPAD(n.POZITIE::varchar, 2, ''0''),'''')
                          FROM PROIECTNOD n,tt_w w
                          WHERE w.CodProiectNod = n.NODORIGINAL
                       )
                      SELECT CodProiectNod, IND FROM tt_w order by CodProiectNod
                     ) X                   on x.CodProiectNod = nod.CodProiectNod' || gSuplJoins || '
    where coalesce(nod.nodoriginal, 0) &gt; 0  and c1.codcomanda1 = ' || coalesce(p_CodComanda1,0);
  ELSE
    sString :=
    'insert into ' || tmpName || '( Obiect, UM, Cant, Pozitie, Nivel, ordine, obs' || gUserFields || ')
    select obj.denumire, UM.den_um, nod.Cant, nod.Pozitie, nod.Nivel, substr(x.ind,5, length(x.ind)-3), mat.obs' || gUserAlias || '
    from proiectnod nod
      inner join proiect        prj    on prj.codproiect    = nod.codproiect
      inner join nartobj        objprj on prj.codobiectprod = objprj.codobiect
      left  join prodmat        mat    on mat.codmat        = nod.codprodmat
      left  join nartobj        obj    on nod.codobiect     = obj.codobiect
      left  join nartobjsubunit objsub on nod.codobiect     = objsub.codobiect
                                          and (objsub.codgest is null or objsub.codgest = 0)
                                          and objsub.subunitate = getsubunitate()
      left  join nart           art    on obj.codarticol    = art.codarticol
      left  join nclasea        cls    on cls.codclasea     = art.clasa
      left  join num            um     on um.codum          = art.um
      LEFT  JOIN (
                  WITH RECURSIVE tt_w AS
                   ( SELECT CodProiectNod,pozitie,NODORIGINAL,  ''.'' ||COALESCE(LPAD(POZITIE::varchar, 2, ''0''),'''') IND
                      FROM PROIECTNOD
                      WHERE NODORIGINAL=0
                      UNION ALL
                      SELECT n.CodProiectNod,
                                 n.pozitie,
                                 n.NODORIGINAL,
                                 w.IND || ''.'' ||COALESCE(LPAD(n.POZITIE::varchar, 2, ''0''),'''')
                      FROM PROIECTNOD n,tt_w w
                      WHERE w.CodProiectNod = n.NODORIGINAL
                   )
                  SELECT CodProiectNod, IND FROM tt_w order by CodProiectNod
                 ) X on x.CodProiectNod = nod.CodProiectNod' || gSuplJoins || '
    where coalesce(nod.nodoriginal, 0) &gt; 0  and nod.codproiect = ' || coalesce(current_setting('PKG_LIST_BASE_PROIECT.p_CodProiect', true),'');
  END IF;
  PERFORM LIST_EXECUTE_IMMEDIATE(sstring, aListID, aListVer);

  IF  p_CodComanda1 &gt; 0 THEN
    BEGIN
      SELECT codcomanda INTO aCodComanda FROM comanda1 WHERE codcomanda1 = p_CodComanda1;
    EXCEPTION WHEN others THEN
      aCodComanda := 0;
    END;
    IF  aCodComanda &gt; 0 THEN
      PERFORM pkg_list_base_comdoc_SETPARAMS(aCodComanda, aListID, 0);
      PERFORM pkg_list_base_comdoc_ADD_LIST_PARAMS();
    END IF;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rac_detinfog_setparams</obj_name>
  <obj_hashval>02ca983ba3fbf70672eff162cd2e76c2</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rac_detinfog_setparams(pcoddoc numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  perform set_config('PKG_LIST_BASE_RAC_DETINFOG.vCodDoc',(pCodDoc)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rac_masinioc_processlist</obj_name>
  <obj_hashval>e9bf77c683db4a3fefe3fbb84cdde86d</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rac_masinioc_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert varchar := '';
  sSelect varchar := '';
  gDataS  varchar    := current_setting('PKG_LIST_ALEGPERIOADA.gDataS', true);
  gDataF  varchar    := current_setting('PKG_LIST_ALEGPERIOADA.gDataF', true);
  gSuplCols varchar := 'NGEST G, COMANDA C, RAC_REZ R, NPARCAUT P, CONTRACT CC, NPART NP';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 06.06.2025 - sinc. Oracle
  --Florin 10.07.2023 - fixat 58826
  --Florin 15.02.2023 - fixat 57204
  --Florin 10.02.2023 - fixat 57094
  --Adina 15.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_rac_masinioc.gSuplCols', gSuplCols, false);

  sInsert :=
  'INSERT INTO ' || tmpName || '(
     NAV_CodDoc, NAV_TipDoc, REZERVARE, AN, LUNA, ZI, Judet,
     CUSTOMER,
     SHUTTLE,
     COURTESY,
     UZINTERN,
     REPARATII,
     ABONAMENT,
     TRANSFER,
     DATA, GESTIUNE, SUBUNITATE, MARCA, MODEL, CLASA, MaxRezSimultan,
     Partener,
     Contract '||gUserFields||')';

  sSelect := '
  WITH recursive q(CodGestSursa, Codcomanda, TipRezervare, NIVEL, DATA) as (
    SELECT R.CodGestSursa, R.Codcomanda, R.TipRezervare, 1 NIVEL, Date_Trunc(''day'',R.DATASTART)::date as DATA
    FROM   RAC_REZ R
          INNER JOIN comanda  c on c.codcomanda  = r.codcomanda
          INNER JOIN NParcAut P on P.CODNPARCAUT = Coalesce(C.MijlTransp, 0)
          INNER JOIN NEchiv   E on E.Codobiect   = P.CodArt
    WHERE c.tipdoc = 94 and Coalesce(C.Mijltransp,0) &gt; 0 and Coalesce(E.Generic,0) = 0
          AND R.DATASTART &lt;= to_date(''' || gDataF || ''', ''dd.mm.yyyy'')
          AND R.DATASTOP  &gt;= to_date(''' || gDataS || ''', ''dd.mm.yyyy'')
    UNION ALL
    SELECT R.CodGestSursa, R.Codcomanda, R.TipRezervare, Q.NIVEL + 1, Date_Trunc(''day'',add_days(R.DATASTART::date, Q.NIVEL::integer))::date
    FROM RAC_REZ R, q
    WHERE R.Codcomanda = q.Codcomanda AND Q.DATA &lt; add_days(Date_Trunc(''day'',R.DATASTART)::date, Q.NIVEL::integer)
          AND add_days(Date_Trunc(''day'',R.DATASTART)::date, Q.NIVEL::integer) &lt;= Case when coalesce(R.Predat,0) = 0 then Date_Trunc(''day'',R.DATASTOP) else Least(Date_Trunc(''day'',R.DATASTOP), Date_Trunc(''day'',R.DATAPRED)) end
  )
  SELECT
    C.CodComanda, C.TipDoc, C.Seriadoc||C.Nrdoc::varchar Rezervare,
    Extract(Year  FROM z.Ziua) An,
    Extract(Month FROM z.Ziua) Luna,
    Extract(Day   FROM z.Ziua) Zi,
    J.SimbAuto Judet,
    (case when q.TipRezervare= 0 then  1 else  0 end) Customer,
    (case when q.TipRezervare= 1 then  1 else  0 end) Shuttle,
    (case when q.TipRezervare= 3 then  1 else  0 end) Courtesy,
    (case when q.TipRezervare= 4 then  1 else  0 end) UzIntern,
    (case when q.TipRezervare= 5 then  1 else  0 end) Reparatii,
    (case when q.TipRezervare= 6 then  1 else  0 end) Abonament,
    (case when q.TipRezervare= 7 then  1 else  0 end) Transfer,
    z.Ziua AS DATA, G.DEN_GEST Gestiune, S.Den_subunit Subunitate, Coalesce(Ma.Marca, ''?'') Marca, Coalesce(Mo.Model, ''?'') Model, Gr.DENUMIRE Clasa, Cc.Maxreplsimultane,
    CASE WHEN q.TipRezervare IN (0,1,3,6) THEN NP.DEN_PART else ''-'' END,
    Cc.Seriadoc||CC.Nrdoc::varchar||''/''||to_char(Cc.DataDoc,''dd.mm.yyyy'') Contract '||gUserAlias||'
  FROM   ngest g
        CROSS JOIN tmp_zile z
        inner JOIN q               ON q.CodGestSursa = g.CodGest AND q.Data = z.Ziua
        inner JOIN comanda  c      on c.codcomanda   = q.codcomanda
        LEFT  JOIN Rac_Rez  r      on r.codcomanda   = c.codcomanda
        LEFT  JOIN NParcAut P      on P.CODNPARCAUT  = Coalesce(C.MijlTransp, 0)
        LEFT  JOIN NEchiv   E      on E.Codobiect    = P.CodArt
        LEFT  JOIN GrEchiv Gr      on Gr.CODGRECHIV  = E.CodGrupa
        LEFT  JOIN NAGENDA A       on Coalesce(A.CodGest,0) = G.CODGEST
        LEFT  JOIN NLocalit L      on L.CodLocalit   = A.Codlocalit
        LEFT  JOIN NJudet J        on J.CodJudet     = L.CodJudet
        LEFT  JOIN Nsubunit S      on S.codSubunit   = G.CodSubunit
        LEFT  JOIN Contract Cc     on Cc.CodContract = Coalesce(C.CodContract,0)
        LEFT  JOIN NPart NP        on Np.CodPart     = Coalesce(C.Partener,0)
        LEFT  JOIN Nmodeleauto Mo  on Mo.CODMODELEAUTO = Coalesce(p.Model,0)
        LEFT  JOIN Nmarciauto  Ma  on Ma.CODMarciAuto  = Coalesce(p.Marca,0)'||gSuplJoins;
  PERFORM PKG_RAC_REZ_SET_RAC_DATASTART(gDataS);
  PERFORM UMPLE_TMP_ZILE(to_date(gDataS, 'dd.mm.yyyy'), to_date(gDataF, 'dd.mm.yyyy'));
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rapconsprod_setparams</obj_name>
  <obj_hashval>9478fed60a9afb99e995ef7dc98ffcc5</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rapconsprod_setparams(aanluna numeric DEFAULT 0, aallart numeric DEFAULT 0, acodcomanda numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15 septembrie 2020
  perform set_config('PKG_LIST_BASE_RAPCONSPROD.vAnLuna'    ,(aAnLuna)::varchar     ,false);
  perform set_config('PKG_LIST_BASE_RAPCONSPROD.vAllArt'    ,(aAllArt)::varchar     ,false);
  perform set_config('PKG_LIST_BASE_RAPCONSPROD.vCodComanda',(aCodComanda)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rapconsprod_umplepredarisiconsumuri</obj_name>
  <obj_hashval>5952d98611fba709e11fb4caab61b8f1</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rapconsprod_umplepredarisiconsumuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
  N     RECORD;
  vCodComanda      NUMERIC := current_setting('PKG_LIST_BASE_RAPCONSPROD.vCodComanda', true)::numeric;
  vAllArt          NUMERIC := current_setting('PKG_LIST_BASE_RAPCONSPROD.vAllArt'    , true)::numeric;
  vAnLuna          NUMERIC := current_setting('PKG_LIST_BASE_RAPCONSPROD.vAnLuna'    , true)::numeric;
BEGIN
  --Adina 15 septembrie 2020
  DELETE FROM MANEVRA_CONSUM;
  DELETE FROM OBJ_CMDINT1;

  IF  vCodComanda &gt; 0 THEN
    INSERT INTO OBJ_CMDINT1(CODCMDINT1, CODOBIECT)
    SELECT  DISTINCT i1.codcmdint1, i1.codobiect
    FROM intrari1 i1
    WHERE i1.codcmdint1 IN (SELECT codcomanda1 FROM comanda1 WHERE codcomanda = vCodComanda);
  ELSE
    INSERT INTO OBJ_CMDINT1(CODCMDINT1, CODOBIECT)
    SELECT  DISTINCT i1.codcmdint1, i1.codobiect
    FROM   intrari1 i1
          INNER JOIN intrari i ON  i1.codintr = i.codintr
    WHERE ( EXISTS (SELECT valoare FROM tmp_manevra_liste WHERE valoare = i1.codobiect::varchar and  filtru = 'CODOBIECT')
            or  vAllArt = 1
          )
          and  i.tipdoc = 7 and  COALESCE(i.anulat, 0) = 0 and  i.operat = 1 and  i.an * 12 + i.luna = vAnLuna
          and (i.subunitatea = getSUBUNITATE() or  getSUBUNITATE() = 1) ;
  END IF;

  FOR v_rec IN (
    WITH man_cons AS (
      SELECT   i1.codobiect PRODUS, ies1.codobiect MATERIAL, l1.cant, COALESCE(ns1.pretmat, 0) * l1.cant VALOARE,
              ns1.tipdoc, COALESCE(ii1.codcmdint1, 0) CODCMDINT1, ies1.codies1, l1.codlivr1, ns.codnirstoc CODNIRSTOCPRED,
              COALESCE(it1.cant, 0) CANTPRED, it1.codintr1,
              CASE WHEN  ns1.tipdoc = 7 and  prod.tip = 0 THEN 1 ELSE 0 END  TIP
      FROM   OBJ_CMDINT1             i1
            INNER JOIN iesiri1      ies1 ON  ies1.codcmdint1    = i1.codcmdint1
            INNER JOIN iesiri       ies  ON  ies1.codies        = ies.codies
            INNER JOIN livr1        l1   ON  l1.codies1         = ies1.codies1
            INNER JOIN livr         l    ON  l.codlivr          = l1.codlivr    and  ies.codies = l.codies
            INNER JOIN nirstoc1     ns1  ON  l1.codnirstoc      = ns1.codnirstoc
            INNER JOIN nirstoc      ns   ON  ns.codnirstoc      = ns1.codnirstocorig
            LEFT  JOIN intrari1     ii1  ON  ii1.codintr1       = ns.codintr1
            LEFT  JOIN intrari1     it1  ON  it1.codcmdint1     = ii1.codcmdint1 and  it1.codobiect = ies1.codobiect
            LEFT  JOIN intrprodlink lk   ON  lk.codintr1        = it1.codintr1
            LEFT  JOIN cmdprodmat   prod ON  prod.codcmdprodmat = lk.codliniecomanda
      WHERE ies.operat = 1 and  COALESCE(ies.anulat, 0) = 0 and  ns1.tipdoc = 7 and  prod.tip = 0
    ),
    man_cons_mat AS (
      SELECT   i1.codobiect PRODUS, ies1.codobiect MATERIAL, l1.cant, COALESCE(ns1.pretmat, 0) * l1.cant VALOARE,
              ns1.tipdoc, 0 CODCMDINT1, ies1.codies1, l1.codlivr1, ns.codnirstoc CODNIRSTOCPRED,
              COALESCE(it1.cant, 0) CANTPRED, it1.codintr1,
              CASE WHEN  ns1.tipdoc = 7 and  prod.tip = 0 THEN 1 ELSE 0 END  TIP
      FROM   OBJ_CMDINT1             i1
            INNER JOIN iesiri1      ies1 ON  ies1.codcmdint1    = i1.codcmdint1
            INNER JOIN iesiri       ies  ON  ies1.codies        = ies.codies
            INNER JOIN livr1        l1   ON  l1.codies1         = ies1.codies1
            INNER JOIN livr         l    ON  l.codlivr          = l1.codlivr    and  ies.codies = l.codies
            INNER JOIN nirstoc1     ns1  ON  l1.codnirstoc      = ns1.codnirstoc
            INNER JOIN nirstoc      ns   ON  ns.codnirstoc      = ns1.codnirstocorig
            LEFT  JOIN intrari1     ii1  ON  ii1.codintr1       = ns.codintr1
            LEFT  JOIN intrari1     it1  ON  it1.codcmdint1     = ii1.codcmdint1 and  it1.codobiect = ies1.codobiect
            LEFT  JOIN intrprodlink lk   ON  lk.codintr1        = it1.codintr1
            LEFT  JOIN cmdprodmat   prod ON  prod.codcmdprodmat = lk.codliniecomanda
      WHERE ies.operat = 1 and  COALESCE(ies.anulat, 0) = 0 and  NOT (   ns1.tipdoc = 7 and  COALESCE(prod.tip, -1) = 0)
    )
    SELECT produs, material, sum(cant) CANT, sum(valoare) VALOARE, codcmdint1, totcons, totval, totpred, tip, codlivr1
    FROM (SELECT  DISTINCT man_cons_mat.produs, man_cons_mat.material, man_cons_mat.cant, man_cons_mat.valoare, man_cons_mat.codcmdint1, tot_cons.cant TOTCONS, tot_cons.valoare TOTVAL, 0 TOTPRED, man_cons_mat.tip, man_cons_mat.codlivr1
          FROM   man_cons_mat
                INNER JOIN nartobj obj ON  obj.codobiect = man_cons_mat.material
                INNER JOIN (SELECT sum(cant) CANT, material, produs, codcmdint1, tip, sum(valoare) VALOARE
                            FROM (SELECT  DISTINCT cant, codlivr1, material, produs, codcmdint1, tip, valoare FROM man_cons_mat) A_PG
                            GROUP BY material, produs, codcmdint1, tip
                           ) tot_cons ON  tot_cons.material   = man_cons_mat.material   and
                                           tot_cons.produs     = man_cons_mat.produs     and
                                           tot_cons.codcmdint1 = man_cons_mat.codcmdint1 and
                                           tot_cons.tip        = man_cons_mat.tip
          union ALL
          SELECT  DISTINCT man_cons.produs, man_cons.material, man_cons.cant, man_cons.valoare,
                  CASE WHEN  man_cons.tip = 1 THEN man_cons.codcmdint1 ELSE 0 END  CODCMDINT1,
                  tot_cons.cant TOTCONS, tot_cons.valoare TOTVAL, COALESCE(tot_pred.total, 0) TOTPRED, man_cons.tip, 0 CODLIVR1
          FROM   man_cons
                INNER JOIN nartobj obj ON  obj.codobiect = man_cons.material
                INNER JOIN (SELECT sum(cant) CANT, material, produs, codcmdint1, tip, sum(valoare) VALOARE
                            FROM (SELECT  DISTINCT cant, codlivr1, material, produs, codcmdint1, tip, valoare FROM man_cons) B_PG
                            GROUP BY material, produs, codcmdint1, tip
                           ) tot_cons ON  tot_cons.material   = man_cons.material   and
                                           tot_cons.produs     = man_cons.produs     and
                                           tot_cons.codcmdint1 = man_cons.codcmdint1 and
                                           tot_cons.tip        = man_cons.tip
                LEFT JOIN (SELECT sum(cantpred) TOTAL, material, produs, codcmdint1, tip
                           FROM (SELECT  DISTINCT produs, material, codcmdint1, cantpred, codintr1, tip FROM man_cons WHERE tipdoc = 7 AND  TIP = 1) C_PG
                           GROUP BY produs, material, codcmdint1, tip
                          ) tot_pred ON  tot_pred.produs     = man_cons.produs     and
                                         tot_pred.material   = man_cons.material   and
                                         tot_pred.codcmdint1 = man_cons.codcmdint1 and
                                         tot_pred.tip        = man_cons.tip
         ) D_PG
    GROUP BY produs, material, codcmdint1, totcons, totpred, tip, totval, codlivr1
  )
  LOOP
    IF  v_rec.codcmdint1 &gt; 0 and  v_rec.tip = 1 THEN
      PERFORM pkg_list_base_rapconsprod_BagaMaterialeSemi(v_rec.produs, v_rec.material, v_rec.totcons / v_rec.totpred, v_rec.codcmdint1);
    ELSE
      FOR N IN (SELECT   v_rec.produs PRODUS, v_rec.produs NODPARINTE, V_REC.MATERIAL MATERIAL,
                        V_REC.cant CANT, V_REC.valoare VALOARE, v_rec.totcons TOTCONS, v_rec.totval TOTVAL
               )
      LOOP
        UPDATE  MANEVRA_CONSUM C
           SET CANT = COALESCE(C.CANT, 0) + N.CANT, VALOARE = COALESCE(C.VALOARE, 0) + N.VALOARE
        WHERE C.CODOBIECT = N.MATERIAL and  C.NODPARINTE = N.NODPARINTE and  C.PRODUS = N.PRODUS;

        IF NOT FOUND THEN
          INSERT INTO MANEVRA_CONSUM AS C (CODOBIECT, VALOARE, CANT, NODPARINTE, PRODUS) VALUES (N.MATERIAL, N.VALOARE, N.CANT, N.NODPARINTE, N.PRODUS) ;
        END IF;
      END LOOP;
    END IF;
  END LOOP;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rapconsumprod_setparams</obj_name>
  <obj_hashval>d5e39cb3b3dd58d5953d70c450615709</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rapconsumprod_setparams(atouch numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 15.10.2020
  perform set_config('PKG_LIST_BASE_RAPCONSUMPROD.vTouch',( Coalesce(aTouch, 0) = 1)::varchar,false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_rapgesttvaval_processlist</obj_name>
  <obj_hashval>636fa55532e2cd1b0540ae10716ac688</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_rapgesttvaval_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert   varchar :='';
  sSelect   varchar :='';
  sDataIni  varchar := coalesce(to_char((SELECT PKG_LIST_SELECTGEST2_ZiuaIni.WME_RESULT FROM PKG_LIST_SELECTGEST2_ZiuaIni(NULL,NULL)), 'fm00'),'') || '.' || coalesce(to_char(getlunalucru(), 'fm00'),'') || '.' || coalesce(to_char(getanlucru(), 'fm0000'),'');
  sDataFin  varchar := coalesce(to_char((SELECT PKG_LIST_SELECTGEST2_ZiuaFin.WME_RESULT FROM PKG_LIST_SELECTGEST2_ZiuaFin(NULL,NULL)), 'fm00'),'') || '.' || coalesce(to_char(getlunalucru(), 'fm00'),'') || '.' || coalesce(to_char(getanlucru(), 'fm0000'),'');
  sCondData varchar :='';
BEGIN
  --Adina 06.04.2021 - alstart,alstop
  --Adina 01.12.2020 tichet 41363
  --STEF 20.11.2020
  --Adina iulie 2020
 IF  (SELECT PKG_LIST_SELECTGEST2_ZiuaIni.WME_RESULT FROM PKG_LIST_SELECTGEST2_ZiuaIni(NULL,NULL)) = (SELECT PKG_LIST_SELECTGEST2_ZiuaFin.WME_RESULT FROM PKG_LIST_SELECTGEST2_ZiuaFin(NULL,NULL))
 THEN sCondData := ' = to_date(''' || coalesce(sDataIni,'') || ''',''DD.MM.YYYY'') ';
 ELSE sCondData := ' BETWEEN to_date(''' || coalesce(sDataIni,'') || ''',''DD.MM.YYYY'') AND to_date(''' || coalesce(sDataFin,'') || ''',''DD.MM.YYYY'') ';
 END IF;

 sInsert :=
    'INSERT INTO '||tmpName||' (
      NAV_CodDoc, NAV_TipDoc, PrefixDoc, NrDoc, DataDoc, Document, TipDoc,
      AdDebit,  ValDFTVA, ValDCTVA, TVAD,
      AdCredit, ValCFTVA, ValCCTVA, TVAC,
      SoldFinFTVA, SoldFinCTVA, SursaDest, DenIOART, SoldIn, AchizIn, SoldAd,
      Coef,
      DenGest, DenCONT, SimbCONT, RecLivr, Zi, ZiDoc, PjTVA )';

 sSelect := '
  WITH
    IOA1 AS (
      SELECT IO.CODIOART, IO.DEN_IOART, NCo.DEN_CONT, NCo.SIMBOL SIMB_CONT
      FROM IOART1 IO1  --, IOART IO, NCONT NCo
       JOIN IOART      IO  on IO.CODIOART = IO1.CODIOART
       LEFT JOIN NCONT NCo on NCo.CODCONT = IO1.CONT
      WHERE
        IO1.MG = 5
        AND  '||getAnLunaLucru()::varchar||' BETWEEN IO1.ALStart and IO1.ALStop
    ),
    SVM AS (
      SELECT GEST, CODIOART, Coalesce(TVA,0) TVA, SOLD, SOLD/(1+Coalesce(TVA,0))-(SOLD-Coalesce(ADAOS,0)) ADAOS, SOLDINTR, ADAOSINTR
      FROM STOCVALLUNA SVL '||pkg_list_base_rapgesttvaval_jointmp('SVL.GEST')||'
      WHERE (AN * 12 + LUNA + 1)= '||getAnLunaLucru()::varchar||'
      UNION ALL -- NIR-URI DIN INTRARI
      SELECT N.GEST, NS.CODIOART, NS.TVA, NS.CANTNIR * NS.PRET SOLD, NS.CANTNIR * NS.ADAOS ADAOS, NS.CANTNIR * NS.PRET SOLDINTR, NS.CANTNIR * NS.ADAOS ADAOSINTR
      FROM NIRSTOC NS
        INNER JOIN NIR     N    ON N.CODNIR      = NS.CODNIR '||pkg_list_base_rapgesttvaval_jointmp('N.GEST')||'
        INNER JOIN INTRARI I    ON I.CODINTR     = N.CODINTR
        INNER JOIN IOA1         ON IOA1.CODIOART = NS.CODIOART
      WHERE I.TIPDOC IN (1, 2, 3, 4, 5, 6, 7) AND I.ANULAT = 0 AND I.OPERAT = 1
        AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
        AND N.DATANIR &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'')
      UNION ALL -- NIR-URI DIN MISCARI INTERNE
      SELECT N.GEST, NS.CODIOART, NS.TVA, NS.CANTNIR * NS.PRET SOLD, NS.CANTNIR * NS.ADAOS ADAOS, NS.CANTNIR * NS.PRET SOLDINTR, NS.CANTNIR * NS.ADAOS ADAOSINTR
      FROM NIRSTOC NS
        INNER JOIN NIR    N ON N.CODNIR      = NS.CODNIR '||pkg_list_base_rapgesttvaval_jointmp('N.GEST')||'
        INNER JOIN TRANSF T ON T.CODTRANSF   = N.CODTRANSF
        INNER JOIN IOA1     ON IOA1.CODIOART = NS.CODIOART
      WHERE T.TIPDOC IN (12, 13) AND  T.ANULAT = 0 AND T.OPERAT = 1
        AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
        AND N.DATANIR &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'')
      UNION ALL -- LIVRARI INTRARI
      SELECT LV.GEST, LV.CODIOART, Coalesce(LV.TVANEEX, 0) TVA, - LV.PRETINREG * L1.CANT SOLD, - (LV.PRETINREG - LV.PRETACHIZ) * L1.CANT ADAOS, 0 SOLDINTR, 0 ADAOSINTR
      FROM LIVRVAL LV '||pkg_list_base_rapgesttvaval_jointmp('LV.GEST')||'
        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
      WHERE I.TIPDOC IN (1, 2, 3, 4, 5, 6, 7) AND I.OPERAT = 1 AND I.ANULAT = 0
        AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
        AND L.DATALIVR &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'')
      UNION ALL -- LIVRARI IESIRI
      SELECT LV.GEST, LV.CODIOART, Coalesce(LV.TVANEEX, 0) TVA, - LV.PRETINREG * L1.CANT SOLD, - (LV.PRETINREG - LV.PRETACHIZ) * L1.CANT ADAOS, 0 SOLDINTR, 0 ADAOSINTR
      FROM LIVRVAL LV '||pkg_list_base_rapgesttvaval_jointmp('LV.GEST')||'
        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
      WHERE I.TIPDOC IN (14, 16, 19, 20, 21, 22, 23, 24 ) AND I.OPERAT = 1 AND I.ANULAT = 0
        AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
        AND L.DATALIVR &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'')
      UNION ALL -- LIVRARI MISCARI INTERNE
      SELECT LV.GEST, LV.CODIOART, Coalesce(LV.TVANEEX, 0) TVA, - LV.PRETINREG * L1.CANT SOLD, - (LV.PRETINREG - LV.PRETACHIZ) * L1.CANT ADAOS, 0 SOLDINTR, 0 ADAOSINTR
      FROM LIVRVAL LV '||pkg_list_base_rapgesttvaval_jointmp('LV.GEST')||'
        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
      WHERE T.TIPDOC IN (12, 13) AND T.OPERAT = 1 AND T.ANULAT = 0
        AND L.DATALIVR &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'')
        AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
      UNION ALL -- LIVRARI MARIRI DE STOC
      SELECT LV.GEST, LV.CODIOART, Coalesce(LV.TVANEEX, 0) TVA, LV.PRETINREG * L1.CANT SOLD, (LV.PRETINREG - LV.PRETACHIZ) * L1.CANT ADAOS, LV.PRETINREG * L1.CANT SOLDINTR, (LV.PRETINREG - LV.PRETACHIZ) * L1.CANT ADAOSINTR
      FROM  LIVRVAL LV '||pkg_list_base_rapgesttvaval_jointmp('LV.GEST')||'
        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
      WHERE I.TIPDOC = 15 AND I.OPERAT = 1 AND I.ANULAT = 0
        AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
        AND L.DATALIVR &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'')
    )
  SELECT
    NULL CodDoc, NULL TipDoc, '' '' PrefixDoc, NULL NrDoc, to_date('''||sDataIni||''',''DD.MM.YYYY'') DataDoc, ''Sold initial'' Doc, '' '' TipDoc,
    0 AdDebit, 0 ValDFTva, 0 ValDCTva, 0 TVAD, 0 AdCredit, 0 ValCFTva, 0 ValCCTva, 0 TvaC,
    SUM(SVM.Sold / (1 + SVM.Tva)) SoldFinFTva, SUM(SVM.Sold) SoldFinCTva,
    NULL SursaDest, IOA1.DEN_IOART,
    SUM(SVM.SOLDINTR) SoldIn, SUM(SVM.SOLDINTR - SVM.ADAOSINTR) AchizIn, SUM(SVM.ADAOS) SoldAd,
    (case when SUM(SVM.SOLDINTR - SVM.ADAOSINTR)=0 then 0 else SUM(SVM.SOLDINTR) / SUM(SVM.SOLDINTR - SVM.ADAOSINTR) end) Coef,
    NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
    NULL RecLivr, 0 Zi, 0 ZiDoc, SVM.TVA * 100 PjTVA  --aici col.ZI,ZiDoc erau pus char.
  FROM SVM
    INNER JOIN IOA1     ON IOA1.CODIOART = SVM.CODIOART
    INNER JOIN NGEST NG ON NG.CODGEST    = SVM.GEST '||
    coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG','CODSUBUNIT',NULL,NULL))::varchar,'')||'
  GROUP BY NG.DEN_GEST, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, SVM.TVA
  UNION ALL -- INTRARI
  SELECT
    I.CODINTR CodDoc, I.TIPDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC,
  --i.prefixdoc ||i.seriadoc||i.nrdoc ||''/''||to_date(i.datadoc,''dd.mm.yyyy'') Doc,
    coalesce(i.prefixdoc,'''') ||coalesce(i.seriadoc,'''')||coalesce(i.nrdoc::varchar,'''') ||''/''||coalesce(to_char(i.datadoc,''dd.mm.yyyy''),'''') Doc,
    coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',I.TIPDOC)),''''),
    SUM(NS.CANTNIR * (NS.ADAOS - NS.PRET * NS.TVA / (1+NS.TVA) )) AdDebit, SUm(NS.CANTNIR * NS.PRET / (1+NS.TVA)) ValDFTva, SUM(NS.CANTNIR * NS.PRET) ValDCTva,
    SUM(NS.CANTNIR * NS.PRET * NS.TVA / (1+NS.TVA)) TVAD, 0 AdCredit, 0 ValCFTva, 0 ValCCTva, 0 TvaC,
    SUM(NS.CANTNIR * NS.PRET / (1+NS.TVA)) SoldFinFTva, SUM(NS.CANTNIR * NS.PRET) SoldFinCTva,
    (Case  When I.TIPDOC=6 then S.DEN_SUBUNIT When I.TIPDOC=7 then G.DEN_GEST else NP.DEN_PART end) SursaDest, IOA1.DEN_IOART,
    SUM(NS.CANTNIR * NS.PRET) SoldIn, SUM(NS.CANTNIR * (NS.PRET - NS.ADAOS)) AchizIn, 0 SoldAd,
    (Case  When SUM(NS.CANTNIR * (NS.PRET - NS.ADAOS))=0 then 0 else SUM(NS.CANTNIR * NS.PRET) / SUM(NS.CANTNIR * (NS.PRET - NS.ADAOS)) end) Coef,
    NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
    N.NRNIR||''/''||to_char(N.DATANIR,''dd.mm.yyyy'') RecLivr, TO_CHAR(N.DATANIR,''DD'')::numeric Zi, TO_CHAR(I.DATADOC,''DD'')::numeric ZiDoc, NS.TVA * 100 PjTva  --am pus col.Zi,ZiDoc de tip numeric
  FROM NIRSTOC NS
    INNER JOIN IOA1        ON IOA1.CODIOART = NS.CODIOART
    INNER JOIN NIR      N  ON N.CODNIR      = NS.CODNIR'||pkg_list_base_rapgesttvaval_jointmp('N.GEST')||'
    INNER JOIN NGEST    NG ON NG.CODGEST    = N.GEST '||
    coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG','CODSUBUNIT',NULL,NULL))::varchar,'')||'
    INNER JOIN INTRARI  I  ON I.CODINTR     = N.CODINTR
    LEFT  JOIN NPART    NP ON NP.CODPART    = I.PARTENER
    LEFT  JOIN NGEST    G  ON G.CODGEST     = I.CODGESTPROD
    LEFT  JOIN NSUBUNIT S  ON S.CODSUBUNIT  = I.CODSUBUNIT
  WHERE I.TIPDOC IN (1, 2, 3, 4, 5, 6, 7) AND I.ANULAT = 0 AND I.OPERAT = 1
    AND N.DATANIR'||sCondData||'
    AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
  GROUP BY I.CODINTR, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC, N.NRNIR, N.DATANIR, NS.TVA, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST, NP.DEN_PART, S.DEN_SUBUNIT, G.DEN_GEST
  UNION ALL -- INTRARI DIN TRANSFERURI
  SELECT
    T.CODTRANSF CodDoc, T.TIPDOC, T.PREFIXDOC, T.NRDOC, T.DATADOC,
  --t.prefixdoc ||t.seriadoc||t.nrdoc||''/''||to_date(t.datadoc,''dd.mm.yyyy'') Doc,
    coalesce(t.prefixdoc,'''') ||coalesce(t.seriadoc,'''')||coalesce(t.nrdoc::varchar,'''')||''/''||coalesce(to_char(t.datadoc,''dd.mm.yyyy''),'''') Doc,
    coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',T.TIPDOC)),''''),
    SUM(NS.CANTNIR * (NS.ADAOS - NS.PRET * NS.TVA / (1+NS.TVA) )) AdDebit, SUm(NS.CANTNIR * NS.PRET / (1+NS.TVA)) ValDFTva, SUM(NS.CANTNIR * NS.PRET) ValDCTva,
    SUM(NS.CANTNIR * NS.PRET * NS.TVA / (1+NS.TVA)) TVAD, 0 AdCredit, 0 ValCFTva, 0 ValCCTva, 0 TvaC,
    SUM(NS.CANTNIR * NS.PRET / (1+NS.TVA)) SoldFinFTva, SUM(NS.CANTNIR * NS.PRET) SoldFinCTva,
    NG_S.DEN_GEST SursaDest, IOA1.DEN_IOART,
    SUM(NS.CANTNIR * NS.PRET) SoldIn, SUM(NS.CANTNIR * (NS.PRET - NS.ADAOS)) AchizIn, 0 SoldAd,
    (Case  When SUM(NS.CANTNIR * (NS.PRET - NS.ADAOS))=0 then 0 else SUM(NS.CANTNIR * NS.PRET) / SUM(NS.CANTNIR * (NS.PRET - NS.ADAOS)) end) Coef,
    NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
    N.NRNIR||''/''||to_char(N.DATANIR,''dd.mm.yyyy'') RecLivr, TO_CHAR(N.DATANIR,''DD'')::numeric Zi, TO_CHAR(T.DATADOC,''DD'')::numeric ZiDoc, NS.TVA * 100 PjTva  --am pus col.Zi,ZiDoc de tip numeric
  FROM TRANSF T
    INNER JOIN NIR     N    ON N.CODTRANSF     = T.CODTRANSF'||pkg_list_base_rapgesttvaval_jointmp('N.GEST')||'
    INNER JOIN NIRSTOC NS   ON NS.CODNIR       = N.CODNIR
    INNER JOIN IOA1         ON IOA1.CODIOART   = NS.CODIOART
    INNER JOIN NGEST   NG   ON NG.CODGEST      = N.GEST '|| coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(null,'NG','CODSUBUNIT',null,null))::varchar,'')||'
    LEFT  JOIN NIRSTOC NS_S ON NS_S.CODNIRSTOC = NS.CODNIRSTOCPARINTE AND (NS.CODNIRSTOCPARINTE IS NOT NULL)
    LEFT  JOIN NIR     N_S  ON N_S.CODNIR      = NS_S.CODNIR
    LEFT  JOIN LIVRVAL LV_S ON LV_S.CODLIVR1   = NS.CODLIVR1
    LEFT  JOIN NGEST   NG_S ON NG_S.CODGEST    = Coalesce(N_S.GEST,LV_S.GEST)
  WHERE T.TIPDOC = 12 AND T.ANULAT = 0 AND T.OPERAT = 1
    AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
    AND N.DATANIR'||sCondData||'
  GROUP BY T.CODTRANSF, T.TIPDOC, T.PREFIXDOC, T.SERIADOC, T.NRDOC, T.DATADOC, N.NRNIR, N.DATANIR, NS.TVA, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST, NG_S.DEN_GEST
  UNION ALL -- IESIRI DIN TRANSFERURI
  SELECT
    T.CODTRANSF CodDoc, T.TIPDOC, T.PREFIXDOC, T.NRDOC, T.DATADOC,
  --t.prefixdoc ||t.seriadoc||t.nrdoc||''/''||to_date(t.datadoc,''dd.mm.yyyy'') Doc,
    coalesce(t.prefixdoc,'''') ||coalesce(t.seriadoc,'''')||coalesce(t.nrdoc::varchar,'''')||''/''||coalesce(to_char(t.datadoc,''dd.mm.yyyy''),'''') Doc,
    coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',T.TIPDOC)),''''),
    0 Addebit, 0 ValDFTva, 0 ValDCTva, 0 TvaD,
    SUM(L1.CANT * (LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0)) - LV.PRETACHIZ)) AdCredit,
    SUM(L1.CANT * LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0))) ValCFTva, SUM(L1.CANT * LV.PRETINREG) ValCCTva,
    SUM(L1.CANT * LV.PRETINREG * Coalesce(LV.TVANEEX, 0) / (1+Coalesce(LV.TVANEEX, 0))) TvaC,
    -SUM(L1.CANT * LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0))) SoldFinFTva, -SUM(L1.CANT * LV.PRETINREG) SoldFinCTva,
    NG_D.DEN_GEST SursaDest, IOA1.DEN_IOART,
    0 SoldIn, 0 AchizIn, 0 SoldAd,
    0 Coef,
    NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
    L.NRLIVR||''/''||to_char(L.DATALIVR,''dd.mm.yyyy'') RecLivr, TO_CHAR(L.DATALIVR,''DD'')::numeric Zi, TO_CHAR(T.DATADOC,''DD'')::numeric ZiDoc, Coalesce(LV.TVANEEX, 0) * 100 PjTVA  --am pus col.Zi,ZiDoc de tip numeric
  FROM TRANSF T
    INNER JOIN LIVR    L    ON L.CODTRANSF   = T.CODTRANSF
    INNER JOIN LIVR1   L1   ON L1.CODLIVR    = L.CODLIVR
    INNER JOIN LIVRVAL LV   ON LV.CODLIVR1   = L1.CODLIVR1'||pkg_list_base_rapgesttvaval_jointmp('LV.GEST')||'
    INNER JOIN IOA1         ON IOA1.CODIOART = LV.CODIOART
    INNER JOIN NGEST   NG   ON NG.CODGEST    = LV.GEST '|| coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(null,'NG','CODSUBUNIT',null,null))::varchar,'')||'
    LEFT  JOIN NIRSTOC NS_D ON NS_D.CODLIVR1 = L1.CODLIVR1
    LEFT  JOIN NIR     N_D  ON N_D.CODNIR    = NS_D.CODNIR
    LEFT  JOIN NGEST   NG_D ON NG_D.CODGEST  = N_D.GEST
  WHERE T.TIPDOC = 12 AND T.OPERAT = 1 AND T.ANULAT = 0
    AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
    AND L.DATALIVR'||sCondData||'
  GROUP BY T.CODTRANSF, T.TIPDOC, T.PREFIXDOC, T.SERIADOC, T.NRDOC, T.DATADOC, L.NRLIVR, L.DATALIVR, Coalesce(LV.TVANEEX, 0), IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST, NG_D.DEN_GEST
  UNION ALL -- MODIFICARI DE PRET
  SELECT
    T.CODTRANSF CodDoc, T.TIPDOC, T.PREFIXDOC, T.NRDOC, T.DATADOC,
  --t.prefixdoc ||t.seriadoc||t.nrdoc||''/''||to_date(t.datadoc,''dd.mm.yyyy'') Doc,
    coalesce(t.prefixdoc,'''') ||coalesce(t.seriadoc,'''')||coalesce(t.nrdoc::varchar,'''')||''/''||coalesce(to_char(t.datadoc,''dd.mm.yyyy''),'''') Doc,
    coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',T.TIPDOC)),''''),
    SUM(NS.CANTNIR * (NS.ADAOS - NS.PRET * NS.TVA / (1+NS.TVA))) AdDebit, SUm(NS.CANTNIR * NS.PRET / (1+NS.TVA)) ValDFTva, SUM(NS.CANTNIR * NS.PRET) ValDCTva,
    SUM(NS.CANTNIR * NS.PRET * NS.TVA / (1+NS.TVA)) TVAD,
    SUM(NS.CANTNIR * (Case  When NS.CODNIRSTOCPARINTE IS NULL then (LV_S.PRETINREG / (1+LV_S.TVANEEX) - LV_S.PRETACHIZ) else (NS_S.ADAOS - NS_S.PRET * NS_S.TVA / (1+NS_S.TVA)) end)) AdCredit,
    SUM(NS.CANTNIR * (Case  When NS.CODNIRSTOCPARINTE IS NULL then LV_S.PRETINREG / (1+LV_S.TVANEEX) else NS_S.PRET / (1+NS_S.TVA) end)) ValCFTva,
    SUM(NS.CANTNIR * (Case  When NS.CODNIRSTOCPARINTE IS NULL then LV_S.PRETINREG else NS_S.PRET end)) ValCCTva,
    SUM(NS.CANTNIR * (Case  When NS.CODNIRSTOCPARINTE IS NULL then LV_S.PRETINREG * LV_S.TVANEEX / (1+LV_S.TVANEEX) else NS_S.PRET * NS_S.TVA / (1+NS_S.TVA) end)) TvaC,
    SUM(NS.CANTNIR * NS.PRET / (1+NS.TVA)) - SUM(NS.CANTNIR * (Case  When NS.CODNIRSTOCPARINTE IS NULL then LV_S.PRETINREG / (1+LV_S.TVANEEX) else NS_S.PRET / (1+NS_S.TVA) end))  SoldFinFTva,
    SUM(NS.CANTNIR * NS.PRET) - SUM(NS.CANTNIR * (Case  When NS.CODNIRSTOCPARINTE IS NULL then LV_S.PRETINREG else NS_S.PRET end)) SoldFinCTva,
    NG.DEN_GEST SursaDest, IOA1.DEN_IOART,
    SUM(NS.CANTNIR * NS.PRET) SoldIn, SUM(NS.CANTNIR * (NS.PRET - NS.ADAOS)) AchizIn, 0 SoldAd,
    (Case  When SUM(NS.CANTNIR * (NS.PRET - NS.ADAOS))=0 then 0 else SUM(NS.CANTNIR * NS.PRET) / SUM(NS.CANTNIR * (NS.PRET - NS.ADAOS)) end) Coef,
    NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
    N.NRNIR||''/''||to_char(N.DATANIR,''dd.mm.yyyy'') RecLivr, TO_CHAR(N.DATANIR,''DD'')::numeric Zi, TO_CHAR(T.DATADOC,''DD'')::numeric ZiDoc, NS.TVA * 100 PjTva  --am pus col.Zi,ZiDoc de tip numeric
  FROM TRANSF T
    INNER JOIN NIR     N    ON N.CODTRANSF     = T.CODTRANSF'||pkg_list_base_rapgesttvaval_jointmp('N.GEST')||'
    INNER JOIN NIRSTOC NS   ON NS.CODNIR       = N.CODNIR
    INNER JOIN IOA1         ON IOA1.CODIOART   = NS.CODIOART
    INNER JOIN NGEST   NG   ON NG.CODGEST      = N.GEST '|| coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(null,'NG','CODSUBUNIT',null,null))::varchar,'')||'
    LEFT  JOIN NIRSTOC NS_S ON NS_S.CODNIRSTOC = NS.CODNIRSTOCPARINTE AND (NS.CODNIRSTOCPARINTE IS NOT NULL)
    LEFT  JOIN NIR     N_S  ON N_S.CODNIR      = NS_S.CODNIR
    LEFT  JOIN LIVR1   L1_S ON L1_S.CODLIVR1   = NS.CODLIVR1 AND (NS.CODNIRSTOCPARINTE IS NULL)
    LEFT  JOIN (SELECT CODLIVR1, Coalesce(PRETINREG, 0) PRETINREG, Coalesce(PRETACHIZ, 0) PRETACHIZ, Coalesce(TVANEEX, 0) TVANEEX, GEST
               FROM LIVRVAL
              )        LV_S ON LV_S.CODLIVR1 = L1_S.CODLIVR1
    LEFT  JOIN NGEST   NG_S ON NG_S.CODGEST  = Coalesce(N_S.GEST,LV_S.GEST)
  WHERE T.TIPDOC = 13 AND T.ANULAT = 0 AND T.OPERAT = 1
    AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
    AND N.DATANIR'||sCondData||'
  GROUP BY T.CODTRANSF, T.TIPDOC, T.PREFIXDOC, T.SERIADOC, T.NRDOC, T.DATADOC, N.NRNIR, N.DATANIR, NS.TVA, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST, NG_S.DEN_GEST
  UNION ALL -- RETUR INTRARI VALORIC
  SELECT
    I.CODINTR CodDoc, I.TIPDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC,
  --i.prefixdoc ||i.seriadoc||i.nrdoc ||''/''||to_date(i.datadoc,''dd.mm.yyyy'') Doc,
    coalesce(i.prefixdoc,'''') ||coalesce(i.seriadoc,'''')||coalesce(i.nrdoc::varchar,'''') ||''/''||coalesce(to_char(i.datadoc,''dd.mm.yyyy''),'''') Doc,
    coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',I.TIPDOC)),''''),
    - SUM(L1.CANT * (LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0)) - LV.PRETACHIZ) ) AdDebit, - SUM(L1.CANT * LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0))) ValDFTva,
    - SUM(L1.CANT * LV.PRETINREG) ValDCTva, - SUM(L1.CANT * LV.PRETINREG * Coalesce(LV.TVANEEX, 0) / (1+Coalesce(LV.TVANEEX, 0))) TvaD,
    0 Adcredit, 0 ValCFTva, 0 ValCCTva, 0 TvaC,
    -SUM(L1.CANT * LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0))) SoldFinFTva, -SUM(L1.CANT * LV.PRETINREG) SoldFinCTva,
    (Case  When I.TIPDOC=6 then S.DEN_SUBUNIT When I.TIPDOC=7 then G.DEN_GEST else NP.DEN_PART end) SursaDest, IOA1.DEN_IOART,
    0 SoldIn, 0 AchizIn, 0 SoldAd,
    0 Coef,
    NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
    L.NRLIVR||''/''||to_char(L.DATALIVR,''dd.mm.yyyy'') RecLivr, TO_CHAR(L.DATALIVR,''DD'')::numeric Zi, TO_CHAR(I.DATADOC,''DD'')::numeric ZiDoc, Coalesce(LV.TVANEEX, 0) * 100 PjTVA  --am pus col.Zi,ZiDoc de tip numeric
  FROM INTRARI I
    INNER JOIN LIVR     L  ON L.CODINTR     = I.CODINTR
    INNER JOIN LIVR1    L1 ON L1.CODLIVR    = L.CODLIVR
    INNER JOIN LIVRVAL  LV ON LV.CODLIVR1   = L1.CODLIVR1'||pkg_list_base_rapgesttvaval_jointmp('LV.GEST')||'
    INNER JOIN IOA1        ON IOA1.CODIOART = LV.CODIOART
    INNER JOIN NGEST    NG ON NG.CODGEST    = LV.GEST '|| coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(null,'NG','CODSUBUNIT',null,null))::varchar,'')||'
    LEFT  JOIN NPART    NP ON NP.CODPART    = I.PARTENER
    LEFT  JOIN NGEST    G  ON G.CODGEST     = I.CODGESTPROD
    LEFT  JOIN NSUBUNIT S  ON S.CODSUBUNIT  = I.CODSUBUNIT
  WHERE I.TIPDOC IN (1, 2, 3, 4, 5, 6, 7) AND I.OPERAT = 1 AND I.ANULAT = 0
    AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
    AND L.DATALIVR'||sCondData||'
  GROUP BY I.CODINTR, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC, L.NRLIVR, L.DATALIVR, Coalesce(LV.TVANEEX, 0), IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST, NP.DEN_PART, S.DEN_SUBUNIT, G.DEN_GEST
  UNION ALL  -- IESIRI VALORIC
  SELECT
    I.CODIES CodDoc, I.TIPDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC,
  --i.prefixdoc ||i.seriadoc||i.nrdoc ||''/''||to_date(i.datadoc,''dd.mm.yyyy'') Doc,
    coalesce(i.prefixdoc,'''') ||coalesce(i.seriadoc,'''')||coalesce(i.nrdoc::varchar,'''') ||''/''||coalesce(to_char(i.datadoc,''dd.mm.yyyy''),'''') Doc,
    coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',I.TIPDOC)),''''),
    0 AdDebit, 0 ValDFTva, 0 ValDCTva, 0 TvaD,
    SUM(L1.CANT * (LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0)) - LV.PRETACHIZ) ) Adcredit, SUM(L1.CANT * LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0))) ValCFTva, SUM(L1.CANT * LV.PRETINREG) ValCCTva,
    SUM(L1.CANT * LV.PRETINREG * Coalesce(LV.TVANEEX, 0) / (1+Coalesce(LV.TVANEEX, 0))) TvaC,
    -SUM(L1.CANT * LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0))) SoldFinFTva, -SUM(L1.CANT * LV.PRETINREG) SoldFinCTva,
    (Case  When I.TIPDOC=14 then ''-'' When I.TIPDOC=16 then ''-'' When I.TIPDOC=23 then S.DEN_SUBUNIT When I.TIPDOC=24 then NG.DEN_GEST else NP.DEN_PART end) SursaDest, IOA1.DEN_IOART,
    0 SoldIn, 0 AchizIn, 0 SoldAd,
    0 Coef,
    NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
    L.NRLIVR||''/''||to_char(L.DATALIVR,''dd.mm.yyyy'') RecLivr, TO_CHAR(L.DATALIVR,''DD'')::numeric Zi, TO_CHAR(I.DATADOC,''DD'')::numeric ZiDoc, Coalesce(LV.TVANEEX, 0) * 100 PjTVA  --am pus col.Zi,ZiDoc de tip numeric
  FROM IESIRI I
    INNER JOIN LIVR     L  ON L.CODIES      = I.CODIES
    INNER JOIN LIVR1    L1 ON L1.CODLIVR    = L.CODLIVR
    INNER JOIN LIVRVAL  LV ON LV.CODLIVR1   = L1.CODLIVR1'||pkg_list_base_rapgesttvaval_jointmp('LV.GEST')||'
    INNER JOIN IOA1        ON IOA1.CODIOART = LV.CODIOART
    INNER JOIN NGEST    NG ON NG.CODGEST    = LV.GEST '|| coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(null,'NG','CODSUBUNIT',null,null))::varchar,'')||'
    LEFT  JOIN NPART    NP ON NP.CODPART    = I.PARTENER
    LEFT  JOIN NGEST    G  ON G.CODGEST     = I.CODGESTPROD
    LEFT  JOIN NSUBUNIT S  ON S.CODSUBUNIT  = I.CODSUBUNIT
  WHERE I.TIPDOC IN (14, 16, 19, 20, 21, 22, 23, 24) AND I.OPERAT = 1 AND I.ANULAT = 0
    AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
    AND L.DATALIVR'||sCondData||'
  GROUP BY I.CODIES, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC, L.NRLIVR, L.DATALIVR, Coalesce(LV.TVANEEX, 0), IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST, NP.DEN_PART, S.DEN_SUBUNIT, G.DEN_GEST
  UNION ALL -- MARIRI DE STOC VALORIC
  SELECT
    I.CODIES CodDoc, I.TIPDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC,
  --i.prefixdoc ||i.seriadoc||i.nrdoc ||''/''||to_date(i.datadoc,''dd.mm.yyyy'') Doc,
    coalesce(i.prefixdoc,'''') ||coalesce(i.seriadoc,'''')||coalesce(i.nrdoc::varchar,'''') ||''/''||coalesce(to_char(i.datadoc,''dd.mm.yyyy''),'''') Doc,
    coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',I.TIPDOC)),''''),
    SUM(L1.CANT * (LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0)) - LV.PRETACHIZ)) AdDebit, SUM(L1.CANT * LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0))) ValDFTva, SUM(L1.CANT * LV.PRETINREG) ValDCTva,
    SUM(L1.CANT * LV.PRETINREG * Coalesce(LV.TVANEEX, 0) / (1+Coalesce(LV.TVANEEX, 0))) TvaD, 0 Adcredit, 0 ValCFTva, 0 ValCCTva, 0 TvaC,
    SUM(L1.CANT * LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0))) SoldFinFTva, SUM(L1.CANT * LV.PRETINREG) SoldFinCTva,
    NG.DEN_GEST SursaDest, IOA1.DEN_IOART,
    SUM(L1.CANT * LV.PRETINREG) SoldIn, SUM(L1.CANT * LV.PRETINREG) AchizIn, 0 SoldAd,
    (Case  When SUM(L1.CANT * LV.PRETINREG)=0 then 0 else SUM(L1.CANT * LV.PRETINREG) / SUM(L1.CANT * LV.PRETINREG) end) Coef,
    NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
    L.NRLIVR||''/''||to_char(L.DATALIVR,''dd.mm.yyyy'') RecLivr, TO_CHAR(L.DATALIVR,''DD'')::numeric Zi, TO_CHAR(I.DATADOC,''DD'')::numeric ZiDoc, Coalesce(LV.TVANEEX, 0) * 100 PjTVA  --am pus col.Zi,ZiDoc de tip numeric
  FROM IESIRI I
    INNER JOIN LIVR    L  ON L.CODIES      = I.CODIES
    INNER JOIN LIVR1   L1 ON L1.CODLIVR    = L.CODLIVR
    INNER JOIN LIVRVAL LV ON LV.CODLIVR1   = L1.CODLIVR1'||pkg_list_base_rapgesttvaval_jointmp('LV.GEST')||'
    INNER JOIN IOA1       ON IOA1.CODIOART = LV.CODIOART
    INNER JOIN NGEST   NG ON NG.CODGEST    = LV.GEST '||
    coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(null,'NG','CODSUBUNIT',null,null))::varchar,'')||'
  WHERE I.TIPDOC = 15 AND I.OPERAT = 1 AND I.ANULAT = 0
    AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
    AND L.DATALIVR'||sCondData||'
  GROUP BY I.CODIES, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC, L.NRLIVR, L.DATALIVR, Coalesce(LV.TVANEEX, 0), IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST';

 PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
 EXECUTE 'UPDATE ' || coalesce(tmpName,'') || ' SET SoldAd=AdDebit-AdCredit WHERE SoldAd=0';
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_raportagenti_processlist</obj_name>
  <obj_hashval>26ba6f42acf379fed009fc3b17d59e85</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportagenti_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar := '';
  sSelect     varchar := '';
  sWhereP     varchar := '';
  gSuplCols   VARCHAR := 'npers ag';
   gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  vTipData    boolean := current_setting('PKG_LIST_BASE_RAPORTAGENTI.vTipData', true)::boolean;
  vInceput    varchar := current_setting('PKG_LIST_BASE_RAPORTAGENTI.vInceput', true);  --poate fi de tip data sau de tip numeric
  vSfarsit    varchar := current_setting('PKG_LIST_BASE_RAPORTAGENTI.vSfarsit', true);  --poate fi de tip data sau de tip numeric
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_RAPORTAGENTI.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  IF vTipData THEN
    sWhereP := 'I.DATADOC';
  ELSE
    sWhereP := 'I.An*12 + I.LUNA';
  END IF;

  IF  vInceput = vSfarsit THEN
    sWhereP := coalesce(sWhereP,'') || ' = ' || vInceput;
  ELSE
    sWhereP := coalesce(sWhereP,'') || ' BETWEEN ' || vInceput || ' AND ' || vSfarsit;
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(Agent, NrCli, NrIes, NrPromo, Val, Tva' || gUserFields || ')';

  sSelect := '
  WITH
    CA AS (
      SELECT Min(codies) codies
      FROM  (  SELECT partener, codlocatie, subunitatea, codies, dense_rank() over(partition by i.partener, i.codlocatie, i.subunitatea ORDER BY i.datadoc asc, i.codies asc) NR
              FROM iesiri i
              WHERE i.anulat = 0 AND i.operat = 1
                AND i.tipdoc::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''TIPDOC'')
                AND coalesce(i.partener,0) &lt;&gt; 0 AND coalesce(i.codlocatie,0) &lt;&gt; 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('i',NULL,NULL,NULL),'') || '
            ) aa
      WHERE NR=1
      GROUP BY partener, codlocatie, subunitatea),
    IG AS (
      SELECT
        coalesce(I.AGENT,0) AGENT, coalesce(I.PARTENER,0) PARTENER, coalesce(I.CODLOCATIE,0) CODLOCATIE, I.CODIES,
        MAX(CASE WHEN coalesce(I1.CADOU,0) = 1 THEN 1 WHEN coalesce(AE1.CADOU,0) = 1 THEN 1 WHEN coalesce(I1.PU,0) = 0 THEN 1 ELSE 0 END) Cadou,
        I.ValDoc, I.TVADoc
      FROM IESIRI I
        INNER JOIN IESIRI1 I1  ON I1.CODIES   = I.CODIES
        INNER JOIN NARTOBJ O   ON O.CODOBIECT = I1.CODOBIECT
        LEFT  JOIN IESLINK IL  ON IL.CODIES1  = I1.CODIES1
        LEFT  JOIN IESIRI1 AE1 ON AE1.CODIES1 = IL.CODLINIEAVIZ
      WHERE ' || coalesce(sWhereP,'') || '
        AND I.TIPDOC::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''TIPDOC'')
        AND I.ANULAT = 0 AND I.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
      GROUP BY I.CODIES, coalesce(I.AGENT,0), I.PARTENER, I.CODLOCATIE, I.ValDoc, I.TVADoc),
    G AS (
      SELECT
        AGENT,
        --COUNT(DISTINCT PARTENER||''_''||CODLOCATIE) NrCli,
        SUM((case when CA.CODIES is NULL then 0 else 1 end)) NrCli,
        COUNT(1) NrIes, Sum(Cadou) NrPromo, Sum(ValDoc) Val, Sum(TvaDoc) Tva
      FROM IG LEFT JOIN CA ON CA.CODIES = IG.CODIES
      GROUP BY AGENT)
  SELECT (case when G.AGENT=0 then AG.NUME else AG.NUME||'' ''||AG.PRENUME end) AGENT, G.NrCli, G.NrIes, G.NrPromo, G.VAL, G.TVA
  FROM G LEFT JOIN NPERS AG ON AG.CODPERS = G.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_restlistgest_processlistdif</obj_name>
  <obj_hashval>475008dfb8cec040b42c9b61cca75339</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_restlistgest_processlistdif(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  S varchar := '';
begin
  -- Bogdan 30.06.2023 - corectie sincronizare
  --Florin 26.05.2023 - sinc. Oracle
  --Adina 15.10.2020
  S := 'INSERT INTO ' || TMPNAME || '(DENUMIRE, DENUM, CANT, OBS, ORDINE) ' || CHR(13) ||
  ' SELECT '               || CHR(13) ||
  '   M.DENUMIRE, '         || CHR(13) ||
  '   M.DUM, '               || CHR(13) ||
  '   M.CANTNOUA - M.CANT, '   || CHR(13) ||
  '   M.OBS, '               || CHR(13) ||
  '   R.ORDINE '          ||  CHR(13) ||
  ' FROM '                 || CHR(13) ||
  '   TMP_MODIRESTCMD1 M INNER JOIN RESTCMD1 R ON R.CODRESTCMD1 = M.CODRESTCMD1';
  PERFORM LIST_EXECUTE_IMMEDIATE(s, aListID, aListVer);
END;
$function$
</obj_text>
</row>

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

  sConv       varchar;
BEGIN
  --Florin 13.07.2023 - fixat 58862
  --Florin 11.07.2023 - sinc. oracle
  --Stef 08.08.2022
  IF NOT PKG_LIST_SELECTSCADENTAR_TMPOk() THEN
    PERFORM PKG_LIST_BASE_SCADENTARF_UmpleTmp(aListId);
  END IF;
  sConv    := coalesce(current_setting('PKG_LIST_BASE_SCADENTARF.sConv',    true),'');

  gSuplCols :=
    'TMP_SCADENTARF S, TMP_LST_SCAD_STINS STINS, 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,'||
    '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, 'INTRARIF', 'IEXT', 'iext.codintr = s.coddoc AND s.tipdoc IN (1, 9)');
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_SCADENTARF.gSuplCols',gSuplCols,false);

  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 o.semnificatie IN (110,111)                               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_SCADENTARF_CalcAdaosDoc(S.CodDoc,s.restval - Coalesce(stins.valoare,0))
    END'||sConv||' ADAOS';
  END IF;

  IF PKG_LIST_SELECTSCADENTAR_CalcDiscTermen() THEN
    sValDiscZP := ',
        Coalesce((Select wme_result From PKG_CONTRACT_CALCULEAZA_DISCT_DOC(null, s.TipDoc, s.CodDoc, ''' || sDataRef || ''', (s.restval - Coalesce(stins.valoare,0)))), 0)' || sConv || ' VALDISCZP,
        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)' || sConv || ' VALDISCC';
  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,
    RESTSPLITTVA,
    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,
    SUBUNITATE, EXCLUSPLATA, CREDITF, SERTDECONT, SERTDOC, SERTSER, SERTNRDOC, SERTDATADOC, SERTVALDOC, SERTDATADEC, SERTVALASOC, CENTRUCOST, SIMBCENTRUCOST,
    AVANS, PROCTVAMEDIU,
    TVAINCAS, SPLITTVA,
    VALMT103,
    CF_AS, CF_CURS,
    ANSAPT, CURS,CURS_INI,CURS_REF,ADAOSDOC,VALDISCZP, VALDISCC '||gUserFields||')';

  sSelect := '
  SELECT
    CASE WHEN ts.codsubunit IS NULL OR s.initializari = 1 THEN NULL ELSE s.CodDoc  END NAV_CodDoc,
    CASE WHEN ts.codsubunit IS NULL OR s.initializari = 1 THEN NULL ELSE s.CodDoc1 END NAV_CodDoc1,
    CASE WHEN ts.codsubunit IS NULL OR s.initializari = 1 THEN NULL ELSE s.TipDoc  END NAV_TipDoc,
    (Select wme_result From pkg_list_base_utils_decode_tipdoc(null,s.TipDoc)) TipDoc,
    np.den_part, g.den_gest, fisc.codfiscal, slivr.obs LIVR_DEN, llivr.den_localit LIVR_LOC, jlivr.den_judet LIVR_JUD, zlivr.den_zona LIVR_ZONA, ncp.den_clasep,
    CASE WHEN np.blocat = 1 THEN ''DA'' ELSE ''NU'' END BLOCAT, CASE WHEN s.blocat = 1 THEN ''DA'' ELSE ''NU'' END BLOCATDOC, s.doc, s.nrdoc, s.datadoc, s.nri, s.obs OBSDOC, Coalesce(s.seriadoc,dc.serie) SERDOC,
    CASE WHEN ag_doc.codpers &lt;&gt; 0 THEN ag_doc.nume||'' ''||ag_doc.prenume ELSE ag_doc.nume END AGDOC,
    Coalesce(s.termen,s.datadoc) TERMEN, EXTRACT(YEAR FROM Coalesce(s.termen,s.datadoc)) TERMENAN, EXTRACT(MONTH FROM Coalesce(s.termen,s.datadoc)) TERMENLUNA,
    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 || ' VALOARE,
    s.majorare,
    (s.restval - Coalesce(stins.valoare,0))' || sConv || ' REST,
    (s.restsplittva - Coalesce(stins.dincaretva,0))' || sConv || ' RESTTVA,
    (s.resttva - Coalesce(stins.tva,0))' || sConv || ' RESTTVA,
    Sum((s.restval - Coalesce(stins.valoare,0))' || sConv || ') OVER (PARTITION BY s.codpart) RESTPART,
    CASE
      WHEN s.zile_depasire &lt;= 0 THEN 0
      ELSE ((s.restval - Coalesce(stins.valoare,0) - CASE WHEN o.semnificatie IN (110,310,330) THEN s.resttva - Coalesce(stins.tva,0) ELSE 0 END) * s.majorare/100 * s.zile_depasire)
    END ' || sConv || ' valmaj,
    COALESCE(s.termen - s.datadoc,0) ZILE_SCADENTA, CASE WHEN s.zile_trecute &gt; 0 THEN s.zile_trecute ELSE 0 END ZILE_TRECUTE, s.zile_depasire,
    coalesce(s.doc::varchar,'''')||coalesce(s.nrdoc::varchar,'''')||''/''||coalesce(to_char(s.datadoc,''dd.mm.yyyy''),'''') as DOCUMENT,
    mon.den_moneda MONEDA, nc.simbol CONT, cs.simbol CONTS,
    CASE WHEN s.zile_depasire &lt;= 0                THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END Z_0,
    CASE WHEN s.zile_depasire BETWEEN   1 AND  30 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END L_1,
    CASE WHEN s.zile_depasire BETWEEN  31 AND  60 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END L_2,
    CASE WHEN s.zile_depasire BETWEEN  61 AND  90 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END L_3,
    CASE WHEN s.zile_depasire BETWEEN  91 AND 120 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END L_4,
    CASE WHEN s.zile_depasire BETWEEN 121 AND 150 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END L_5,
    CASE WHEN s.zile_depasire BETWEEN 151 AND 180 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END L_6,
    CASE WHEN s.zile_depasire BETWEEN  91 AND 180 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END T_2,
    CASE WHEN s.zile_depasire BETWEEN 181 AND 270 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END T_3,
    CASE WHEN s.zile_depasire BETWEEN 181 AND 210 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END T_31,
    CASE WHEN s.zile_depasire BETWEEN 211 AND 240 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END T_32,
    CASE WHEN s.zile_depasire BETWEEN 241 AND 270 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END T_33,
    CASE WHEN s.zile_depasire BETWEEN 271 AND 360 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END T_4,
    CASE WHEN s.zile_depasire BETWEEN   1 AND   7 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END S_1,
    CASE WHEN s.zile_depasire BETWEEN   8 AND  15 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END S_2,
    CASE WHEN s.zile_depasire BETWEEN  16 AND  21 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END S_3,
    CASE WHEN s.zile_depasire BETWEEN  22 AND  30 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END S_4,
    CASE WHEN s.zile_depasire &gt;  30               THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END P_30,
    CASE WHEN s.zile_depasire &gt;  60               THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END P_60,
    CASE WHEN s.zile_depasire &gt;  90               THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END P_90,
    CASE WHEN s.zile_depasire &gt; 360               THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END P_360,
    CASE WHEN s.zile_depasire BETWEEN  -7 AND  -1 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END TS_1,
    CASE WHEN s.zile_depasire BETWEEN -14 AND  -8 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END TS_2,
    CASE WHEN s.zile_depasire BETWEEN -21 AND -15 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END TS_3,
    CASE WHEN s.zile_depasire BETWEEN -28 AND -22 THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END TS_4,
    CASE WHEN s.zile_depasire &lt; -28               THEN (s.restval - Coalesce(stins.valoare,0))' || sConv || ' ELSE 0 END TS_4p,
    sub.den_subunit SUBUNITATE, CASE WHEN s.exclusplata = 1 THEN ''DA'' ELSE ''NU'' END EXCLUSPLATA, np1.creditfurn CREDITF,
    TLSS.DECONT SERTDECONT, TLSS.DOC SERTDOC, TLSS.SER SERTSER, TLSS.NRDOC SERTNRDOC, TLSS.DATADOC SERTDATADOC, TLSS.VALOARE SERTVALDOC, TLSS.DATADECONT SERTDATADEC, TLSS.VALASOC SERTVALASOC,
    CC.DENUMIRE CENTRUCOST, substr(CC.SIMBOL, 40) SIMBCENTRUCOST,
    CASE WHEN O.semnificatie IN (110,111,210,211,310,330,410,430) THEN ''DA'' ELSE ''NU'' END AVANS, Coalesce(s.TVAMediu,0) PROCTVAMEDIU,
    CASE WHEN s.TvaIncasare = 1 THEN ''DA'' ELSE ''NU'' END TVAINCAS, CASE WHEN s.SplitTVA = 1 THEN ''DA'' ELSE ''NU'' END SPLITTVA,
    Coalesce(
      ( SELECT SUM(Coalesce(p1103.REST,0))
        FROM plati1 p1103 INNER JOIN PLATI P ON P.CODPLATA = P1103.CODPLATA
        WHERE p1103.codobligpif = s.codobligpif AND P1103.REST &lt;&gt; 0
      ), 0) VALMT103,
    TO_CHAR( Coalesce(s.termen,s.datadoc+Coalesce(np.scadentac,0)::integer),''IYYY.IW'') CF_AS, Coalesce(cfc.valoare,1) CF_CURS,
    s.ansapt, s.curs,s.cursini'||sCursRef||sFAdaosDoc||sValDiscZP||gUserAlias||'
  FROM tmp_scadentarf s
    LEFT JOIN obligpif            o          ON o.codobligpif            = s.codobligpif
    LEFT JOIN npart               np         ON np.codpart               = s.codpart
    LEFT JOIN tmp_scadf_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 '||getAnLunaLucru()::varchar||' 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 '||getAnLunaLucru()::varchar||' BETWEEN np1.ALStart and np1.ALStop
    LEFT JOIN iopart              iop        ON iop.codiopart            = np1.codiopart
    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 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 tlss       ON tlss.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
    LEFT JOIN TMP_LST_CURS        cfc        ON cfc.codmoneda            = s.moneda'||
    gSuplJoins||'
  WHERE (Abs(s.restval - Coalesce(stins.valoare,0)) &gt;= 0.01 OR Abs(s.restsplittva - Coalesce(stins.dincaretva,0)) &gt;= 0.01)';

  PERFORM PKG_LIST_BASE_UTILS_UMPLE_TMP_LST_CURS(NULL,NULL,NULL);
  PERFORM LIST_EXECUTE_IMMEDIATE('UPDATE tmp_lst_scad_stins SET VALOARE = VALOARE+DINCARETVA', aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE('UPDATE ' || coalesce(tmpname,'') || ' SET CF_VALOARE = CF_CURS*REST', aListID, aListVer);

  IF PKG_LIST_SELECTSCADENTAR_CalcDiscTermen() THEN
    EXECUTE 'SELECT sum(valoare) FROM '||tmpname||' WHERE NAV_TipDoc IN (1,9)' 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 (1, 9)';
  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 WHEN ansapt = '||vrec.Cod||' THEN rest ELSE 0 END';
    END LOOP;
    sUpdate := 'UPDATE '||tmpname||' SET '||SubStr(sUpdate,2);
    IF i &gt; 0 THEN
      EXECUTE sUpdate;
    END IF;
  END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_scadentarf_umpletmp</obj_name>
  <obj_hashval>257779f556b553eac17da319f35d1aad</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_scadentarf_umpletmp(alistid numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsTMP        TEXT;
  sSelTMP        TEXT;
  sFiltruLuna    VARCHAR(200) := '';
  sAnP           NUMERIC(4);
  sLunaP         NUMERIC(2);
  sAnC           NUMERIC(4);
  sLunaC         NUMERIC(2);
  sZilePlusDoc   VARCHAR(100);
  sZilePlusTerm  VARCHAR(100);
  sZilePlusTermC VARCHAR(100);
  dDataRef       DATE          := PKG_LIST_SELECTSCADENTAR_DataRef();
  dDataCoalesce  DATE          := LAST_DAY(ADD_MONTHS(dDataRef,-1));
  sDataRef       VARCHAR(10)   := To_Char(dDataRef, 'dd.mm.yyyy');
  sDataCoalesce  VARCHAR(10)   := To_Char(dDataCoalesce, 'dd.mm.yyyy');
  sJoinFiltru    VARCHAR(500)  := '';
  sIcontS_F      VARCHAR(2500) := ',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';

  sConv          VARCHAR(100);
BEGIN
  --Florin 11.11.2025 - sinc. Oracle
  --Stef   11.06.2025 - fixat 58862
  --Florin 30.05.2025 - fixat 65790
  --Florin 28.04.2025 - sinc. Oracle
  --Florin 10.02.2025 - sinc. Oracle
  --Florin 07.02.2023 - sinc. Oracle
  --Florin 01.09.2022 - fixat 55412
  --Florin 19.08.20022 - fixat 55263
  TRUNCATE TABLE TMP_SCADENTARF;

  sZilePlusDoc  := '(TO_DATE('''||sDataRef||''',''dd.mm.yyyy'') - Coalesce(D.DATADOC,TO_DATE('''||sDataCoalesce||''',''dd.mm.yyyy'')))';

  IF current_setting('PKG_LIST_SELECTSCADENTAR.g_CodJob1', TRUE)::NUMERIC &gt; 0 THEN
    PERFORM pkg_globals_SetLunaLucru_SIMPLA(extract(year from dDataRef), extract(month from dDataRef));
  END IF;

  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 := ' = '||getAnLunaLucru()::varchar;
  ELSE
    SELECT  NEWAN, newLuna INTO sAnP, sLunaP from pkg_globals_Calculeaza_Luna_Precedenta(sAnC, sLunaC, sAnP, sLunaP);
    sFiltruLuna := ' BETWEEN '||(sAnC*12+sLunaC)::varchar||' AND '||getAnLunaLucru()::varchar;
  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 = 251 -- pe gestiuni
  THEN sConv := sConv||'*Coalesce(cg.Coef,1)';
  END IF;

  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)::varchar = 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::varchar = tmpp.valoare AND tmpp.filtru = ''CODPART'' ';
  END IF;

  IF PKG_LIST_SELECTSCADENTAR_TipIntarziere() = 0
  THEN
    sZilePlusTerm  := 'Coalesce(TO_DATE('''||sDataRef||''',''dd.mm.yyyy'')-Coalesce(O.TERMEN,D.DATADOC),0)';
    sZilePlusTermC := 'Coalesce(TO_DATE('''||sDataRef||''',''dd.mm.yyyy'')-COALESCE(D.DATADECONT,O.TERMEN,D.DATADOC),0)';
  ELSE
    sZilePlusTerm  := 'Coalesce(TO_DATE('''||sDataRef||''',''dd.mm.yyyy'')-D.DATADOC,0)';
    sZilePlusTermC := 'Coalesce(TO_DATE('''||sDataRef||''',''dd.mm.yyyy'')-D.DATADOC,0)';
  END IF;

  sInsTMP :=
  'INSERT INTO TMP_SCADENTARF (
    codobligpif,CodDoc,CodDoc1,TipDoc, codpart, doc, nrdoc, datadoc, nri, blocat, termen,
    valoare,
    tva,
    restval,
    restsplittva,
    resttva,
    majorare, zile_trecute, zile_depasire,
    cont, adaosdoc,
    moneda, cursini, obs, carnetdoc, seriadoc, subunitatea, agent, codlocatie, initializari,
    codgeneral, exclusplata,
    curs,
    codcentru, userid, tvamediu, tvaincasare, splittva, ansapt)';

  sSelTMP := '
  SELECT --FACTURI PERIOADA CURENTA
    o.codobligpif, g.coddoc, NULL coddoc1, g.tipdoc, o.codpart, Coalesce(d.PREFIXDOC,''F'') doc, Coalesce(d.nrdoc,0) nrdoc, d.datadoc, d.nri, d.blocat, o.termen,
    (o.valoare-
    CASE
      WHEN NOT(d.tiptva = 2 AND o.semnificatie=110) THEN 0
      WHEN O.VALOARE = 0         THEN 0
      WHEN Coalesce(G.TVA,0) = 0 THEN 0
      WHEN (SELECT SUM(xO.VALOARE) FROM OBLIGPIF xO WHERE xO.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) * CASE WHEN o.semnificatie = 110 THEN -1 ELSE 1 END valoare,
    CASE
      WHEN d.tiptva = 2 AND o.semnificatie=110 THEN 0
      WHEN O.VALOARE = 0         THEN 0
      WHEN Coalesce(G.TVA,0) = 0 THEN 0
      WHEN (SELECT SUM(xO.VALOARE) FROM OBLIGPIF xO WHERE xO.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 * CASE WHEN o.semnificatie = 110 THEN -1 ELSE 1 END tva,
    (o.valoare-
    CASE
      WHEN NOT(d.tiptva = 2 AND o.semnificatie=110) THEN 0
      WHEN O.VALOARE = 0         THEN 0
      WHEN Coalesce(G.TVA,0) = 0 THEN 0
      WHEN (SELECT SUM(xO.VALOARE) FROM OBLIGPIF xO WHERE xO.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) * CASE WHEN o.semnificatie = 110 THEN -1 ELSE 1 END restval,
    Coalesce(o.dincaretva,0) * CASE WHEN o.semnificatie = 110 THEN -1 ELSE 1 END restsplittva,
    CASE
      WHEN d.tiptva = 2 AND o.semnificatie=110 THEN 0
      WHEN O.VALOARE = 0         THEN 0
      WHEN Coalesce(G.TVA,0) = 0 THEN 0
      WHEN (SELECT SUM(xO.VALOARE) FROM OBLIGPIF xO WHERE xO.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 * CASE WHEN o.semnificatie = 110 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,'||getAnLunaLucru()::varchar||',o.semnificatie) cont, o.adaosdoc,
    Coalesce(g.moneda,0) Moneda, COALESCE(NullIf(g.curs,0), 1) cursini, d.obs, d.carnetdoc, d.seriadoc, d.subunitatea, NULL agent, d.codlocatie, d.Initializari,
    g.CodGeneral, d.exclusplata,
    Coalesce(rc.curs, COALESCE(NullIf(g.curs,0), 1)) curs,
    o.codcentru, d.userid,
    round(d.tvadoc/Coalesce(NULLIF(CASE WHEN d.tipdoc = 5 THEN d.valdoc ELSE d.valdoc-d.tvadoc END*100,0),1),2) TVAMediu,
    Coalesce(d.TvaIncasare,0) TvaIncasare, Coalesce(o.splittva,0) SplitTVA, to_char(Coalesce(o.termen,d.datadoc), ''IYYYIW'')::numeric
  FROM intrari d
    INNER JOIN general  g ON g.coddoc     = d.codintr AND g.tipdoc = d.tipdoc
    INNER JOIN obligpif o ON o.codgeneral = g.codgeneral'||
    sJoinFiltru||'
    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;= '||getAnLunaLucru()::varchar||') x where x.nr=1
      GROUP BY x.CodGeneral
    ) rc ON rc.codgeneral = g.codgeneral
  WHERE d.tipdoc IN (1,3,4,5,9)
    AND o.semnificatie IN (100,110,120)
    AND NOT (o.semnificatie = 110 AND Coalesce(g.tva,0)=o.valoare)
    AND d.an * 12 + d.luna'||sFiltruLuna||
    PKG_LIST_SELECTSCADENTAR_COND_SUBUNIT('d')||
    PKG_LIST_BASE_UTILS_COND_USERID ('d')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('d.DataDoc');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInstmp||sSeltmp, aLISTID, 0);

  sSelTMP := '
  SELECT --FACTURI CU SOLD LA INCEPUTUL PERIOADEI
    o.codobligpif, g.coddoc, NULL coddoc1, g.tipdoc, o.codpart, Coalesce(d.PREFIXDOC,''F'') doc, Coalesce(d.nrdoc,0) nrdoc, d.datadoc, d.nri, d.blocat, o.termen,
    (o.valoare-
    CASE
      WHEN NOT(d.tiptva = 2 AND o.semnificatie=110) THEN 0
      WHEN O.VALOARE = 0         THEN 0
      WHEN Coalesce(G.TVA,0) = 0 THEN 0
      WHEN (SELECT SUM(xO.VALOARE) FROM OBLIGPIF xO WHERE xO.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) * CASE WHEN o.semnificatie = 110 THEN -1 ELSE 1 END valoare,
    CASE
      WHEN d.tiptva = 2 AND o.semnificatie=110 THEN 0
      WHEN O.VALOARE = 0         THEN 0
      WHEN Coalesce(G.TVA,0) = 0 THEN 0
      WHEN (SELECT SUM(xO.VALOARE) FROM OBLIGPIF xO WHERE xO.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 * CASE WHEN o.semnificatie = 110 THEN -1 ELSE 1 END tva,
    (Coalesce(ol.rest,0)-CASE WHEN d.tiptva = 2 AND o.semnificatie=110 THEN Coalesce(ol.resttva,0) ELSE 0 END) * CASE WHEN o.semnificatie = 110 THEN -1 ELSE 1 END restval,
    Coalesce(ol.restsplittva,0) * CASE WHEN o.semnificatie = 110 THEN -1 ELSE 1 END restsplittva,
    CASE WHEN d.tiptva = 2 AND o.semnificatie=110 THEN 0 ELSE Coalesce(ol.resttva,0) END * CASE WHEN o.semnificatie = 110 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,'||getAnLunaLucru()::varchar||',o.semnificatie) cont, o.adaosdoc,
    Coalesce(g.moneda,0) Moneda, COALESCE(NullIf(g.curs,0), 1) cursini, d.obs, d.carnetdoc, d.seriadoc, d.subunitatea, NULL agent, d.codlocatie, d.Initializari,
    g.CodGeneral, d.exclusplata,
    Coalesce(rc.curs, COALESCE(NullIf(g.curs,0), 1)) curs,
    o.codcentru, d.userid,
    round(d.tvadoc/Coalesce(NULLIF(CASE WHEN d.tipdoc = 5 THEN d.valdoc ELSE d.valdoc-d.tvadoc END*100,0),1),2) TVAMediu,
    Coalesce(d.TvaIncasare,0) TvaIncasare, Coalesce(o.splittva,0) SplitTVA, to_char(Coalesce(o.termen,d.datadoc), ''IYYYIW'')::numeric
  FROM obligpifluna ol
    INNER JOIN obligpif o ON o.codobligpif = ol.codobligpif
    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 '||
    sJoinFiltru||'
    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;= '||getAnLunaLucru()::varchar||') x where x.nr=1
      GROUP BY x.CodGeneral
    ) rc ON rc.codgeneral = g.codgeneral
  WHERE ol.an = '||sAnP::varchar||' AND ol.luna = '||sLunaP::varchar||'
    AND (Coalesce(ol.rest,0) &lt;&gt; 0 OR Coalesce(ol.resttva,0) &lt;&gt; 0)
    AND o.semnificatie IN (100,110,120)
    AND NOT (o.semnificatie = 110 AND Coalesce(g.tva,0)=o.valoare)'||
    PKG_LIST_SELECTSCADENTAR_COND_SUBUNIT('d')||
    PKG_LIST_BASE_UTILS_COND_USERID ('d')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('d.DataDoc');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInstmp||sSeltmp, aLISTID, 0);

  sSelTMP := '
    SELECT --FACTURI ANTERIOARE PERIOADEI CU STINGERI IN LUNA CURENTA SI CU SOLD 0 LA INCEPUTUL PERIOADEI
    o.codobligpif, g.coddoc, NULL coddoc1, g.tipdoc, o.codpart, Coalesce(d.PREFIXDOC,''F'') doc, Coalesce(d.nrdoc,0) nrdoc, d.datadoc, d.nri, d.blocat, o.termen,
    (o.valoare-
    CASE
      WHEN NOT(d.tiptva = 2 AND o.semnificatie=110) THEN 0
      WHEN O.VALOARE = 0         THEN 0
      WHEN Coalesce(G.TVA,0) = 0 THEN 0
      WHEN (SELECT SUM(xO.VALOARE) FROM OBLIGPIF xO WHERE xO.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) * CASE WHEN o.semnificatie = 110 THEN -1 ELSE 1 END valoare,
    CASE
      WHEN d.tiptva = 2 AND o.semnificatie=110 THEN 0
      WHEN O.VALOARE = 0         THEN 0
      WHEN Coalesce(G.TVA,0) = 0 THEN 0
      WHEN (SELECT SUM(xO.VALOARE) FROM OBLIGPIF xO WHERE xO.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 * CASE WHEN o.semnificatie = 110 THEN -1 ELSE 1 END tva,
    0 restval,
    0 restsplitva,
    0 resttva,
    Coalesce(o.majorari,0) majorare, '||sZilePlusDoc||' zile_trecute, '||sZilePlusTerm||' zile_depasire,
    PKG_LIST_BASE_UTILS_iCont_CodCont(o.icont,o.codpart,'||getAnLunaLucru()::varchar||',o.semnificatie) cont, o.adaosdoc,
    Coalesce(g.moneda,0) Moneda, COALESCE(NullIf(g.curs,0), 1) cursini, d.obs, d.carnetdoc, d.seriadoc, d.subunitatea, NULL agent, d.codlocatie, d.Initializari,
    g.CodGeneral, d.exclusplata,
    Coalesce(rc.curs, COALESCE(NullIf(g.curs,0), 1)) curs,
    o.codcentru, d.userid,
    round(d.tvadoc/Coalesce(NULLIF(CASE WHEN d.tipdoc = 5 THEN d.valdoc ELSE d.valdoc-d.tvadoc END*100,0),1),2) TVAMediu,
    Coalesce(d.TvaIncasare,0) TvaIncasare, Coalesce(o.splittva,0) SplitTVA, to_char(Coalesce(o.termen,d.datadoc), ''IYYYIW'')::numeric
  FROM (
    SELECT DISTINCT o.codobligpif
    FROM trezor t
      INNER JOIN trezor1      t1 ON t1.codtrezor      = t.codtrezor
      INNER JOIN general      gs ON gs.coddoc         = t1.codtrezor1 AND gs.tipdoc = t.tipdoc
      INNER JOIN obligpif     os ON os.codgeneral     = gs.codgeneral
      INNER JOIN stingere     s  ON s.codstingatorpif = os.codobligpif
      INNER JOIN obligpif     o  ON o.codobligpif     = s.codstinspif
      INNER JOIN general      g  ON g.codgeneral      = o.codgeneral  AND g.tipdoc IN (1,3,4,5,9)
      LEFT  JOIN obligpifluna ol ON ol.codobligpif    = o.codobligpif AND ol.an = '||sAnP::varchar||' AND ol.luna = '||sLunaP::varchar||'
    WHERE t.tipdoc IN (29,30,31,33)
      AND gs.semnificatie = 700 AND (t.an*12+t.luna'||sFiltruLuna||')
      AND o.semnificatie IN (100,110,120)
      AND NOT (o.semnificatie = 110 AND Coalesce(g.tva,0)=o.valoare)
      AND Coalesce(ol.rest,0) = 0 AND Coalesce(ol.resttva,0) = 0 '||
      PKG_LIST_SELECTSCADENTAR_COND_SUBUNIT('t')||
      PKG_LIST_BASE_UTILS_COND_USERID ('t')||
      PKG_LIST_SELECTSCADENTAR_FiltruData('t.DataDoc')||'
  ) x
    INNER JOIN obligpif o ON o.codobligpif = x.codobligpif
    INNER JOIN general g ON g.codgeneral = o.codgeneral
    INNER JOIN intrari d ON d.codintr = g.coddoc '||
    sJoinFiltru||'
    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;= '||getAnLunaLucru()::varchar||'
      ) x where x.nr=1
      GROUP BY x.CodGeneral
    ) rc ON rc.codgeneral = g.codgeneral
  WHERE d.an * 12 + d.luna &lt;= '||To_Char(sAnP*12+sLunaP)||
    PKG_LIST_SELECTSCADENTAR_COND_SUBUNIT('d')||
    PKG_LIST_BASE_UTILS_COND_USERID ('d')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('d.DataDoc');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInstmp||sSeltmp, aLISTID, 0);

  sSelTMP := '
    SELECT -- FACTURI EXTERNE  -- PLATI VAMA
    o.codobligpif, i.codintr, NULL coddoc1, i.tipdoc, o.codpart, ''DVI'' doc, Coalesce(d.nrdoc,0) nrdoc, d.datadoc, i.nri, i.blocat, o.termen,
    o.valoare, Coalesce(g.tva,0),
    CASE WHEN ol.codobligpif IS NULL THEN o.valoare                ELSE ol.rest                     END restval,
    CASE WHEN ol.codobligpif IS NULL THEN Coalesce(o.dincaretva,0) ELSE Coalesce(ol.restsplittva,0) END restsplittva,
    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,'||getAnLunaLucru()::varchar||',o.semnificatie) cont, o.adaosdoc,
    Coalesce(g.moneda,0) Moneda, COALESCE(NullIf(g.curs,0), 1) curs, i.obs, i.carnetdoc, i.seriadoc, i.subunitatea, NULL agent, i.codlocatie, i.Initializari,
    g.CodGeneral, d.exclusplata,
    Coalesce(rc.curs, COALESCE(NullIf(g.curs,0), 1)) curs,
    o.codcentru, i.userid,
    round(i.tvadoc/Coalesce(NULLIF(CASE WHEN i.tipdoc = 5 THEN i.valdoc ELSE i.valdoc-i.tvadoc END*100,0),1),2) TVAMediu,
    Coalesce(d.TvaIncasare,0) TvaIncasare, Coalesce(o.splittva,0) SplitTVA, to_char(Coalesce(o.termen,d.datadoc), ''IYYYIW'')::numeric
  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 '||
    sJoinFiltru||'
    LEFT  JOIN obligpifluna ol ON ol.codobligpif = o.codobligpif AND ol.an = '||sAnP::varchar||' AND ol.luna = '||sLunaP::varchar||'
    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;= '||getAnLunaLucru()::varchar||') x where x.nr=1
      GROUP BY x.CodGeneral
    ) rc ON rc.codgeneral = g.codgeneral
  WHERE o.semnificatie = 130
    AND ((i.an * 12 + i.luna'||sFiltruLuna||') OR (Coalesce(ol.rest,0) &lt;&gt; 0) OR (Coalesce(ol.resttva,0) &lt;&gt; 0)) '||
    PKG_LIST_SELECTSCADENTAR_COND_SUBUNIT('i')||
    PKG_LIST_BASE_UTILS_COND_USERID ('i')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('d.DataDoc');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInstmp||sSeltmp, aLISTID, 0);

  DELETE FROM TMP_SCADF_COEFG;

  IF  aListID = 251 THEN
    INSERT INTO TMP_SCADF_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, I1.GESTACT, 0) CODGEST, Sum(I1.PRETORIG * I1.COEFDISCMAJ * COALESCE(NS.CANTFURN, I1.CANT)) VAL,
        Count(1) NRLINII, Sum(Sum(I1.PRETORIG * I1.COEFDISCMAJ * COALESCE(NS.CANTFURN, I1.CANT))) OVER (PARTITION BY S.CODOBLIGPIF) VALTOT
      FROM TMP_SCADENTARF S
        LEFT JOIN INTRARI  I  ON  I.CODINTR  = S.CODDOC  AND  I.TIPDOC = S.TIPDOC
        LEFT JOIN INTRARI1 I1 ON  I1.CODINTR = I.CODINTR
        LEFT JOIN NIR      N  ON  N.CODINTR  = I.CODINTR AND  N.TIPNIR = I.TIPDOC
        LEFT JOIN NIRSTOC  NS ON  NS.CODNIR  = N.CODNIR  AND  NS.CODINTR1 = I1.CODINTR1
      GROUP BY S.CODOBLIGPIF, COALESCE(N.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,d.datadoc) 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(o.dincaretva,0) ELSE Coalesce(ol.restsplittva,0) END restsplittva,
    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, '||sZilePlusTermC||' 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,
    Coalesce(g.moneda,0) 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, g.exclusplata,
    Coalesce(rc.curs, COALESCE(NullIf(g.curs,0), 1)) curs,
    o.codcentru, t.userid,
    0 TVAMediu,
    0 TvaIncasare, Coalesce(o.splittva,0) SplitTVA, to_char(Coalesce(d.datadecont,o.termen,d.datadoc), ''IYYYIW'')::numeric
   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||'
    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;= '||getAnLunaLucru()::varchar||'
      ) x where x.nr=1
      GROUP BY x.CodGeneral
    ) rc ON rc.codgeneral = g.codgeneral
  WHERE o.semnificatie = 500
    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
      EXISTS (
        SELECT 1
        FROM general gg
          INNER JOIN obligpif og ON og.codgeneral     = gg.codgeneral
          INNER JOIN stingere s  ON s.codstingatorpif = og.codobligpif
          INNER JOIN obligpif os ON os.codobligpif    = s.codstinspif
          INNER JOIN general  gs ON gs.codgeneral     = os.codgeneral
          INNER JOIN intrari  i  ON i.codintr         = gs.coddoc AND i.tipdoc = gs.tipdoc
        WHERE gg.coddoc = g.coddoc AND gg.tipdoc = g.tipdoc AND gg.semnificatie &lt;&gt; g.semnificatie
          AND i.subunitatea = '||getSUBUNITATE()::varchar||'
      )
    )'
    WHEN PKG_LIST_SELECTSCADENTAR_TranzCursFirma() THEN ''
    ELSE PKG_LIST_SELECTSCADENTAR_COND_SUBUNIT('t')
  END;

  IF PKG_LIST_SELECTSCADENTAR_CuTranzInCurs() THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(sInstmp||sSeltmp, aLISTID, 0);
  END IF;

  sSelTMP := '
  SELECT --TREZORERIE - PLATI IN AVANS, RETUR CEC
    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 = 310 THEN -1 ELSE 1 END valoare, Coalesce(g.tva,0) * CASE WHEN o.semnificatie = 310 THEN -1 ELSE 1 END tva,
    CASE WHEN ol.codobligpif IS NULL THEN o.valoare ELSE ol.rest END * CASE WHEN o.semnificatie = 310 THEN -1 ELSE 1 END restval,
    CASE WHEN ol.codobligpif IS NULL THEN Coalesce(o.dincaretva,0) ELSE Coalesce(ol.restsplittva,0) END * CASE WHEN o.semnificatie = 310 THEN -1 ELSE 1 END restsplittva,
    CASE WHEN ol.codobligpif IS NULL THEN Coalesce(g.tva,0) ELSE Coalesce(ol.resttva,0) END * CASE WHEN o.semnificatie = 310 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,'||getAnLunaLucru()::varchar||',o.semnificatie) cont, o.adaosdoc,
    Coalesce(g.moneda,0) Moneda, COALESCE(NullIf(g.curs,0), 1) curs,  d.obs, d.carnetdoc, d.seriedoc seriadoc, t.subunitatea,  COALESCE(NullIf(d.agent,0),t.agent) agent, d.codlocatie, d.Initializari,
    g.CodGeneral, g.exclusplata,
    Coalesce(rc.curs, COALESCE(NullIf(g.curs,0), 1)) curs,
    o.codcentru, t.userid,
    0 TVAMediu,
    0 TvaIncasare, Coalesce(o.splittva,0) SplitTVA, to_char(Coalesce(d.datadecont,o.termen,d.datadoc), ''IYYYIW'')::numeric
  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||'
    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;= '||getAnLunaLucru()::varchar||') x where x.nr=1
      GROUP BY x.CodGeneral
    ) rc ON rc.codgeneral = g.codgeneral
  WHERE o.semnificatie IN (310,430)
    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_COND_SUBUNIT('t')||
    PKG_LIST_BASE_UTILS_COND_USERID ('t')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('d.DataDoc');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInstmp||sSeltmp, aLISTID, 0);

  sSelTMP := '
  SELECT --NOTE CONTABILE LEGATE DE PARTENERI
    o.codobligpif, d.codnc, NULL coddoc1, g.tipdoc, o.codpart, ''NC'' doc, d.nrdoc, d.datadoc, '' '' nri, 0 blocat, o.termen,
    CASE WHEN o.icont in (4,12) THEN -1 ELSE 1 END*o.valoare , CASE WHEN o.icont in (4,12) THEN -1 ELSE 1 END*Coalesce(g.tva,0) tva,
    CASE WHEN o.icont in (4,12) THEN -1 ELSE 1 END*CASE WHEN ol.codobligpif IS NULL THEN o.valoare                ELSE ol.rest                     END restval,
    CASE WHEN o.icont in (4,12) THEN -1 ELSE 1 END*CASE WHEN ol.codobligpif IS NULL THEN Coalesce(o.dincaretva,0) ELSE Coalesce(ol.restsplittva,0) END restsplittva,
    CASE WHEN o.icont in (4,12) THEN -1 ELSE 1 END*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,'||getAnLunaLucru()::varchar||',o.semnificatie) cont, o.adaosdoc,
    Coalesce(g.moneda,0) Moneda, COALESCE(NullIf(g.curs,0), 1) curs, nc1.obs, d.carnetdoc, NULL seriadoc, d.subunitatea, nc1.agent, 0 codlocatie, 0 Initializari,
    g.CodGeneral, g.exclusplata,
    Coalesce(rc.curs, COALESCE(NullIf(g.curs,0), 1)) curs,
    o.codcentru, d.userid,
    0 TVAMediu,
    0 TvaIncasare, Coalesce(o.splittva,0) SplitTVA, to_char(Coalesce(o.termen,d.datadoc), ''IYYYIW'')::numeric
  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||'
    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;= '||getAnLunaLucru()::varchar||') x where x.nr=1
      GROUP BY x.CodGeneral
    ) rc ON rc.codgeneral = g.codgeneral
  WHERE o.icont IN (2,4,8,9,12,13,14,15,16,19,21,22'||sIcontS_F||')  -- 6 - facturi de incasat - 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_SELECTSCADENTAR_COND_SUBUNIT('d')||
    PKG_LIST_BASE_UTILS_COND_USERID('d');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInstmp||sSeltmp, aLISTID, 0);

  sSelTMP := '
  SELECT --COMPENSARI
    o.codobligpif, g.coddoc, NULL coddoc1, g.tipdoc, o.codpart, ''PV'' doc, d.nrdoc, d.datadoc, '' '' nri, 0 blocat, o.termen,
    o.valoare * CASE WHEN o.semnificatie = 1301 AND o.icont NOT IN (2) THEN -1 ELSE 1 END valoare, Coalesce(g.tva,0) * CASE WHEN o.semnificatie = 1301 AND o.icont NOT IN (2) THEN -1 ELSE 1 END tva,
    CASE WHEN ol.codobligpif IS NULL THEN o.valoare ELSE ol.rest END * CASE WHEN o.semnificatie = 1301 AND o.icont NOT IN (2) THEN -1 ELSE 1 END restval,
    CASE WHEN ol.codobligpif IS NULL THEN Coalesce(o.dincaretva,0) ELSE Coalesce(ol.restsplittva,0) END * CASE WHEN o.semnificatie = 1301 AND o.icont NOT IN (2) THEN -1 ELSE 1 END restsplittva,
    CASE WHEN ol.codobligpif IS NULL THEN Coalesce(g.tva,0) ELSE Coalesce(ol.resttva,0) END * CASE WHEN o.semnificatie = 1301 AND o.icont NOT IN (2) 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,'||getAnLunaLucru()::varchar||',o.semnificatie) cont, o.adaosdoc,
    Coalesce(g.moneda,0) Moneda, COALESCE(NullIf(g.curs,0), 1) curs,  d.obsd obs, d.carnetdoc, NULL seriadoc, d.subunitatea, d.agent, 0 codlocatie, 0 Initializari,
    g.CodGeneral, g.exclusplata,
    Coalesce(rc.curs, COALESCE(NullIf(g.curs,0), 1)) curs,
    o.codcentru, d.userid,
    0 TVAMediu,
    0 TvaIncasare, Coalesce(o.splittva,0) SplitTVA, to_char(Coalesce(o.termen,d.datadoc), ''IYYYIW'')::numeric
  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||'
    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;= '||getAnLunaLucru()::varchar||'
      ) x where x.nr=1
      GROUP BY x.CodGeneral
    ) rc ON rc.codgeneral = g.codgeneral
  WHERE o.semnificatie IN (1301,1351)
    AND o.icont IN (2,4,8,9,12,13,14,15'||sIcontS_F||') -- 6 - facturi de incasat - 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_SELECTSCADENTAR_COND_SUBUNIT('d')||
    PKG_LIST_BASE_UTILS_COND_USERID ('d')||
    PKG_LIST_SELECTSCADENTAR_FiltruData('d.DataDoc');

  PERFORM LIST_EXECUTE_IMMEDIATE(sInstmp||sSeltmp, aLISTID, 0);

  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_SCADENTARF WHERE ANSAPT IS NOT NULL ORDER BY ANSAPT
      ) a_pg
      ORDER BY ansapt
    ) B_PG;
  END IF;

  sInsTmp := 'INSERT INTO tmp_lst_scad_stins  (codstinspif, valoare, tva, dincaretva)
  SELECT codstinspif, SUM( valoare * semn) valoare, SUM(tva*semn) tva, SUM(dincaretva*semn) valoare
  FROM (
    SELECT
      s.codstinspif,
      Abs(s.valoare-CASE WHEN Coalesce(i.tiptva,0) = 2 AND o.semnificatie=110 THEN Coalesce(g.tva,0) ELSE 0 END) valoare,
      Abs(Coalesce(s.dincaretva,0)) dincaretva,
      CASE WHEN Coalesce(i.tiptva,0) = 2 AND o.semnificatie=110 THEN 0 ELSE Abs(Coalesce(g.tva,0)) END Tva,
      CASE
        -- la resturi nesemnificative nu poate fi determinat semnul in functie de valoare initiala a obligatiei (posibil sa se fi platit mai mult si atunci e semn invers)
        WHEN OS.SEMNIFICATIE = 1300 AND O.SEMNIFICATIE = 100 AND Coalesce(s.valoare, 0)    &lt;&gt; 0 THEN SIGN(s.valoare)
        WHEN OS.SEMNIFICATIE = 1300 AND O.SEMNIFICATIE = 100 AND Coalesce(s.dincaretva, 0) &lt;&gt; 0 THEN SIGN(s.dincaretva)
        ELSE
          CASE WHEN Coalesce(o.valoare,0) &lt; 0 THEN -1 ELSE 1 END *
          CASE
            WHEN OS.SEMNIFICATIE = 700                                                                                             THEN -1
            WHEN OS.SEMNIFICATIE = 1300 AND O.ICONT  = 2       AND      O.SEMNIFICATIE IN (     1200      ) AND O.ICONT = 2        THEN  1
            WHEN OS.SEMNIFICATIE = 1300 AND O.ICONT  = 2       AND NOT (O.SEMNIFICATIE IN (130,       1201)                      ) THEN -1
            WHEN OS.SEMNIFICATIE = 1300 AND OS.ICONT IN (4,12) AND NOT (O.SEMNIFICATIE IN (110, 1200, 1201) AND O.ICONT IN (4,12)) THEN -1
            ELSE 1
          END *
          CASE
            WHEN O.SEMNIFICATIE IN (1200, 1201) AND     O.ICONT IN ( 4,12)      THEN -1
            WHEN O.SEMNIFICATIE = 1301          AND NOT O.ICONT IN ( 2 )        THEN -1
            WHEN O.SEMNIFICATIE = 1351          AND     O.ICONT IN ( 2 )        THEN -1
            WHEN O.SEMNIFICATIE IN (110,310)                                    THEN -1
            WHEN O.SEMNIFICATIE = 430           AND NOT O.ICONT IN (12, 13, 14) THEN -1
            ELSE 1
          END
      END semn
    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'||
      sJoinFiltru||'
      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 i.tipdoc = g.tipdoc --AND os.semnificatie IN (111)
    WHERE COALESCE(i.an * 12 + i.luna,t1.an * 12 + t1.luna,c.an * 12 + c.luna)'||sFiltruLuna||
      PKG_LIST_SELECTSCADENTAR_FiltruData('i.DataDoc,t1.DataDoc,c.DataDoc')||'
  ) a_pg GROUP BY codstinspif';

  TRUNCATE TABLE tmp_lst_scad_stins;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsTmp, aListID, 0);

  sInsTmp := 'INSERT INTO tmp_lst_scad_sertar  (codobligpif, decont, doc, ser, nrdoc, datadoc, valoare, datadecont, valasoc)
    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::varchar||''/''||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;= '||getAnLunaLucru()::varchar||'
      LEFT JOIN obligpif o  ON o.codobligpif = ns1.codobligpif
    WHERE t1.codtrezor IS NULL
    GROUP BY ns1.codobligpif';

  TRUNCATE TABLE tmp_lst_scad_sertar;
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsTmp, aListID, 0);
  PERFORM PKG_LIST_BASE_UTILS_Make_idx_tmp_lst_scad();

  perform set_config('PKG_LIST_BASE_SCADENTARF.sConv',    sConv,    false);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_scadentarleasing_processlist</obj_name>
  <obj_hashval>e394e7b7c6d47025a38d9bd1afa6b13a</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_scadentarleasing_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 := '';
  sDoc           varchar := '';
  sCodDoc       varchar := '';
  sTipContr     varchar := '';
  sCondDataC     varchar := '';
  sCondDataI     varchar := '';
  sCondDataC2   varchar := '';
  sCondDataC0   varchar := '';
  sCondCurs     varchar := '';
  vDataAux       date;
  gSuplCols     VARCHAR := 'contract c, contract2 c2, npart p, nmonede mc';
   gUserFields   VARCHAR := '';
  gUserAlias     VARCHAR := '';
  gNullAlias     VARCHAR := '';
  gSuplJoins     VARCHAR := '';
BEGIN
  --Adina 10 septembrie 2020
  call pkg_list_struct_startsuplcols();
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_SCADENTARLEASING.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  CASE  current_setting('PKG_LIST_SELMOMENT.vTip', true)::numeric
    WHEN 2 THEN
      vDataAux     := to_date(current_setting('PKG_LIST_SELMOMENT.vDataRef', true),'dd.mm.yyyy');
      sCondDataI   := ' AND I.DATADOC   &lt;= To_Date(''' || coalesce(To_Char(vDataAux,'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
      sCondDataC   := ' AND C.DATASTART &lt;= To_Date(''' || coalesce(To_Char(vDataAux,'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
      sCondDataC2 := ' AND coalesce(C2.DATADOC,C2.DATA) &lt;= To_Date(''' || coalesce(To_Char(vDataAux,'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
      sCondDataC0 := ' AND C0.DATADOC &lt;= To_Date(''' || coalesce(To_Char(vDataAux,'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
      sCondCurs   := ' AND C0.DATA    &lt;= To_Date(''' || coalesce(To_Char(vDataAux,'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
    WHEN 1 THEN
      vDataAux     := Last_Day(To_Date(COALESCE(getANLUCRU()::varchar,'') || '.' || coalesce(getLUNALUCRU()::varchar,''), 'YYYY.MM'));
      sCondDataI   := ' AND I.AN * 12 + I.LUNA &lt;= ' || coalesce(getAnLunaLucru()::varchar,'');
      sCondDataC   := ' AND C.DATASTART &lt;= To_Date(''' || coalesce(To_Char(vDataAux,'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
      sCondDataC2 := ' AND coalesce(C2.DATADOC,C2.DATA) &lt;= To_Date(''' || coalesce(To_Char(vDataAux,'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
      sCondDataC0 := ' AND C0.DATADOC &lt;= To_Date('''  || coalesce(To_Char(vDataAux,'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
      sCondCurs   := ' AND C0.DATA    &lt;= To_Date('''  || coalesce(To_Char(vDataAux,'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
    ELSE NULL;
  END CASE;

  IF  aLISTID = 256 THEN
    sDoc       := 'intrari';
    sCodDoc   := 'codintr';
    sTipContr := '25';
  ELSE
    sDoc       := 'iesiri';
    sCodDoc   := 'codies';
    sTipContr := '25';
  END IF;

  sInsert := 'INSERT INTO ' || tmpName || '(
    NAV_CodDoc, NAV_TipDoc, CONTRNR, CONTRDATA, CONTRDATAI, CONTRDATAS, CONTRMoneda,
    CONTRCurs,
    FACTCurs,
    CFCurs,
    CF_AS,
    ACTIV, CONTABILIZAT, STORNAT,
    PART, FACTData,
    ART,
    CONTRRata, CONTRDob, CONTRAsig,
    NrFact, DataFact,
    FACTRata, FACTDob, FACTAsig,
    RESTRata, RESTDob, RESTAsig ' || gUserFields || ')';

  sSelect := '
  WITH x AS (
    SELECT
      c.codcontract,
      MIN(
        CASE
          WHEN i.' || sCodDoc || ' IS NOT NULL ' || sCondDataI  || ' THEN 1
          WHEN coalesce(c2.NrDoc,0) &lt;&gt; 0 '       || sCondDataC2 || ' THEN 1
          ELSE 0
        END) Facturat,
      CASE
        WHEN (SELECT COUNT(1) FROM CONTRACT0 c0 WHERE c0.codcontract = c.codcontract AND c0.tiplinie = 1' || sCondDataC0 || ') &gt; 0 THEN ''DA''
        ELSE ''NU''
      END Contabilizat,
      CASE
        WHEN (SELECT COUNT(1) FROM CONTRACT0 c0 WHERE c0.codcontract = c.codcontract AND c0.tiplinie = 3' || sCondDataC0 || ') &gt; 0 THEN ''DA''
        ELSE ''NU''
      END Stornat
    FROM contract c
      INNER JOIN contract2 c2 ON c2.codcontract = c.codcontract
      LEFT JOIN ' || sDoc || ' i ON i.' || sCodDoc || ' = c2.coddoc AND i.tipdoc = c2.tipdoc
    WHERE c.tipdoc = ' || sTipContr || sCondDataC || ' AND c.operat = 1 AND c.anulat = 0 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('C',NULL,NULL,NULL),'') || '
    GROUP BY c.codcontract
  )
  SELECT
    c.codcontract, c.tipdoc, c.NrDoc, c.Datadoc, c.DataStart, c.DataStop, mc.den_moneda,
    CASE
      WHEN mc.codmoneda = 0 THEN 1
      ELSE
        COALESCE(
          ( SELECT Max(curs)
            FROM (SELECT c0.curs, dense_rank() over(ORDER BY c0.data desc) NR
                  FROM contract0 c0
                  WHERE c0.codcontract = x.codcontract AND c0.tiplinie = 2' || sCondCurs || ' ) aa
            WHERE NR=1
          ),
          ( SELECT Max(oldcurs)
            FROM (SELECT c0.oldcurs, dense_rank() over(ORDER BY c0.data asc) NR
                  FROM contract0 c0
                  WHERE c0.codcontract = x.codcontract AND c0.tiplinie = 2 ) bb
            WHERE NR=1
          ),
          Coalesce(NULLIF(coalesce(c.curs,0),0),1)
        )
    END curscontr ,
    CASE
      WHEN mc.codmoneda = 0 THEN 1
      ELSE
        COALESCE(
          ( SELECT Max(curs)
            FROM (SELECT c0.curs, dense_rank() over(ORDER BY c0.data desc) NR
                  FROM contract0 c0
                  WHERE c0.codcontract = x.codcontract AND c0.tiplinie = 2 AND c0.data &lt; c2.data' || sCondCurs || ' ) cc
            WHERE NR=1
          ),
          ( SELECT Max(oldcurs)
            FROM (SELECT c0.oldcurs, dense_rank() over(ORDER BY c0.data asc) NR
                  FROM contract0 c0
                  WHERE c0.codcontract = x.codcontract AND c0.tiplinie = 2 ) dd
            WHERE NR=1
          ),
          Coalesce(NULLIF(coalesce(c.curs,0),0),1)
        )
    END cursfact ,
    coalesce(cfc.valoare, 1) cfcurs,
    TO_CHAR(c2.data+coalesce(p.scadentac,0)::integer,''IYYY.IW'') CF_AS,
    (case when c.activ=1 then ''DA'' else ''NU'' end), x.Contabilizat, x.Stornat,
    p.den_part, c2.data,
    ( SELECT string_agg(DISTINCT o.denumire ,'''||COALESCE(current_setting('PKG_GLOBALS.SEP', true)::varchar,'|')||'''  ORDER BY o.denumire)
      FROM contract1 c1 INNER JOIN nartobj o ON o.codobiect = c1.codobiect
      WHERE c1.codcontract = c.codcontract ),
    coalesce(c2.suma,0) suma, coalesce(c2.dobanda,0) dob, coalesce(c2.asigurare,0) asig,
    CASE
      WHEN i.' || sCodDoc || ' IS NOT NULL ' || sCondDataI  || ' THEN i.nrdoc
      WHEN coalesce(c2.NrDoc,0) &lt;&gt; 0 '       || sCondDataC2 || ' THEN c2.NrDoc
      ELSE NULL
    END NrFact,
    CASE
      WHEN i.' || sCodDoc || ' IS NOT NULL ' || sCondDataI  || ' THEN I.DATADOC
      WHEN coalesce(c2.NrDoc,0) &lt;&gt; 0 '       || sCondDataC2 || ' THEN coalesce(C2.DATADOC,C2.DATA)
      ELSE NULL
    END DataFact,
    CASE
      WHEN i.' || sCodDoc || ' IS NOT NULL ' || sCondDataI  || ' THEN coalesce(c2.suma,0)
      WHEN coalesce(c2.NrDoc,0) &lt;&gt; 0 '       || sCondDataC2 || ' THEN coalesce(c2.suma,0)
      ELSE 0
    END FactRata,
    CASE
      WHEN i.' || sCodDoc || ' IS NOT NULL ' || sCondDataI  || ' THEN coalesce(c2.dobanda,0)
      WHEN coalesce(c2.NrDoc,0) &lt;&gt; 0 '       || sCondDataC2 || ' THEN coalesce(c2.dobanda,0)
      ELSE 0
    END FactDob,
    CASE
      WHEN i.' || sCodDoc || ' IS NOT NULL ' || sCondDataI  || ' THEN coalesce(c2.asigurare,0)
      WHEN coalesce(c2.NrDoc,0) &lt;&gt; 0 '       || sCondDataC2 || ' THEN coalesce(c2.asigurare,0)
      ELSE 0
    END FactAsig,
    CASE
      WHEN i.' || sCodDoc || ' IS NOT NULL ' || sCondDataI  || ' THEN 0
      WHEN coalesce(c2.NrDoc,0) &lt;&gt; 0 '       || sCondDataC2 || ' THEN 0
      ELSE coalesce(c2.suma,0)
    END RESTRata,
    CASE
      WHEN i.' || sCodDoc || ' IS NOT NULL ' || sCondDataI  || ' THEN 0
      WHEN coalesce(c2.NrDoc,0) &lt;&gt; 0 '       || sCondDataC2 || ' THEN 0
      ELSE coalesce(c2.dobanda,0)
    END RESTDob,
    CASE
      WHEN i.' || sCodDoc || ' IS NOT NULL ' || sCondDataI  || ' THEN 0
      WHEN coalesce(c2.NrDoc,0) &lt;&gt; 0 '       || sCondDataC2 || ' THEN 0
      ELSE coalesce(c2.asigurare,0)
    END RESTAsig ' || gUserAlias || '
  FROM x
    INNER JOIN contract  c  ON c.codcontract  = x.codcontract
    INNER JOIN contract2 c2 ON c2.codcontract = c.codcontract
    LEFT  JOIN ' || sDoc || ' i ON i.' || sCodDoc || ' = c2.coddoc AND i.tipdoc = c2.tipdoc
    LEFT  JOIN npart   p  ON p.codpart    = c.partener
    LEFT  JOIN nmonede mc ON mc.codmoneda = coalesce(c.moneda,0)
    LEFT  JOIN TMP_LST_CURS cfc ON cfc.codmoneda = coalesce(c.moneda,0)' || gSuplJoins || '
  WHERE x.Facturat = 0';

  sUpdate := 'UPDATE ' || tmpName || '
  SET
    RESTRataLei = FACTCurs * RESTRata,
    RESTDobLei  = FACTCurs * RESTDob ,
    RESTAsigLei = FACTCurs * RESTAsig,
    CFRestRata  = CFCurs   * RESTRata,
    CFRestDob   = CFCurs   * RESTDob,
    CFRestAsig  = CFCurs   * RESTAsig';

  PERFORM PKG_LIST_BASE_UTILS_UMPLE_TMP_LST_CURS(NULL,NULL,NULL);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);
  PERFORM LIST_EXECUTE_IMMEDIATE(sUpdate, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_serii_setjoinuri</obj_name>
  <obj_hashval>9849f3f877ed18cab0fb0c959038aab8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_serii_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 17 august 2020
  PERFORM Pkg_List_Struct_SetTableSpec(current_setting('PKG_LIST_BASE_SERII.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitbonretail_getgnullalias</obj_name>
  <obj_hashval>139a151e6931f98ae74f559e61be6a19</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitbonretail_getgnullalias(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_SITBONRETAIL.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_sitbonretail_getgsuplcols</obj_name>
  <obj_hashval>8ab8c99089ea6eabd59d596a176b4320</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitbonretail_getgsuplcols(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_SITBONRETAIL.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_sitbonretail_getgsupljoins</obj_name>
  <obj_hashval>4448a53921c2914a50686d9ab03b01d3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitbonretail_getgsupljoins(INOUT wme_result character varying, INOUT fakeparam numeric)
 RETURNS record
 LANGUAGE plpgsql
AS $function$
begin
BEGIN
  WME_Result := current_setting('PKG_LIST_BASE_SITBONRETAIL.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_sitbonretailsint_setjoinuri</obj_name>
  <obj_hashval>0fa6e447de8f9c428f3234f670bb7fa6</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitbonretailsint_setjoinuri()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 08.06.2021
  PERFORM pkg_list_struct_SetTableSpec(current_setting('PKG_LIST_BASE_SITBONRETAILSINT.gSuplCols', true));
  PERFORM pkg_list_struct_AdunaColoanele();
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitconsumprod_processlist</obj_name>
  <obj_hashval>a4e1abc42cbf3125e9335b8459c46d49</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitconsumprod_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar := '';
  sInsTMP     varchar := '';
  sSelect     varchar := '';
  sCondGest   varchar := '';
  sJoinAux    varchar := '';
  vCuStoc     BOOLEAN;
  vCampStoc   varchar := '';
  sPer        varchar := ' BETWEEN to_date(''' || coalesce(current_setting('PKG_LIST_SELECTGESTPER.vdatadocini', TRUE), '') || ''', ''dd.mm.yyyy'')
                               and to_date(''' || coalesce(current_setting('PKG_LIST_SELECTGESTPER.vdatadocfin', TRUE), '') || ''', ''dd.mm.yyyy'')';
  sPerCmd     varchar := ' BETWEEN to_date(''' || coalesce(current_setting('PKG_LIST_SELECTGESTPER.vDataIni'   , TRUE), '') || ''', ''dd.mm.yyyy'')
                               and to_date(''' || coalesce(current_setting('PKG_LIST_SELECTGESTPER.vDataFin'   , TRUE), '') || ''', ''dd.mm.yyyy'')';
  gSuplCols   varchar := 'comanda c, comanda1 c1, num1 umc, ngest g, nartobj objmat, nart art, num umm, nartobj objret, comanda1 ccli1, comanda ccli, npart p, nirstoc ns,' || 'cmdprodmat prod, formatii f, nclasea cls, ncont contp, prodcomp pc, cmdprodmat mat, cmdprodman man';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';

  vCod        NUMERIC := CASE WHEN length(current_setting('PKG_LIST_SELECTGESTPER.vCod', TRUE))=0 THEN 0
                              ELSE COALESCE(current_setting('PKG_LIST_SELECTGESTPER.vCod', TRUE)::NUMERIC,0)
                         END;
  sSeriiField VARCHAR(50)  := '';
  sSeriiIes VARCHAR(1000)  := '';
  sSeriiIntr VARCHAR(1000) := '';
  sSeriiNull VARCHAR(50)   := '';
BEGIN
  --Florin 01.09.2022 - fixat 55420
  --Florin 31.08.2022 - fixat 55401
  --Florin 30.08.2022 - sinc. Oracle
  --Bogdan 26.04.2022 54008 Lista Urmarire - Situatia comenzilor interne -&gt; afisare observatii linie document
  --Florin 21.03.2022 - sinc. Oracle
  --Florin 08.09.2021 - sinc.Oracle (07.09.2021)
  --Adina 07.06.2021 - sinc.Oracle din 03.06.2021
  --Adina 08.04.2021 -alstart,alstop
  --Adina 12.01.2021 tichet 42147 - modificat insertul in tabela TMP_CMD (sInsTMP)
  --Adina 11.01.2021 tichet 42106 - pus bExtra1, bIndiferent in loc de vExtra1, vIndiferent
  --Adina 11.01.2021 tichet 42105 - corectat format data pt.coloana Explicatii
  --Adina 06.01.2021 tichet 41960 - add param.vCod (si inlocuit la liniile 71 si 75) si scos comentariile de la liniile 541 si 592 (cele cu Perform)
  --Florin 14.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, 'NARTOBJATR', 'OATRMAT', 'OATRMAT.CODOBIECT = OBJMAT.CODOBIECT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXTRET', 'OEXTRET.CODOBIECT = OBJRET.CODOBIECT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATRRET', 'OATRRET.CODOBIECT = OBJRET.CODOBIECT'    ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDI'   , 'CV'     , 'CV.CODCOMANDA     = C.CODCOMANDA'        ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDI1'  , 'CV1'    , 'CV1.CODCOMANDA1   = C1.CODCOMANDA1'      ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDC'   , 'CCV'    , 'CCV.CODCOMANDA    = CCLI.CODCOMANDA'     ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'COMANDC1'  , 'CCV1'   , 'CCV1.CODCOMANDA1  = CCLI1.CODCOMANDA1'   ,NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'CENTRECOST', 'CCOST'  , 'CCOST.CODCENTRU   = Coalesce(C1.CODCENTRU,0)');
  call pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_SITCONSUMPROD.gSuplCols',gSuplCols,false);

  CALL PRC_AL_CHECK('ioart1');
  CALL PRC_AL_CHECK('tarifeman1');
  sCondGest := '';

  sSeriiField := '';
  sSeriiIes   := '';
  sSeriiIntr  := '';
  if current_setting('PKG_LIST_SELECTGESTPER.bAduSerii', TRUE) then
    sSeriiField := ',Serii';
    sSeriiIes   := ',(select string_agg(ser.serie||''(''||to_char(l1.cant)||'')'', '''') from nirser nse inner join nserii ser on ser.codserie = nse.codserie where nse.codnirser = l1.codnirser)';
    sSeriiIntr  := ',(select string_agg(ser.serie||''(''||to_char(ns.cantnir)||'')'', '''') from nirser nse inner join nserii ser on ser.codserie = nse.codserie where nse.codnirstoc = ns.codnirstoc)';
    sSeriiNull  := ', null';
  end if;

  IF NOT current_setting('PKG_LIST_SELECTGESTPER.vAllGest', TRUE)::boolean THEN
    sCondGest := '
        AND c.codgest::varchar IN (SELECT valoare FROM tmp_manevra_liste WHERE upper(filtru) = ''CODGEST'') ';
  END IF;

  vCuStoc := current_setting('PKG_LIST_SELECTGESTPER.bExtra1', TRUE)::boolean;

  DELETE FROM comanda1_man;

  --IF current_setting('PKG_LIST_SELECTGESTPER.vCod', TRUE)::numeric &gt; 0 THEN
  IF vCod &gt; 0 THEN
    sInsTMP := 'INSERT INTO comanda1_man (codcomanda1)
        select c1.codcomanda1
        from comanda1 c1 inner join comanda c on c.codcomanda = c1.codcomanda
        WHERE c1.codcomanda1 = ' || vCod;   --coalesce(current_setting('PKG_LIST_SELECTGESTPER.vCod', TRUE)::NUMERIC, 0);
  ELSE
    sInsTMP := 'INSERT INTO comanda1_man (codcomanda1)
        select c1.codcomanda1
        from comanda1 c1 inner join comanda c on c.codcomanda = c1.codcomanda
        WHERE c.tipdoc = 53 AND c.operat = 1 AND c.anulat = 0
          AND c.datadoc' || coalesce(sPerCmd,'') || '
          AND c1.cantacceptat &gt; 0' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('c',NULL,NULL,NULL),'') || coalesce(sCondGest,'');
  END IF;

  PERFORM LIST_EXECUTE_IMMEDIATE(sInsTMP, aListID, aListVer);

  DELETE FROM tmp_cmd WHERE userid = current_setting('PKG_GLOBALS.USERID', true)::numeric;

  sInsTMP := 'INSERT INTO TMP_CMD (CODOBIECT, RESTA, USERID, TIP)
  SELECT CODOBIECT, RESTA, ' || coalesce(current_setting('PKG_GLOBALS.USERID', true)::numeric,0) || ' USERID, ''STOC''
  FROM
  (
      SELECT NS.CODOBIECT,SUM(NS.REST) RESTA
      FROM NIRSTOC NS
           INNER JOIN NIR        ON NS.CODNIR = NIR.CODNIR
           INNER JOIN NGEST  NG  ON NIR.GEST  = NG.CODGEST
           LEFT  JOIN IOART1 IOA ON IOA.CODIOART = NS.CODIOART AND ' || getanlunalucru() || ' BETWEEN IOA.ALStart and IOA.ALStop
      WHERE NS.REST &gt; 0 AND IOA.MG &lt;&gt; 5 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('NG', 'CODSUBUNIT',NULL,NULL)::varchar ,'') || '
      GROUP BY NS.CODOBIECT
  ) AA ';

  IF vCuStoc THEN
    PERFORM LIST_EXECUTE_IMMEDIATE(sInsTMP, aListID, aListVer);
    vCampStoc := ', Coalesce(stoc.resta,0) stoc ';
    sJoinAux := coalesce(sJoinAux,'') || '
        LEFT JOIN TMP_CMD STOC ON stoc.codobiect = objmat.codobiect and stoc.tip = ''STOC'' and stoc.userid = ' || coalesce(current_setting('PKG_GLOBALS.USERID', true)::numeric,0);
  ELSE
    vCampStoc := ',0 stoc ';
  END IF;

  sInsTMP := 'INSERT INTO TMP_CMD (CODOBIECT, RESTA, USERID, TIP)
      SELECT R.CODCMDPRODMAT,SUM(R.REST) RESTA, ' || coalesce(current_setting('PKG_GLOBALS.USERID', true)::numeric,0) || ', ''REZ''
      FROM COMANDA1_MAN C1M
           INNER JOIN REZERVATS  R   ON R.CODCOMANDA1     = C1M.CODCOMANDA1
           INNER JOIN CMDPRODMAT MAT ON MAT.CODCMDPRODMAT = R.CODCMDPRODMAT
      GROUP BY R.CODCMDPRODMAT ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsTMP, aListID, aListVer);

  sInsert := 'INSERT INTO ' || TMPNAME || '(
        NAV_CodDoc, NAV_TipDoc, Explicatii,
        ValConsum, ValPredare,
        DataComInt, TermenExec, NrComProd, Client,
        NrComCli, DataComCli, TermenCli, ValCmdInt,
        DENUMIRE, SectiePred, ObsComInt, reteta,
        Cant, CantPredata, UM,
        Tip, ObsDoc, ContPredare, ContConsum,
        CantRez, ObsDet, Stoc ' || sSeriiField || gUserFields || ')';
  sSelect := '
      SELECT
        c.codcomanda NAV_CodDoc, c.tipdoc NAV_TipDoc,
        coalesce(I.PrefixDoc,'''')||'' ''||coalesce(I.NrDoc::varchar,'''')||''/''||to_char(I.DataDoc,''dd.mm.yyyy'') Explicatii,
        L1.Cant * (NS.PRET - COALESCE(NS.ADAOS,0)) ValConsum, 0 ValPredare,
        c.datadoc DataComInt, c1.termen TermenExec, c.nrdoc NrComProd, p.den_part Client,
        ccli.nrdoc NrComCli, ccli.datadoc DataComCli, ccli1.termen TermenCli, c.valoare ValCmdInt,
        objmat.DENUMIRE, g.den_gest SectiePred, c.obs ObsComInt, objret.denumire reteta,
        mat.cant, L1.CANT cantpredata, case when mat.tip = 0 then UMC.Den_UM1 else UMM.Den_um end um,
        ''CONSUM'' Tip, I.Obs ObsDoc, '' '' ContPredare, CONTP.Simbol ContConsum,
        Coalesce(REZ.RESTA,0) CantRez, I1.Obs ObsDet ' || coalesce(vCampStoc,'') || sSeriiIes || gUserAlias || '
      FROM comanda1_man c1m
        INNER JOIN comanda1          c1 ON c1m.codcomanda1 = c1.codcomanda1
        inner join cmdprodmat       mat on mat.codcomanda1 = c1m.codcomanda1
        INNER JOIN CMDPRODMAT      PROD ON C1.CODCOMANDA1  = PROD.CODCOMANDA1 AND Coalesce(PROD.TIP,0) = 0
        INNER JOIN NUM1             UMC ON UMC.codum1      = c1.UMSEC
        INNER JOIN comanda            c ON c1.codcomanda   = c.codcomanda
        INNER JOIN ngest              g ON c.codgest       = g.codgest
        INNER JOIN IESPRODLINK     LIES on LIES.CodCmdProdMat = mat.codcmdprodmat
        INNER JOIN IESIRI1           I1 ON LIES.CodIes1  = I1.CodIes1
        INNER JOIN IESIRI             I ON I1.CodIes     = I.CodIes
        INNER JOIN livr               L ON L.CodIes      = I.CodIes
        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 IOART1         IO1 ON IO1.CODIOART1 = PKG_CONFIGART.GETCODCARACTLUNA(NS.CODIOART, I.AN, I.LUNA)
        --INNER JOIN NCONT        CONTP ON CONTP.CODCONT = IO1.CONT
        LEFT JOIN IOART1            IO1 ON IO1.CODIOART  = NS.CODIOART AND I.AN*12+I.LUNA BETWEEN IO1.ALSTART AND IO1.ALSTOP
        LEFT JOIN NCONT           CONTP ON CONTP.CODCONT = IO1.CONT
        INNER JOIN NARTOBJ       OBJmat ON mat.codobiect = objmat.codobiect
        INNER JOIN NART             ART ON objmat.codarticol = art.codarticol
        INNER JOIN NUM              UMM ON UMM.codum      = art.UM
        INNER JOIN NARTOBJ       ObjRet ON c1.codobiect   = objret.codobiect
        left  join prodcomp          pc on pc.codprodcomp = c1.codreteta
        left  join nclasea          cls on cls.codclasea  = art.clasa
        LEFT  JOIN cmdlink         cmdl ON c1.codcomanda1 = cmdl.codcomanda1
        LEFT  JOIN comanda1       CCli1 ON cmdl.codliniecomanda = ccli1.codcomanda1
        LEFT  JOIN comanda         CCli ON ccli.codcomanda = ccli1.codcomanda
        LEFT  JOIN formatii           f ON c.codformatie   = f.codformatie
        LEFT  JOIN npart              p ON p.codpart       = ccli.partener
        left  join cmdprodman       man on man.codcmdprodman = c1.codcomanda1 - c1.codcomanda1
        LEFT  JOIN TMP_CMD          REZ ON REZ.CODOBIECT   = MAT.CODCMDPRODMAT AND REZ.TIP = ''REZ'' AND REZ.USERID = ' || coalesce(current_setting('PKG_GLOBALS.USERID', true)::numeric,0) || gSuplJoins || coalesce(sJoinAux,'');

  IF NOT current_setting('pkg_list_selectgestper.bIndiferent', TRUE)::boolean THEN
    sSelect := coalesce(sSelect,'') || '
        WHERE I.DataDoc' || coalesce(sPer,'');
  END IF;

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

  sSelect := '
      SELECT
        c.codcomanda NAV_CodDoc, c.tipdoc NAV_TipDoc, ''Fara consum'' Explicatii,
        0 ValConsum, 0 ValPredare,
        c.datadoc DataComInt, c1.termen TermenExec, c.nrdoc NrComProd, p.den_part Client,
        ccli.nrdoc NrComCli, ccli.datadoc DataComCli, ccli1.termen TermenCli, c.valoare ValCmdInt,
        objmat.DENUMIRE, g.den_gest SectiePred, c.obs ObsComInt, objret.denumire reteta,
        mat.rest CANT, 0 cantpredata, case when mat.tip = 0 then UMC.Den_UM1 else UMM.Den_um end um,
        ''FARA CONSUM'' Tip, '' '' ObsDoc, '' '' ContPredare, '' '' ContConsum,
        Coalesce(REZ.RESTA,0) CantRez, '' '' ObsDet ' || coalesce(vCampStoc,'') || sSeriiNull || gUserAlias || '
      FROM comanda1_man c1m
        INNER JOIN comanda1        c1 ON c1m.codcomanda1 = c1.codcomanda1
        inner join cmdprodmat     mat ON c1m.codcomanda1 = mat.codcomanda1
        INNER JOIN CMDPRODMAT    PROD ON C1.CODCOMANDA1  = PROD.CODCOMANDA1 AND Coalesce(PROD.TIP,0) = 0
        INNER JOIN NUM1           UMC ON UMC.codum1      = c1.UMSEC
        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           ART ON objmat.codarticol = art.codarticol
        INNER JOIN NUM            UMM ON UMM.codum      = art.UM
        INNER JOIN NARTOBJ     ObjRet ON c1.codobiect   = objret.codobiect
        left  join prodcomp        pc ON pc.codprodcomp = c1.codreteta
        left  join nclasea        cls ON cls.codclasea  = art.clasa
        LEFT  JOIN NIRSTOC         NS ON NS.CODNIRSTOC  = MAT.TIP - 1
        LEFT  JOIN IESPRODLINK   LIES on LIES.CodCmdProdMat   = mat.codcmdprodmat
        LEFT  JOIN cmdlink       cmdl ON c1.codcomanda1       = cmdl.codcomanda1
        LEFT  JOIN comanda1     CCli1 ON cmdl.codliniecomanda = ccli1.codcomanda1
        LEFT  JOIN comanda       CCli ON ccli.codcomanda = ccli1.codcomanda
        LEFT  JOIN formatii         f ON c.codformatie   = f.codformatie
        LEFT  JOIN npart            p ON p.codpart       = ccli.partener
        left  join cmdprodman     man on man.codcmdprodman = c1.codcomanda1 - c1.codcomanda1
        LEFT  JOIN TMP_CMD        REZ ON REZ.CODOBIECT   = MAT.CODCMDPRODMAT AND REZ.TIP = ''REZ'' AND REZ.USERID = ' || coalesce(current_setting('PKG_GLOBALS.USERID', true)::numeric,0) || gSuplJoins || coalesce(sJoinAux,'') || '
      WHERE mat.tip = 1 AND Coalesce(LIES.CodIes1,0) = 0 and mat.rest = mat.cant and Coalesce(ART.TIPARTICOL,''0'') = ''0''';

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

  sSelect := '
      SELECT
        c.codcomanda NAV_CodDoc, c.tipdoc NAV_TipDoc, SERV.FACT Explicatii,
        Coalesce(SERV.VALOARE,0) ValConsum, 0 ValPredare,
        c.datadoc DataComInt, c1.termen TermenExec, c.nrdoc NrComProd,
        p.den_part Client, ccli.nrdoc NrComCli, ccli.datadoc DataComCli, ccli1.termen TermenCli, c.valoare ValCmdInt,
        objmat.DENUMIRE, g.den_gest SectiePred, c.obs ObsComInt, objret.denumire  reteta,
        mat.rest Cant, Coalesce(SERV.CANT,0) cantpredata, case when mat.tip = 0 then UMC.Den_UM1 else UMM.Den_um end um,
        ''SERVICII'' Tip, '' '' ObsDoc, '' '' ContPredare, '' '' ContConsum,
        Coalesce(REZ.RESTA,0) CantRez, '' '' ObsDet ' || coalesce(vCampStoc,'') || sSeriiNull || gUserAlias || '
      FROM comanda1_man c1m
        INNER JOIN comanda1        c1 ON c1m.codcomanda1 = c1.codcomanda1
        inner join cmdprodmat     mat ON c1m.codcomanda1 = mat.codcomanda1
        INNER JOIN CMDPRODMAT    PROD ON C1.CODCOMANDA1  = PROD.CODCOMANDA1 AND Coalesce(PROD.TIP,0) = 0
        INNER JOIN NUM1           UMC ON UMC.codum1      = c1.UMSEC
        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           ART ON objmat.codarticol = art.codarticol
        INNER JOIN NUM            UMM ON UMM.codum      = art.UM
        INNER JOIN NARTOBJ     ObjRet ON c1.codobiect   = objret.codobiect
        left  join prodcomp        pc on pc.codprodcomp = c1.codreteta
        left  join nclasea        cls on cls.codclasea  = art.clasa
        LEFT  JOIN NIRSTOC         NS ON NS.CODNIRSTOC  = MAT.TIP - 1
        LEFT  JOIN IESPRODLINK   LIES on LIES.CodCmdProdMat   = mat.codcmdprodmat
        LEFT  JOIN cmdlink       cmdl ON c1.codcomanda1       = cmdl.codcomanda1
        LEFT  JOIN comanda1     CCli1 ON cmdl.codliniecomanda = ccli1.codcomanda1
        LEFT  JOIN comanda       CCli ON ccli.codcomanda = ccli1.codcomanda
        LEFT  JOIN formatii         f ON c.codformatie   = f.codformatie
        LEFT  JOIN npart            p ON p.codpart       = ccli.partener
        left  join cmdprodman     man on man.codcmdprodman = c1.codcomanda1 - c1.codcomanda1
        LEFT  JOIN (
          SELECT INTR1.CODCMDINT1 CODCOMANDA1, INTR1.CODOBIECT, SUM(INTR1.CANT) CANT, SUM(INTR1.CANT * INTR1.PU) VALOARE, string_agg(INTR.NRDOC||''/''||TO_CHAR(INTR.DATADOC,''DD.MM.YYYY''), '''') FACT
          FROM INTRARI1 INTR1
            INNER JOIN NARTOBJ OBJ  ON INTR1.CODOBIECT = OBJ.CODOBIECT
            INNER JOIN NART    ART  ON ART.CODARTICOL  = OBJ.CODARTICOL
            INNER JOIN INTRARI INTR ON INTR.CODINTR    = INTR1.CODINTR
          WHERE Coalesce(ART.TIPARTICOL,''0'') = ''1'' AND Coalesce(INTR.ANULAT,0) = 0 AND INTR.OPERAT = 1
          GROUP BY INTR1.CODCMDINT1, INTR1.CODOBIECT
        ) SERV ON SERV.CODCOMANDA1 = C1.CODCOMANDA1 AND SERV.CODOBIECT = MAT.CODOBIECT
        LEFT  JOIN TMP_CMD        REZ ON REZ.CODOBIECT = MAT.CODCMDPRODMAT AND REZ.TIP = ''REZ'' AND REZ.USERID = ' || coalesce(current_setting('PKG_GLOBALS.USERID', true)::numeric,0) || gSuplJoins || coalesce(sJoinAux,'') || '
      WHERE mat.tip = 1 AND Coalesce(LIES.CodIes1,0) = 0 and mat.rest = mat.cant and Coalesce(ART.TIPARTICOL,''0'') = ''1''';

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

  sSelect := '
      SELECT
        c.codcomanda NAV_CodDoc, c.tipdoc NAV_TipDoc, ''Fara predare'' Explicatii,
        0 ValConsum, 0 ValPredare,
        c.datadoc DataComInt, c1.termen TermenExec, c.nrdoc NrComProd,
        p.den_part Client, ccli.nrdoc NrComCli, ccli.datadoc DataComCli, ccli1.termen TermenCli, c.valoare ValCmdInt,
        objmat.DENUMIRE, g.den_gest SectiePred, c.obs ObsComInt, objret.denumire reteta,
        mat.rest Cant, 0 cantpredata, UMC.Den_UM1 um,
        ''FARA PREDARE'' Tip, '' '' ObsDoc, '' '' ContPredare, '' '' ContConsum,
        Coalesce(REZ.RESTA,0) CantRez, '' '' ObsDet ' || coalesce(vCampStoc,'') || sSeriiNull || gUserAlias || '
      FROM comanda1_man c1m
        INNER JOIN comanda1        c1 ON c1m.codcomanda1 = c1.codcomanda1
        inner join cmdprodmat     mat ON c1m.codcomanda1 = mat.codcomanda1 and (mat.tip = 2 or (mat.tip = 0 and c1.consum = 1)) and mat.rest = mat.cant
        INNER JOIN CMDPRODMAT    PROD ON C1.CODCOMANDA1  = PROD.CODCOMANDA1 AND Coalesce(PROD.TIP,0) = 0 and prod.rest = prod.cant
        INNER JOIN NUM1           UMC ON UMC.codum1      = c1.UMSEC
        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           ART ON objmat.codarticol = art.codarticol
        INNER JOIN NUM            UMM ON UMM.codum       = art.UM
        INNER JOIN NARTOBJ     ObjRet ON c1.codobiect    = objret.codobiect
        left  join prodcomp        pc on pc.codprodcomp  = c1.codreteta
        left  join nclasea        cls on cls.codclasea   = art.clasa
        LEFT  JOIN NIRSTOC         NS ON NS.CODNIRSTOC   = MAT.TIP - 1
        LEFT  JOIN INTRPRODLINK LINTR on LINTR.CodLinieComanda = mat.codcmdprodmat and mat.rest &lt;&gt; mat.cant
        LEFT  JOIN cmdlink       cmdl ON c1.codcomanda1  = cmdl.codcomanda1
        LEFT  JOIN comanda1     CCli1 ON cmdl.codliniecomanda = ccli1.codcomanda1
        LEFT  JOIN comanda       CCli ON ccli.codcomanda = ccli1.codcomanda
        LEFT  JOIN formatii         f ON c.codformatie   = f.codformatie
        LEFT  JOIN npart            p ON p.codpart       = ccli.partener
        left  join cmdprodman     man on man.codcmdprodman = c1.codcomanda1 - c1.codcomanda1
        LEFT  JOIN TMP_CMD        REZ ON REZ.CODOBIECT = MAT.CODCMDPRODMAT AND REZ.TIP = ''REZ'' AND REZ.USERID = ' || coalesce(current_setting('PKG_GLOBALS.USERID', true)::numeric,0) || gSuplJoins || coalesce(sJoinAux,'') || '
      WHERE Coalesce(LINTR.CodIntr1,0) = 0';

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

  sSelect := '
      SELECT
        c.codcomanda NAV_CodDoc, c.tipdoc NAV_TipDoc,
        coalesce(I.PrefixDoc,'''')||'' ''||coalesce(I.NrDoc::varchar,'''')||''/''||to_char(I.DataDoc,''dd.mm.yyyy'') Explicatii,
        L1.Cant * (NS.PRET - COALESCE(NS.ADAOS,0)) ValConsum, 0 ValPredare,
        c.datadoc DataComInt, c1.termen TermenExec, c.nrdoc NrComProd, p.den_part Client,
        ccli.nrdoc NrComCli, ccli.datadoc DataComCli, ccli1.termen TermenCli, c.valoare ValCmdInt,
        objmat.DENUMIRE, g.den_gest SectiePred, c.obs ObsComInt, objret.denumire reteta,
        0 cant, L1.CANT cantpredata, UMM.Den_um um,
        ''CONSUM SUPLIMENTAR'' Tip, I.Obs ObsDoc, '' '' ContPredare, CONTP.Simbol ContConsum,
        0 CantRez, I1.Obs ObsDet ' || coalesce(vCampStoc,'') || sSeriiIes || gUserAlias || '
      FROM comanda1_man c1m
        INNER JOIN comanda1        c1 ON c1m.codcomanda1 = c1.codcomanda1
        INNER JOIN CMDPRODMAT    PROD ON C1m.CODCOMANDA1 = PROD.CODCOMANDA1 AND Coalesce(PROD.TIP,0) = 0
        INNER JOIN NUM1           UMC ON UMC.codum1      = c1.UMSEC
        INNER JOIN comanda          c ON c1.codcomanda   = c.codcomanda
        INNER JOIN ngest            g ON c.codgest       = g.codgest
        INNER JOIN IESIRI1         I1 ON C1.CodComanda1  = I1.CodCmdInt1
        INNER JOIN IESIRI           I ON I1.CodIes       = I.CodIes
        inner join livr             l on i.codies        = l.codies
        INNER JOIN livr1           L1 ON L1.CodIes1      = I1.CodIes1 and l.codlivr = l1.codlivr
        INNER JOIN NIRSTOC         NS ON L1.CODNIRSTOC   = NS.CODNIRSTOC
        LEFT JOIN IOART1  IO1         ON IO1.CODIOART    = NS.CODIOART AND I.AN*12+I.LUNA BETWEEN IO1.ALSTART AND IO1.ALSTOP
        LEFT JOIN NCONT         CONTP ON CONTP.CODCONT   = IO1.CONT
        INNER JOIN NARTOBJ     OBJmat ON i1.codobiect    = objmat.codobiect
        INNER JOIN NART           ART ON objmat.codarticol = art.codarticol
        INNER JOIN NUM            UMM ON UMM.codum       = art.UM
        INNER JOIN NARTOBJ     ObjRet ON c1.codobiect    = objret.codobiect
        left  join prodcomp        pc on pc.codprodcomp  = c1.codreteta
        left  join nclasea        cls on cls.codclasea   = art.clasa
        LEFT  JOIN IESPRODLINK   LIES on LIES.CodIes1    = i1.codies1
        LEFT  JOIN cmdlink       cmdl ON c1.codcomanda1  = cmdl.codcomanda1
        LEFT  JOIN comanda1     CCli1 ON cmdl.codliniecomanda = ccli1.codcomanda1
        LEFT  JOIN comanda       CCli ON ccli.codcomanda = ccli1.codcomanda
        LEFT  JOIN formatii         f ON c.codformatie   = f.codformatie
        LEFT  JOIN npart            p ON p.codpart       = ccli.partener
        left  join cmdprodmat     mat on mat.codcomanda1 = c1.codcomanda1 - c1.codcomanda1
        left  join cmdprodman     man on man.codcmdprodman = c1.codcomanda1 - c1.codcomanda1' || gSuplJoins || coalesce(sJoinAux,'') || '
      WHERE Coalesce(LIES.codcmdprodmat,0) = 0 ';

  IF NOT current_setting('pkg_list_selectgestper.bIndiferent', TRUE)::boolean THEN
    sSelect := coalesce(sSelect,'') || '
        and I.DataDoc' || coalesce(sPer,'');
  END IF;

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

  sSelect := '  SELECT
        c.codcomanda NAV_CodDoc, c.tipdoc NAV_TipDoc,
        CASE WHEN INTR.TIPTRANZACTIE = 10 THEN ''NR''
             WHEN INTR.TIPTRANZACTIE =  9 THEN ''NPR''
             ELSE coalesce(INTR.PrefixDoc,'''')
        END||'' ''||coalesce(INTR.NrDoc::varchar,'''')||''/''||to_char(INTR.DataDoc,''dd.mm.yyyy'') Explicatii,
        0 ValConsum, INTR1.Cant * INTR1.PU ValPredare,
        c.datadoc DataComInt, c1.termen TermenExec, c.nrdoc NrComProd, p.den_part Client,
        ccli.nrdoc NrComCli, ccli.datadoc DataComCli, ccli1.termen TermenCli, c.valoare ValCmdInt,
        objmat.DENUMIRE, g.den_gest SectiePred, c.obs ObsComInt, objret.denumire reteta,
        mat.cant, INTR1.CANT cantpredata, case when mat.tip = 0 then UMC.Den_UM1 else UMM.Den_um end um,
        case when intr.tiptranzactie = 9 then ''REBUT'' else ''PREDARE'' end Tip, INTR.Obs ObsDoc, contp.simbol ContPredare, '' '' ContConsum,
        Coalesce(REZ.RESTA,0) CantRez, INTR1.Obs ObsDet ' || coalesce(vCampStoc,'') || sSeriiIntr || gUserAlias || '
      FROM comanda1_man c1m
        INNER JOIN comanda1        c1 ON c1m.codcomanda1 = c1.codcomanda1
        inner join cmdprodmat     mat on c1m.codcomanda1 = mat.codcomanda1
        INNER JOIN CMDPRODMAT    PROD ON C1.CODCOMANDA1  = PROD.CODCOMANDA1 AND Coalesce(PROD.TIP,0) = 0
        INNER JOIN NUM1           UMC ON UMC.codum1      = c1.UMSEC
        INNER JOIN comanda          c ON c1.codcomanda   = c.codcomanda
        INNER JOIN ngest            g ON c.codgest       = g.codgest
        INNER JOIN INTRPRODLINK LINTR on LINTR.CodLinieComanda = mat.codcmdprodmat
        INNER JOIN INTRARI1     INTR1 ON LINTR.CodIntr1  = INTR1.CodIntr1
        INNER JOIN INTRARI       INTR ON INTR.CodIntr    = INTR1.CodIntr
        LEFT JOIN LIVR1            L1 ON L1.CODINTR1     = INTR1.CODINTR1
        LEFT JOIN NIRSTOC          NS ON NS.CODINTR1     = INTR1.CODINTR1 OR NS.CODNIRSTOC = L1.CODNIRSTOC
        LEFT JOIN IOART1  IO1 ON IO1.CODIOART    = NS.CODIOART AND INTR.AN*12+INTR.LUNA BETWEEN IO1.ALSTART AND IO1.ALSTOP
        LEFT JOIN NCONT         CONTP ON CONTP.CODCONT   = IO1.CONT
        INNER JOIN NARTOBJ     OBJmat ON mat.codobiect   = objmat.codobiect
        INNER JOIN NART           ART ON objmat.codarticol = art.codarticol
        INNER JOIN NUM            UMM ON UMM.codum      = art.UM
        INNER JOIN NARTOBJ     ObjRet ON c1.codobiect   = objret.codobiect
        left  join prodcomp       pc  on pc.codprodcomp = c1.codreteta
        left  join nclasea        cls on cls.codclasea  = art.clasa
        LEFT  JOIN cmdlink       cmdl ON c1.codcomanda1 = cmdl.codcomanda1
        LEFT  JOIN comanda1     CCli1 ON cmdl.codliniecomanda = ccli1.codcomanda1
        LEFT  JOIN comanda       CCli ON ccli.codcomanda = ccli1.codcomanda
        LEFT  JOIN formatii         f ON c.codformatie   = f.codformatie
        LEFT  JOIN npart            p ON p.codpart       = ccli.partener
        left  join cmdprodman     man on man.codcmdprodman = c1.codcomanda1 - c1.codcomanda1
        LEFT  JOIN TMP_CMD        REZ ON REZ.CODOBIECT   = MAT.CODCMDPRODMAT AND REZ.TIP = ''REZ'' AND REZ.USERID = ' || coalesce(current_setting('PKG_GLOBALS.USERID', true)::numeric,0) || gSuplJoins || coalesce(sJoinAux,'') || '
      WHERE intr.anulat = 0 ';

  IF NOT current_setting('pkg_list_selectgestper.bIndiferent', TRUE)::boolean THEN
    sSelect := coalesce(sSelect,'') || '
        AND Intr.DataDoc' || coalesce(sPer,'');
  END IF;

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

  sSelect := '  SELECT
        c.codcomanda NAV_CodDoc, c.tipdoc NAV_TipDoc,
        coalesce(INTR.PrefixDoc,'''')||'' ''||coalesce(INTR.NrDoc::varchar,'''')||''/''||to_char(INTR.DataDoc,''dd.mm.yyyy'') Explicatii,
        0 ValConsum, INTR1.Cant * INTR1.PU ValPredare,
        c.datadoc DataComInt, c1.termen TermenExec, c.nrdoc NrComProd, p.den_part Client,
        ccli.nrdoc NrComCli, ccli.datadoc DataComCli, ccli1.termen TermenCli, c.valoare ValCmdInt,
        objNP.DENUMIRE, g.den_gest SectiePred, c.obs ObsComInt, objret.denumire reteta,
        0 cant, NS.CANTNIR cantpredata, UMC.Den_UM1 um,
        ''PREDARE SUPLIMENTARA'' Tip, INTR.Obs ObsDoc, contp.simbol ContPredare, '' '' ContConsum,
        Coalesce(REZ.RESTA,0) CantRez, INTR1.Obs ObsDet ' || coalesce(vCampStoc,'') || sSeriiIntr || gUserAlias || '
      FROM comanda1_man c1m
        INNER JOIN comanda1        c1 ON c1m.codcomanda1  = c1.codcomanda1
        INNER JOIN CMDPRODMAT    PROD ON C1.CODCOMANDA1   = PROD.CODCOMANDA1 AND ((Coalesce(PROD.TIP,0) in (0,2) and c1.consum = 1) or (Coalesce(PROD.TIP,0) = 2 and c1.consum = 2))
        INNER JOIN NUM1           UMC ON UMC.codum1       = c1.UMSEC
        INNER JOIN comanda          c ON c1.codcomanda    = c.codcomanda
        INNER JOIN ngest            g ON c.codgest        = g.codgest
        INNER JOIN INTRARI1     INTR1 ON INTR1.CodCmdInt1 = c1.codcomanda1 AND INTR1.CODOBIECT = PROD.CODOBIECT
        INNER JOIN NIRSTOC         NS ON NS.CODINTR1      = INTR1.CODINTR1
        INNER JOIN INTRARI       INTR ON INTR.CodIntr     = INTR1.CodIntr
        INNER JOIN NARTOBJ     ObjRet ON c1.codobiect     = objret.codobiect
        INNER JOIN NARTOBJ     ObjNP  ON intr1.codobiect  = objNP.codobiect
        INNER JOIN NART           ART ON objNP.codarticol = art.codarticol
        INNER JOIN NUM            UMM ON UMM.codum        = art.UM
        LEFT  JOIN NARTOBJ     ObjMat ON c1.codobiect - c1.codobiect = objmat.codobiect
        LEFT JOIN IOART1  IO1         ON IO1.CODIOART     = NS.CODIOART AND INTR.AN*12+INTR.LUNA BETWEEN IO1.ALSTART AND IO1.ALSTOP
        LEFT JOIN NCONT         CONTP ON CONTP.CODCONT    = IO1.CONT
        LEFT  JOIN INTRPRODLINK LINTR on LINTR.CodLinieComanda = prod.codcmdprodmat AND LINTR.CODINTR1 = INTR1.CODINTR1
        left  join prodcomp        pc on pc.codprodcomp   = c1.codreteta
        left  join nclasea        cls on cls.codclasea    = art.clasa
        LEFT  JOIN cmdlink       cmdl ON c1.codcomanda1   = cmdl.codcomanda1
        LEFT  JOIN comanda1     CCli1 ON cmdl.codliniecomanda = ccli1.codcomanda1
        LEFT  JOIN comanda       CCli ON ccli.codcomanda  = ccli1.codcomanda
        LEFT  JOIN formatii         f ON c.codformatie    = f.codformatie
        LEFT  JOIN npart            p ON p.codpart        = ccli.partener
        left  join cmdprodmat     mat on mat.codcomanda1  = c1.codcomanda1 - c1.codcomanda1
        left  join cmdprodman     man on man.codcmdprodman = c1.codcomanda1 - c1.codcomanda1
        LEFT  JOIN TMP_CMD        REZ ON REZ.CODOBIECT    = PROD.CODCMDPRODMAT AND REZ.TIP = ''REZ'' AND REZ.USERID = ' || coalesce(current_setting('PKG_GLOBALS.USERID', true)::numeric,0) || gSuplJoins || coalesce(sJoinAux,'') || '
      WHERE intr.anulat = 0 and LINTR.CODINTR1 IS NULL ';

  IF NOT current_setting('pkg_list_selectgestper.bIndiferent', TRUE)::boolean THEN
    sSelect := coalesce(sSelect,'') || '
        AND Intr.DataDoc' || coalesce(sPer,'');
  END IF;

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

  sSelect := '
      SELECT
        c.codcomanda NAV_CodDoc, c.tipdoc NAV_TipDoc, coalesce(r.NrDoc::varchar,'''')||''/''||to_char(r.DataI,''dd.mm.yyyy'') Explicatii,
        CASE WHEN r2.codies1 &gt; 0 THEN i1.pu ELSE T1.Tarif END * Coalesce(r2.TU, pm.tu) * r2.REALIZAT / 60 ValConsum, 0 ValPredare,
        c.datadoc DataComInt, c1.termen TermenExec, c.nrdoc NrComProd, p.den_part Client,
        ccli.nrdoc NrComCli, ccli.datadoc DataComCli, ccli1.termen TermenCli, c.valoare ValCmdInt,
        case when Coalesce(OP.codop,0) = 0 then OPMan.DENUMIRE else OP.Denumire end Denumire, g.den_gest SectiePred, c.obs ObsComInt, objret.denumire reteta,
        0 cant, r2.realizat cantpredata, UMC.Den_UM1 um,
        ''RAPORTARE SUPLIMENTARA'' Tip, '' '' ObsDoc, '' '' ContPredare, '' '' ContConsum,
        0 CantRez, '' '' ObsDet ' || coalesce(vCampStoc,'') || sSeriiNull || gUserAlias || '
      FROM comanda1_man c1m
        INNER JOIN comanda1        c1 ON c1m.codcomanda1 = c1.codcomanda1
        INNER JOIN CMDPRODMAT    PROD ON C1.CODCOMANDA1  = PROD.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 raportp0        r0 ON r0.CodComanda1  = c1m.CodComanda1
        INNER JOIN raportp          r ON r0.CodRaportP   = r.CodRaportP
        INNER JOIN raportp1        r1 ON r1.CodRaportP0  = r0.CodRaportP0
        INNER JOIN raportp2        r2 ON r2.CodRaportP1  = r1.CodRaportP1
        INNER JOIN NARTOBJ     ObjRet ON c1.codobiect    = objret.codobiect
        LEFT JOIN nirstoc          ns ON ns.codnirstoc   = ObjRet.CodObiect - ObjRet.CodObiect
        LEFT JOIN NCONT         CONTP ON CONTP.CODCONT   = objret.codobiect - objret.codobiect
        LEFT JOIN NARTOBJ      ObjMat ON c1.codobiect - c1.codobiect = objmat.codobiect
        LEFT JOIN NART         ArtMat ON ObjMat.codarticol = ArtMat.codarticol
        left JOIN NUM              UM ON UM.codum        = ArtMat.UM
        left JOIN NUM1            UMC ON UMC.codum1      = c1m.codcomanda1 - c1m.codcomanda1
        left join prodcomp         pc on pc.codprodcomp  = c1.codreteta
        LEFT JOIN cmdlink        cmdl ON c1.codcomanda1  = cmdl.codcomanda1
        LEFT JOIN comanda1      CCli1 ON cmdl.codliniecomanda = ccli1.codcomanda1
        LEFT JOIN comanda        CCli ON ccli.codcomanda = ccli1.codcomanda
        LEFT JOIN formatii          f ON c.codformatie   = f.codformatie
        LEFT JOIN npart             p ON p.codpart       = ccli.partener
        LEFT JOIN IESIRI1          I1 ON I1.CODIES1      = R2.CODIES1
        left JOIN ProdMan          PM ON PM.CodMan       = r2.CodMan
        left join locmunca         lm on r2.codloc       = lm.codloc
        LEFT JOIN Tarifeman1       T1 on T1.CodTarif     = CASE WHEN Coalesce(r2.CodTarif,0) = 0 THEN Pm.codTarif ELSE r2.CodTarif END
                                         AND ' || getanlunalucru() || ' BETWEEN T1.ALStart and T1.ALStop
        LEFT JOIN NOper            Op ON Op.CodOp         = r2.CodOp
        LEFT JOIN NOper         OpMan ON OpMan.CodOp      = PM.CodOp
        left join nclasea         cls ON cls.codclasea    = c1m.codcomanda1 - c1m.codcomanda1
        LEFT JOIN manprodlink    manl ON manl.CodRaportP2 = r2.codraportp2
        left JOIN NART            ART ON art.codarticol   = objmat.codarticol - objmat.codarticol
        left  join cmdprodman     man on man.codcmdprodman = c1.codcomanda1 - c1.codcomanda1
        left  join cmdprodmat     mat on mat.codcomanda1  = c1.codcomanda1 - c1.codcomanda1 ' || gSuplJoins || coalesce(sJoinAux,'') || '
      WHERE Coalesce(manl.codraportp2,0) = 0 ';

  IF NOT current_setting('pkg_list_selectgestper.bIndiferent', TRUE)::boolean THEN
    sSelect := coalesce(sSelect,'') || '
        AND ( (R.DataI' || coalesce(sPer,'') || ') or (R.DataS' || coalesce(sPer,'') || ') ) ';
  END IF;

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

  sSelect := '  SELECT
        c.codcomanda NAV_CodDoc, c.tipdoc NAV_TipDoc, coalesce(r.NrDoc::varchar,'''')||''/''||to_char(r.DataI,''dd.mm.yyyy'') Explicatii,
        CASE WHEN r2.codies1 &gt; 0 THEN i1.pu ELSE T1.Tarif END * Coalesce(r2.TU, pm.tu) * r2.REALIZAT / 60 ValConsum, 0 ValPredare,
        c.datadoc DataComInt, c1.termen TermenExec, c.nrdoc NrComProd, p.den_part Client,
        ccli.nrdoc NrComCli, ccli.datadoc DataComCli, ccli1.termen TermenCli, c.valoare ValCmdInt,
        case when Coalesce(OP.codop,0) = 0 then OPMan.DENUMIRE else OP.Denumire end DENUMIRE, g.den_gest SectiePred, c.obs ObsComInt, objret.denumire reteta,
        man.cant, r2.realizat cantpredata, UMC.Den_UM1 um,
        ''RAPORTARE'' Tip, '' '' ObsDoc, '' '' ContPredare, '' '' ContConsum,
        0 CantRez, '' '' ObsDet ' || coalesce(vCampStoc,'') || sSeriiNull || gUserAlias || '
      FROM comanda1_man c1m
        INNER JOIN comanda1        c1 ON c1m.codcomanda1    = c1.codcomanda1
        inner join cmdprodman     man on man.codcomanda1    = c1m.codcomanda1
        INNER JOIN CMDPRODMAT    PROD ON C1.CODCOMANDA1     = PROD.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 manprodlink   manl on manl.CodCmdProdMan = man.codcmdprodman
        INNER JOIN raportp2        r2 ON manl.CodRaportP2   = r2.CodRaportP2
        INNER JOIN raportp1        r1 ON r1.CodRaportP1     = r2.CodRaportP1
        INNER JOIN raportp0        r0 ON r0.CodRaportP0     = r1.CodRaportP0
        INNER JOIN raportp          r ON r0.CodRaportP      = r.CodRaportP
        INNER JOIN NARTOBJ     ObjRet ON c1.codobiect       = objret.codobiect
        LEFT JOIN nirstoc          ns ON ns.codnirstoc      = ObjRet.CodObiect - ObjRet.CodObiect
        LEFT JOIN NCONT         CONTP ON CONTP.CODCONT      = objret.codobiect - objret.codobiect
        LEFT JOIN NARTOBJ      ObjMat ON c1.codobiect - c1.codobiect = objmat.codobiect
        LEFT JOIN NART         ArtMat ON ObjMat.codarticol  = ArtMat.codarticol
        left JOIN NUM              UM ON UM.codum           = ArtMat.UM
        left JOIN NUM1            UMC ON UMC.codum1         = c1m.codcomanda1 - c1m.codcomanda1
        left join prodcomp         pc on pc.codprodcomp     = c1.codreteta
        LEFT JOIN cmdlink        cmdl ON c1.codcomanda1     = cmdl.codcomanda1
        LEFT JOIN comanda1      CCli1 ON cmdl.codliniecomanda = ccli1.codcomanda1
        LEFT JOIN comanda        CCli ON ccli.codcomanda    = ccli1.codcomanda
        LEFT JOIN formatii          f ON c.codformatie      = f.codformatie
        LEFT JOIN npart             p ON p.codpart          = ccli.partener
        LEFT JOIN IESIRI1          I1 ON I1.CODIES1         = R2.CODIES1
        left JOIN ProdMan          PM ON PM.CodMan          = r2.CodMan
        left join locmunca         lm on r2.codloc          = lm.codloc
        LEFT JOIN Tarifeman1       T1 on T1.CodTarif = CASE WHEN Coalesce(r2.CodTarif,0) = 0 THEN Pm.codTarif ELSE r2.CodTarif END
                                         AND ' || getanlunalucru() || ' BETWEEN T1.ALStart and T1.ALStop
        LEFT JOIN NOper            Op ON Op.CodOp        = r2.CodOp
        LEFT JOIN NOper         OpMan ON OpMan.CodOp     = PM.CodOp
        left  join nclasea        cls ON cls.codclasea   = c1m.codcomanda1 - c1m.codcomanda1
        left JOIN NART            ART ON art.codarticol  = objmat.codarticol - objmat.codarticol
        left  join cmdprodmat     mat on mat.codcomanda1 = c1.codcomanda1 - c1.codcomanda1 ' || gSuplJoins || coalesce(sJoinAux,'');

  IF NOT current_setting('pkg_list_selectgestper.bIndiferent', TRUE)::boolean THEN
    sSelect := coalesce(sSelect,'') || '
        WHERE ( (R.DataI' || coalesce(sPer,'') || ') or (R.DataS' || coalesce(sPer,'') || ') ) ';
  END IF;

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

  sSelect := '  SELECT
        c.codcomanda NAV_CodDoc, c.tipdoc NAV_TipDoc, ''Fara raportare'' Explicatii,
        0 ValConsum, 0 ValPredare,
        c.datadoc DataComInt, c1.termen TermenExec, c.nrdoc NrComProd, p.den_part Client,
        ccli.nrdoc NrComCli, ccli.datadoc DataComCli, ccli1.termen TermenCli, c.valoare ValCmdInt,
        OPMan.DENUMIRE, g.den_gest SectiePred, c.obs ObsComInt, objret.denumire reteta,
        man.cant, 0 cantpredata, UMC.Den_UM1 um,
        ''FARA RAPORTARE'' Tip, '' '' ObsDoc, '' '' ContPredare, '' '' ContConsum,
        0 CantRez, '' '' ObsDet ' || coalesce(vCampStoc,'') || sSeriiNull || gUserAlias || '
      FROM comanda1_man c1m
        INNER JOIN comanda1        c1 ON c1m.codcomanda1 = c1.codcomanda1
        inner join cmdprodman     man on man.codcomanda1 = c1m.codcomanda1
        INNER JOIN CMDPRODMAT    PROD ON C1.CODCOMANDA1  = PROD.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     ObjRet ON c1.codobiect    = objret.codobiect
        LEFT JOIN manprodlink   manl  on manl.CodCmdProdMan = man.codcmdprodman
        LEFT JOIN raportp2        r2  ON manl.CodRaportP2 = r2.CodRaportP2
        LEFT JOIN raportp1        r1  ON r1.CodRaportP1   = r2.CodRaportP1
        LEFT JOIN raportp0        r0  ON r0.CodRaportP0   = r1.CodRaportP0
        LEFT JOIN raportp          r  ON r0.CodRaportP    = r.CodRaportP
        LEFT JOIN nirstoc          ns ON ns.codnirstoc    = ObjRet.CodObiect - ObjRet.CodObiect
        LEFT JOIN NARTOBJ      ObjMat ON c1.codobiect - c1.codobiect = objmat.codobiect
        LEFT JOIN NART         ArtMat ON ObjMat.codarticol = ArtMat.codarticol
        left JOIN NUM              UM ON UM.codum          = ArtMat.UM
        left JOIN NUM1            UMC ON UMC.codum1        = c1m.codcomanda1 - c1m.codcomanda1
        LEFT JOIN NCONT         CONTP ON CONTP.CODCONT     = objret.codobiect - objret.codobiect
        left join prodcomp         pc on pc.codprodcomp    = c1.codreteta
        LEFT JOIN cmdlink        cmdl ON c1.codcomanda1    = cmdl.codcomanda1
        LEFT JOIN comanda1      CCli1 ON cmdl.codliniecomanda = ccli1.codcomanda1
        LEFT JOIN comanda        CCli ON ccli.codcomanda   = ccli1.codcomanda
        LEFT JOIN formatii          f ON c.codformatie     = f.codformatie
        LEFT JOIN npart             p ON p.codpart         = ccli.partener
        LEFT JOIN IESIRI1          I1 ON I1.CODIES1        = R2.CODIES1
        left JOIN ProdMan          PM ON PM.CodMan         = r2.CodMan
        left join locmunca         lm on r2.codloc         = lm.codloc
        LEFT JOIN Tarifeman1       T1 on T1.CodTarif = CASE WHEN Coalesce(r2.CodTarif,0) = 0 THEN Pm.codTarif ELSE r2.CodTarif END
                                         AND ' || getanlunalucru() || ' BETWEEN T1.ALStart and T1.ALStop
        LEFT JOIN NOper         OpMan ON OpMan.CodOp     = Man.CodOp
        left  join nclasea        cls on cls.codclasea   = c1m.codcomanda1 - c1m.codcomanda1
        left JOIN NART            ART ON art.codarticol  = objmat.codarticol - objmat.codarticol
        left  join cmdprodmat     mat on mat.codcomanda1 = c1.codcomanda1 - c1.codcomanda1 ' || gSuplJoins || coalesce(sJoinAux,'') || '
      WHERE man.rest = man.cant ';

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

  DELETE FROM tmp_cmd WHERE userid = current_setting('PKG_GLOBALS.USERID', true)::numeric;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_sitfin_inchid665fara473</obj_name>
  <obj_hashval>2c3729d03ffdd5917d0d6021192091c8</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_sitfin_inchid665fara473()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
DECLARE
  sSelect  varchar;
  vRez     numeric;
BEGIN
  --Adina 15.10.2020
  vRez := 0;

  sSelect := '
  WITH
    r as (
      SELECT
        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, rs.subunitatea, r.an, r.luna
      FROM ncontrul r
        INNER JOIN ncontrulsub rs ON rs.codcontrul = r.codcontrul
      WHERE r.an*12+r.luna = ' || coalesce(getANLUCRU()::varchar,'') || '*12+1 AND r.luna &gt; 1),
    n AS (
--          SELECT c.codcont
--          FROM ncont c
--          WHERE EXISTS (SELECT 1 FROM ncont1 c1 WHERE c1.codcont = c.codcont AND c1.anstart*12+c1.lunastart &lt;= getANLUCRU()*12)
--          START WITH c.codcont IN (SELECT codcont from ncont where simbol = ''665'')
--          CONNECT BY PRIOR c.codcont = c.codparinte
          WITH RECURSIVE aa  AS(
            SELECT n.codcont, n.codparinte
            FROM ncont n
            where n.codcont IN (SELECT codcont from ncont where simbol = ''665'')
            UNION ALL
            SELECT o.codcont, o.codparinte
            FROM ncont O  inner join AA a ON a.codcont = o.codparinte
          )
          SELECT codcont FROM AA c WHERE EXISTS (SELECT 1 FROM ncont1 c1 WHERE c1.codcont = c.codcont AND c1.anstart*12+c1.lunastart &lt;= ' || coalesce(getANLUCRU()::varchar,'') || '*12)
         )
    select sum(coalesce(debit,0)) from (
    SELECT
      0 nav_coddoc, 0 nav_tipdoc, sc.codcont, 0 codcoresp,
      0 debit, 0 credit, 0 debitv, 0 creditv, 0 valoare, 0 valoarev,
      coalesce(s.soldid,0) - coalesce(s.soldic,0) sold, coalesce(s.soldvid,0) - coalesce(s.soldvic,0) soldv,
      coalesce(s.soldi_ifrs,0) ifrs,  coalesce(s.soldvi_ifrs,0) ifrsv, coalesce(s.soldi_ifrs,0) sold_ifrs, coalesce(s.soldvi_ifrs,0) sold_ifrsv,
      coalesce(s.soldi_grup,0) grup,  coalesce(s.soldvi_grup,0) grupv, coalesce(s.soldi_grup,0) sold_grup, coalesce(s.soldvi_grup,0) sold_grupv,
      ''Sold initial'' obs, null as document, to_date(''01.''||sc.luna||''.''||sc.an,''dd.mm.yyyy'')  datadoc, s.subunitatea, 0 gest, sc.an, sc.luna,
      -1 ordine,
      0 codcentru, 0 indexlocal
    FROM ncontsold sc
      INNER JOIN ncontsoldsub s ON s.codcontsold = sc.codcontsold
      INNER JOIN n              ON n.codcont     = sc.codcont
    WHERE sc.an * 12 + sc.luna = ' || coalesce(getANLUCRU()::varchar,'') || '*12+1
    UNION ALL
    SELECT
      0 nav_coddoc, 0 nav_tipdoc, r.codcont, 0 codcoresp,
      coalesce(r.rulajpd,0) debit, coalesce(r.rulajpc,0) credit, coalesce(r.rulajvpd,0) debitv, coalesce(r.rulajvpc,0) creditv, 0 valoare, 0 valoarev,
      coalesce(r.rulajpd,0) - coalesce(r.rulajpc,0) sold, coalesce(r.rulajvpd,0) - coalesce(r.rulajvpc,0) soldv,
      coalesce(r.rulajp_ifrs,0) ifrs, coalesce(r.rulajvp_ifrs,0) ifrsv, coalesce(r.rulajp_ifrs,0) sold_ifrs, coalesce(r.rulajvp_ifrs,0) sold_ifrsv,
      coalesce(r.rulajp_grup,0) grup, coalesce(r.rulajvp_grup,0) grupv, coalesce(r.rulajp_grup,0) sold_grup, coalesce(r.rulajvp_grup,0) sold_grupv,
      ''Rulaj precedent'' obs, null as document, 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 indexlocal
    FROM r
      INNER JOIN n ON n.codcont = r.codcont
    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.valoarev= 0 then 1 else j.valoare/j.valoarev end),0) grupv, coalesce(j.valoaregrup,0) sold_grup, coalesce(j.valoaregrup/(case when j.valoarev= 0 then 1 else j.valoare/j.valoarev end),0) sold_grupv,
      j.obs, j.document, j.datadoc, j.subunitatea, j.gest, j.an, j.luna,
      CASE
        WHEN j.tipdoc = 81                                       THEN 10000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''SINCRONIZARE%'') THEN 20000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''INCHIDERE%'')    THEN 30000000000000000000
        ELSE 0
      END + j.codjurnal ordine,
      j.codcentru, j.indexlocal
    FROM jurnal j
      INNER JOIN n ON n.codcont = j.contd
    WHERE j.an *12 + j.luna BETWEEN ' || coalesce(getANLUCRU()::varchar,'') || '*12+1 AND ' || coalesce(getANLUCRU()::varchar,'') || '*12+12  and j.contc in (select codcont from ncont where not simbol like ''473.02%'')
    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.valoarev= 0 then 1 else j.valoare/j.valoarev end),0) grupv, -coalesce(j.valoaregrup,0) sold_grup, -coalesce(j.valoaregrup/(case when j.valoarev= 0 then 1 else j.valoare/j.valoarev end),0) sold_grupv,
      j.obs, j.document, j.datadoc, j.subunitatea, j.gest, j.an, j.luna,
      CASE
        WHEN j.tipdoc = 81                                       THEN 10000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''SINCRONIZARE%'') THEN 20000000000000000000
        WHEN TIPDOC = 32 AND UPPER(OBS) LIKE (''INCHIDERE%'')    THEN 30000000000000000000
        ELSE 0
      END + j.codjurnal ordine,
      j.codcentru, j.indexlocal
    FROM jurnal j
      INNER JOIN n ON n.codcont = j.contc
    WHERE j.an *12 + j.luna BETWEEN ' || coalesce(getANLUCRU()::varchar,'') || '*12+1 AND ' || coalesce(getANLUCRU()::varchar,'') || '*12+12  and j.contd in (select codcont from ncont where not simbol like ''473.02%'')
    ) AA_PG';

  BEGIN
    EXECUTE sSelect INTO vRez;
  EXCEPTION WHEN others THEN
    vRez := 0;
  END;

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_situtilaje_processlist</obj_name>
  <obj_hashval>d5246c346870cae90370dc4f9f47c94b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_situtilaje_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  gSuplCols        VARCHAR := 'UTILAJE U, UTILAJE1 U1, NARTOBJ NOBJ, NPART NP, NARTAMB AA, NCLASEP CP, TRASEULIVR TL, NPARTCODFISC CF';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
BEGIN
  --Florin 10.04.2024 - fixat 61632
  --Adina 16 septembrie 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NOBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = NOBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, '', '', '',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_SITUTILAJE.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  sInsert := 'INSERT INTO ' || tmpName || ' (
    DEN_PART, COD_PART, TIPOLOGIE, DEN_UTIL, TIP_UTIL, NrUtilAct,
    SedL, SedL_Adr, SedL_Loc, SedL_Jud,
    SedS, SedS_Adr, SedS_Loc, SedS_Jud,
    SedF, SedF_Adr, SedF_Loc, SedF_Jud,
    Operator,
    StatusDepo,
    StatusPart,
    StatusServ,
    StatusEstetic,
    Responsabil,
    DataCreare' || gUserFields || ')
  SELECT
    NP.DEN_PART, TRIM(REPLACE(UPPER(CF.CODFISCAL),''RO'','''')) CODCLI, TS.DENUMIRE, NOBJ.DENUMIRE, U.TIPUTILAJ, (case when U1.STATUS_PART=2 then 1 else 0 end),
    SL.OBS, fnc_GETADRESA(SL.SECTOR, SL.STRADA, SL.NR1, SL.NR2, SL.BLOC, SL.SCARA, SL.ETAJ, SL.APART, SL.CODPOSTAL), LL.DEN_LOCALIT, JL.DEN_JUDET,
    SS.OBS, fnc_GETADRESA(SS.SECTOR, SS.STRADA, SS.NR1, SS.NR2, SS.BLOC, SS.SCARA, SS.ETAJ, SS.APART, SS.CODPOSTAL), LS.DEN_LOCALIT, JS.DEN_JUDET,
    SF.OBS, fnc_GETADRESA(SF.SECTOR, SF.STRADA, SF.NR1, SF.NR2, SF.BLOC, SF.SCARA, SF.ETAJ, SF.APART, SF.CODPOSTAL), LF.DEN_LOCALIT, JF.DEN_JUDET,
    UTILIZATOR.Nume,
    (case U1.STATUS_DEPO
        when 1 then ''Plasat la partener''
        when 2 then ''Plasabil''
        when 3 then ''Defect/Reparatii''
        when 4 then ''Casabil''
        when 5 then ''Donatie''
        when 6 then ''Plasat la partener pt vanzare''
        when 7 then ''Plasat la partener pt depozitare''
     end),
    (case U1.STATUS_PART when 2 then ''Da'' when 3 then ''Nu'' else ''...'' end),
    (case U1.STATUS_SERVICE when 2 then ''Revizie anuala'' when 3 then ''Incident'' else ''Initial'' end),
    (case U1.ESTETIC
        when 1 then ''Ok''
        when 2 then ''De colantat integral''
        when 3 then ''De colantat fata''
        when 4 then ''De colantat spate''
        when 5 then ''De colantat laterale''
     end),
    (case when RESP.CODPERS=0 then RESP.NUME else RESP.NUME||'' ''||RESP.PRENUME end),
    To_Char(U1.DataCreare,''dd.mm.yyyy hh24:mi'')' || gUserAlias || '
  FROM UTILAJE U
    INNER JOIN UTILAJE1       U1         ON U1.CODUTILAJ   = U.CODUTILAJ
    INNER JOIN NARTOBJ        NOBJ       ON U.CODOBIECT    = NOBJ.CODOBIECT
    LEFT  JOIN NPART          NP         ON NP.CODPART     = U1.CODPART
    LEFT  JOIN NPARTCODFISC   CF         ON CF.CODPART     =  NP.CODPART AND CF.PRINCIPAL = 1
    LEFT  JOIN NAGENDA        SL         ON SL.CODAGENDA   = U1.CODLOCATIE
    LEFT  JOIN NTIPSEDII      TS         ON TS.CODTIPSEDIU = SL.CODTIPSEDIU
    LEFT  JOIN NLOCALIT       LL         ON LL.CODLOCALIT  = SL.CODLOCALIT
    LEFT  JOIN NJUDET         JL         ON JL.CODJUDET    = LL.CODJUDET
    LEFT  JOIN NAGENDA        SS         ON SS.CODPART     = U1.CODPART AND SS.SEDIUSOCIAL BETWEEN 4 AND 7 AND coalesce(SS.INACTIV, 0) = 0
    LEFT  JOIN NLOCALIT       LS         ON LS.CODLOCALIT  = SS.CODLOCALIT
    LEFT  JOIN NJUDET         JS         ON JS.CODJUDET    = LS.CODJUDET
    LEFT  JOIN NAGENDA        SF         ON SF.CODPART     = U1.CODPART AND SF.SEDIUSOCIAL IN (2,3,6,7) AND coalesce(SF.INACTIV, 0) = 0
    LEFT  JOIN NLOCALIT       LF         ON LF.CODLOCALIT  = SF.CODLOCALIT
    LEFT  JOIN NJUDET         JF         ON JF.CODJUDET    = LF.CODJUDET
    LEFT  JOIN MIFIX          M          ON M.NRINVENTAR   = U.NRINVENTAR
    LEFT  JOIN (SELECT DISTINCT CODMIFIX,CODNIRSTOC FROM MIFIX1) M1 ON M1.CODMIFIX = M.CODMIFIX
    LEFT  JOIN NIRSTOC        NS         ON NS.CODNIRSTOC    = M1.CODNIRSTOC
    LEFT  JOIN NARTAMB        AA         ON AA.CODOBIECT     = U.CODOBIECT AND AA.UMSEC = NS.UMSEC
    LEFT  JOIN NCLASEP        CP         ON CP.CODCLASEP     = NP.CODCLASA
    LEFT  JOIN TRASEULIVR     TL         ON TL.CODTRASEULIVR = SL.CODTRASEU
    LEFT  JOIN NPERS          RESp       ON RESP.CODPERS     = coalesce(U1.CODPERS,0)
    LEFT  JOIN TMP_UTILIZATOR UTILIZATOR ON UTILIZATOR.CODUTILIZATOR = U1.USERID' || gSuplJoins || '
  WHERE U1.STATUS_PART = 2
    AND coalesce(SF.CODAGENDA,0) =
        CASE
          WHEN SL.SEDIUSOCIAL IN (2,3,6,7) THEN SL.CODAGENDA
          WHEN SS.SEDIUSOCIAL IN (2,3,6,7) THEN SS.CODAGENDA
          ELSE coalesce((SELECT MIN(x.CODAGENDA) FROM NAGENDA x WHERE x.CODPART = U1.CODPART AND x.SEDIUSOCIAL IN (2,3,6,7) AND coalesce(x.INACTIV, 0) = 0),0)
        END';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocfaramisc_processlist_faratuning</obj_name>
  <obj_hashval>094d78527196b077930dea91e5156318</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocfaramisc_processlist_faratuning(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       varchar := '';
  vToateGest     BOOLEAN := current_setting('PKG_LIST_SELECTSCAD.vToateGest',  true)::boolean;
  vToateIOArt   BOOLEAN := current_setting('PKG_LIST_SELECTSCAD.vToateIoart', true)::boolean;
  vInclNoStoc   BOOLEAN := current_setting('PKG_LIST_SELECTSCAD.vExtra1',     true)::boolean;
  vSerii         BOOLEAN := current_setting('PKG_LIST_SELECTSCAD.vExtra2',     true)::boolean;
  vCateGest     NUMERIC := 0;
  vCateLGest     NUMERIC := 0;
  vZiuaIni       date := to_date(current_setting('PKG_LIST_SELECTSCAD.vDataIni', true), 'DD.MM.YYYY');
  vZiuaFin       date := to_date(current_setting('PKG_LIST_SELECTSCAD.vDataScad', true), 'DD.MM.YYYY');
  sZiuaIni       varchar := 'To_date(''' || coalesce(To_Char(vZiuaIni, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
  sZiuaFin       varchar := 'To_date(''' || coalesce(To_Char(vZiuaFin, 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
  sFiltruStoc   varchar := '';
  sWhere         varchar := '';
  sAux           varchar := '';
  sJoinNIR       varchar := '';
  sJoinNGest    varchar := '';
  sJoinStoc     varchar := 'INNER';
  sExclLivrPer   varchar := '';
  sExclNirPer   varchar := '';
  sSerie         varchar := ' 0 ';
  sCantNir       varchar := 'NS.CANTNIR';
  sJoinSer       varchar := '';
  sFiltruL       varchar := '';
  sSGroup       varchar := '';
  sDenGest       varchar := '';
  sCampSer       varchar := '';
  sCodGest       varchar := 'N.Gest';
  gSuplCols      VARCHAR := 'NARTOBJ NAO, NART NA, NUM NUM, NPART PROD, NCONT NC, NCLASEA CLS';
   gUserFields    VARCHAR := '';
  gUserAlias     VARCHAR := '';
  gNullAlias     VARCHAR := '';
  gSuplJoins     VARCHAR := '';
  vCentralizat  NUMERIC := current_setting('PKG_LIST_SELECTSCAD.vCentralizat', true)::numeric;
BEGIN
  --Adina 14.12.2020 tichete 41572, 41573
  --Adina 03 septembrie 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);
  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_STOCFARAMISC.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias,'') ;
  gNullAlias  := coalesce(gNullAlias,'') ;
  gSuplJoins  := coalesce(gSuplJoins,'') ;
  gSuplCols   := coalesce(gSuplCols,'')  ;

  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
      sFiltruStoc := sFiltruStoc || '
        AND N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
    ELSIF vCateGest = 0 THEN
      sFiltruStoc := sFiltruStoc || '
        AND NS.CODLOCATIE::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'') ';
    ELSE
      sFiltruStoc := sFiltruStoc || '
        AND (N.GEST::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') OR NS.CODLOCATIE::varchar (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODLOCATIE'')) ';
    END IF;
  END IF;

  IF  NOT vToateIOArt THEN
    sFiltruStoc := sFiltruStoc || '
        AND NS.CODIOART::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'') ';
  END IF;

  sAux := (PKG_LIST_BASE_UTILS_COND_SUBUNIT('G', 'CODSUBUNIT', '
        AND',NULL));

  IF sAux IS NOT NULL  THEN
    sJoinNIR := '
        INNER JOIN NIR N ON N.CODNIR = NS.CODNIR';
    sJoinNGest := '
        INNER JOIN NGEST G ON G.CODGEST = N.GEST';
    sFiltruStoc := sFiltruStoc || sAux;
  END IF;

  IF vSerii THEN
    sSerie := ' NSER.';
    sCantNir := 'COALESCE(NSER.CANTNIR,NS.CANTNIR,0)';
    sCampSer := ', L1.CODNIRSER';
    sJoinSer := '
        LEFT JOIN NIRSER NSER ON NSER.CODNIRSTOC = NS.CODNIRSTOC';
    sFiltruL := ' AND coalesce(L.CODNIRSER,0) = coalesce(NSER.CODNIRSER,0)';
    sSGroup := sSGroup || ', NSER.CODSERIE';
  END IF;

  CASE vCentralizat
    WHEN 1 THEN
      sDenGest := 'NG.';
      sSGroup := sSGroup || ', N.GEST';
    WHEN 2 THEN
      sDenGest := 'NG.';
      sSGroup := sSGroup || ', N.GEST';
    ELSE
      sDenGest := '''FIRMA'' ';
      sCodGest := 'NULL::numeric Gest';
  END CASE;

  sSGroup := sSGroup || ', NS.CODIOART';

  IF  vCentralizat &lt;&gt; 0 THEN
    sExclLivrPer := '
            WHEN L.TIPLIVR IN (6,12,13,23) THEN 0';
    sExclNirPer := '
            WHEN N.TIPNIR IN  (6,12,13,23) THEN 0';
  END IF;

  IF vInclNoStoc THEN
    sJoinStoc := 'LEFT';
  END IF;

  IF  NOT vToateGest AND vInclNoStoc AND  vCateGest &lt;&gt; 0 THEN
    sWhere := '
    AND (S.CODOBIECT IS NOT NULL OR NA.GESTIMPLICITA::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST''))';
  ELSIF NOT vToateGest AND vInclNoStoc AND  vCateGest = 0 THEN
    sJoinStoc := 'INNER';
  END IF;

  IF  NOT vToateIOArt AND vInclNoStoc THEN
    sWhere := sWhere || '
    AND (S.CODOBIECT IS NOT NULL OR NA.CONTIMPLICIT::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART''))';
  END IF;

  sInsert :=
  'INSERT INTO ' || tmpName || '(
    CodObiect, Art,Ser,Gest,TipCont,Cont,UM,Stoc,PrInreg,ValInreg,MG,
    CodExt,CodInt,Prod,Promise,Last_Furn,Last_DataAchiz,Last_PretAchiz ' || gUserFields || ')
  WITH
  PROMISE AS
  (
    SELECT c1.codobiect, Sum(coalesce(c1.restacceptat,0) - coalesce(rr.cant,0)) cant
    FROM comanda1 c1
      INNER JOIN comanda c ON c1.codcomanda = c.codcomanda
      LEFT JOIN (
                 SELECT r.codcomanda1, CASE WHEN coalesce(r.codobiect,0) = 0 THEN cc1.codobiect ELSE r.codobiect END codobiect, Sum(r.rest) cant
                 FROM rezervats r INNER JOIN comanda1 cc1 on r.codcomanda1 = cc1.codcomanda1
                 WHERE r.codnirstoc &gt; 0
                 GROUP BY r.codcomanda1, CASE WHEN coalesce(r.codobiect,0) = 0 THEN cc1.codobiect ELSE r.codobiect END
                ) rr ON rr.codcomanda1 = c1.codcomanda1 and c1.codobiect = rr.codobiect
    WHERE c.operat = 1 and c.anulat = 0 and c.tipdoc = 18 and coalesce(c.tiptranzactie,0) = 0
      AND c1.termen BETWEEN ' || sZiuaIni || ' AND ' || sZiuaFin || '
    GROUP BY c1.codobiect
  ),
  L AS
  (
    SELECT l1.codnirstoc' || sCampSer || ',
      SUM((case when L.TIPLIVR=15 then 1 else -1 end) * L1.CANT) CANTIES,
      SUM(CASE' || sExclLivrPer || '
            WHEN L.DATALIVR &gt;= ' || sZiuaIni || ' THEN 1
            ELSE 0
          END
      ) LIVR_PER
    FROM LIVR L
      INNER JOIN livr1   l1 ON l1.codlivr    = l.codlivr
      INNER JOIN nirstoc ns ON ns.codnirstoc = l1.codnirstoc' || sJoinNIR || sJoinNGest || '
    WHERE L.DATALIVR &lt;= ' || sZiuaFin || sFiltruStoc || '
    GROUP BY l1.codnirstoc' || sCampSer || '
  ),
  STOC AS
  (
    SELECT
      NS.CODOBIECT, ' || sSerie || 'CODSERIE, ' || sCodGest || ', NS.CODIOART,
      SUM(' || sCantNir || '+coalesce(L.CANTIES,0)) CANT, SUM((' || sCantNir || '+coalesce(L.CANTIES,0)) * NS.PRET) VALINREG,
      SUM(CASE' || sExclNirPer || '
            WHEN N.DATANIR &gt;= ' || sZiuaIni || ' THEN 1
            ELSE 0
          END
      ) INTR_PER,
      SUM(coalesce(L.LIVR_PER,0)) LIVR_PER
    FROM NIR N
        INNER JOIN NIRSTOC NS ON NS.CODNIR    = N.CODNIR' || sJoinNGest || sJoinSer || '
        LEFT  JOIN         L  ON L.CODNIRSTOC = NS.CODNIRSTOC' || sFiltruL || '
    WHERE N.OPERAT = 1 and N.DATANIR &lt;= ' || sZiuaFin || sFiltruStoc || '
    GROUP BY NS.CODOBIECT' || sSGroup || '
  ),
  LM AS
  (
    SELECT
--      DISTINCT
      NS.CODOBIECT,
--      LAST_VALUE(P.DEN_PART) IGNORE NULLS
--      OVER (PARTITION BY NS.CODOBIECT ORDER BY N.DATANIR ROWS BETWEEN
--            UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS LAST_FURN,
--      LAST_VALUE(N.DATANIR) IGNORE NULLS
--      OVER (PARTITION BY NS.CODOBIECT ORDER BY N.DATANIR ROWS BETWEEN
--            UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS LAST_DATAACHIZ,
--      LAST_VALUE(NS.PRET) IGNORE NULLS
--      OVER (PARTITION BY NS.CODOBIECT ORDER BY N.DATANIR ROWS BETWEEN
--            UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS LAST_PRETACHIZ
      (array_remove(array_agg(P.DEN_PART ORDER BY N.DATANIR DESC, N.CODNIR DESC), null))[1] AS LAST_FURN,  --AA= 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, NS.CODINTR1 ASC), null))[1] AS LAST_PRETACHIZ  -- 14.12.2020 #41573 - pe acelasi Nir am acelasi produs cu 2 preturi diferite si ca sa fie ca in Oracle am adaugat  ''NS.CODINTR1 ASC''
    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(PKG_LIST_BASE_UTILS_COND_SUBUNIT('G', 'CODSUBUNIT',NULL,NULL),'') || '
    GROUP BY NS.CODOBIECT
  ),  --AA= am scos DISTINCT-ul si partition by si am pus aici group by
  IO1  AS
  (
    SELECT CODIOART, MAX(MG) MG, MAX(CONT) CONT
    FROM (SELECT CODIOART, MG, CONT, dense_rank() over(partition by CODIOART order by ANSTART*12+LUNASTART desc) NR
          FROM IOART1
          WHERE ANSTART*12+LUNASTART &lt;= ' || coalesce(getAnLunaLucru()::varchar,'') || '
         ) aa
    WHERE aa.NR=1
    GROUP BY CODIOART
  )
  SELECT
    NAO.CodObiect, NAO.DENUMIRE, SER.SERIE, ' || sDenGest || 'DEN_GEST, IO.DEN_IOART, NC.SIMBOL, NUM.DEN_UM, coalesce(S.CANT,0), coalesce(S.VALINREG/S.CANT,0), coalesce(S.VALINREG,0), (case IO1.MG when 1 then ''FIFO'' when 2 then ''LIFO'' when 3 then ''PMP'' when 4 then ''IDS'' when 5 then ''VALORIC'' else NULL end),
    NAO.CODEXTERN, NAO.CODINTERN, PROD.DEN_PART PRODUCATOR, coalesce(Promise.Cant,0),LM.Last_Furn,LM.Last_DataAchiz,LM.Last_PretAchiz ' || gUserAlias || '
  FROM NARTOBJ                    NAO
    INNER JOIN NART               NA   ON NA.CODARTICOL     = NAO.CODARTICOL
    ' || sJoinStoc || ' JOIN STOC S    ON S.CODOBIECT       = NAO.CODOBIECT
    LEFT  JOIN LM                      ON LM.CODOBIECT      = NAO.CODOBIECT
    LEFT  JOIN PROMISE                 ON PROMISE.CODOBIECT = NAO.CODOBIECT
    LEFT  JOIN NCLASEA            CLS  ON NA.CLASA          = CLS.CODCLASEA
    LEFT  JOIN NSERII             SER  ON SER.CODSERIE      = S.CODSERIE
    LEFT  JOIN NGEST              NG   ON NG.CODGEST        = COALESCE(S.GEST, NA.GESTIMPLICITA, 0)
    LEFT  JOIN IOART              IO   ON IO.CODIOART       = COALESCE(S.CODIOART, NA.CONTIMPLICIT, 0)
    LEFT  JOIN IO1                     ON IO1.CODIOART      = COALESCE(S.CODIOART, NA.CONTIMPLICIT, 0)
    LEFT  JOIN NUM                     ON NUM.CODUM         = NA.UM
    LEFT  JOIN NPART              PROD ON PROD.CODPART      = NAO.CODPRODUCATOR
    LEFT  JOIN NCONT              NC   ON NC.CODCONT        = IO1.CONT' || gSuplJoins || '
  WHERE coalesce(S.CANT,-1) &lt;&gt; 0 AND coalesce(S.INTR_PER,0) = 0 AND coalesce(S.LIVR_PER,0) = 0 AND NA.TIPARTICOL = 0::varchar';

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_stocrotatie_processlist</obj_name>
  <obj_hashval>25f558a1de9f2de55f46255c1dee4ec3</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_stocrotatie_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  vPerioada       varchar := 'TO_DATE(''' || coalesce(current_setting('PKG_LIST_BASE_STOCROTATIE.vDataIni', true),'') || ''',''DD.MM.YYYY'') AND TO_DATE(''' || coalesce(current_setting('PKG_LIST_BASE_STOCROTATIE.vDataFin', true),'') || ''',''DD.MM.YYYY'') ';
  vCondArt         varchar := '';
  sJoinExt         varchar := '';
  gSuplCols        VARCHAR := 'NIR NIR, NIRSTOC NS, INTRARI I, NARTOBJ NAO, NART NA, NUM NUM, NPART NP, NGEST NG';
   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 = NAO.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = NAO.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_STOCROTATIE.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  IF  NOT current_setting('PKG_LIST_BASE_STOCROTATIE.vToateArt', true)::boolean THEN
    vCondArt := ' AND EXISTS ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'' AND VALOARE = NS.CODOBIECT::varchar ) ';
  END IF;

  vCondArt := vCondArt;

  sInsert :=
  'INSERT INTO ' || tmpName || ' (Art, Gest, UM, DataRec, CantRec, Stoc, Furn, TipDoc, NrDoc, DataDoc, Per1, Per2, Per3, Per4, Per5 ' || gUserFields || ')
  WITH
    PER_IES AS (
      SELECT ROOTCODNIRSTOC,
              SUM(CASE WHEN L.DATALIVR - N.DATANIR BETWEEN  0 AND  30 THEN L1.CANT ELSE 0 END) AS PER1,
              SUM(CASE WHEN L.DATALIVR - N.DATANIR BETWEEN 31 AND  60 THEN L1.CANT ELSE 0 END) AS PER2,
              SUM(CASE WHEN L.DATALIVR - N.DATANIR BETWEEN 61 AND  90 THEN L1.CANT ELSE 0 END) AS PER3,
              SUM(CASE WHEN L.DATALIVR - N.DATANIR BETWEEN 91 AND 120 THEN L1.CANT ELSE 0 END) AS PER4,
              SUM(CASE WHEN L.DATALIVR - N.DATANIR &gt; 120 THEN L1.CANT ELSE 0 END) AS PER5
      FROM (
              WITH RECURSIVE AA AS
                (SELECT NS.CODNIRSTOC, NS.CODNIRSTOC ROOTCODNIRSTOC, NS.CODNIR ROOTCODNIR, NS.CODNIRSTOCPARINTE
                 FROM NIRSTOC NS
                 WHERE (NS.CODNIRSTOCPARINTE IS NULL)
                        AND (NS.REST &lt;&gt; NS.CANTNIR)
                        AND (EXISTS (SELECT CODNIR
                                     FROM NIR INNER JOIN INTRARI I ON I.CODINTR = NIR.CODINTR
                                     WHERE NIR.CODNIR = NS.CODNIR
                                       AND NIR.DATANIR BETWEEN ' || vPerioada || ' ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
                                    )
                            )
                        AND NS.REST &lt;&gt; NS.CANTNIR
                 UNION ALL
                 SELECT N.CODNIRSTOC, cr.ROOTCODNIRSTOC, cr.ROOTCODNIR, N.CODNIRSTOCPARINTE
                 FROM NIRSTOC N JOIN AA CR ON cr.CODNIRSTOC = N.CODNIRSTOCPARINTE AND N.REST &lt;&gt; N.CANTNIR
                )
              SELECT CODNIRSTOC, ROOTCODNIRSTOC, ROOTCODNIR FROM AA order by CODNIRSTOC
            ) X
            INNER JOIN NIR N    ON N.CODNIR      = X.ROOTCODNIR
            INNER JOIN LIVR1 L1 ON L1.CODNIRSTOC = X.CODNIRSTOC
            INNER JOIN LIVR L   ON L.CODLIVR     = L1.CODLIVR
      WHERE L.CODIES IS NOT NULL
      GROUP BY ROOTCODNIRSTOC
    )
  SELECT
    NAO.DENUMIRE, NG.DEN_GEST, NUM.DEN_UM ,NIR.DATANIR, NS.CANTNIR, NS.REST, NP.DEN_PART,
    PKG_LIST_BASE_UTILS_DECODE_TIPDOC_SCURT(I.TIPDOC) tipdoc, I.NRDOC, I.DATADOC,
    coalesce(PI.PER1,0), coalesce(PI.PER2,0), coalesce(PI.PER3,0), coalesce(PI.PER4,0), coalesce(PI.PER5,0)' || gUserAlias || '
  FROM   NIR
        INNER JOIN NIRSTOC NS  ON NS.CODNIR     = NIR.CODNIR
        INNER JOIN INTRARI I   ON I.CODINTR     = NIR.CODINTR
        INNER JOIN NARTOBJ NAO ON NAO.CODOBIECT = NS.CODOBIECT
        INNER JOIN NART    NA  ON NA.CODARTICOL = NAO.CODARTICOL
        LEFT  JOIN NUM         ON NUM.CODUM     = NA.UM
        LEFT  JOIN PER_IES PI  ON NS.CODNIRSTOC = PI.ROOTCODNIRSTOC
        LEFT  JOIN NPART   NP  ON NP.CODPART    = I.PARTENER
        LEFT  JOIN NGEST   NG  ON NG.CODGEST    = NIR.GEST' || gSuplJoins || '
  WHERE NIR.DATANIR BETWEEN ' || vPerioada || vCondArt || 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_tehprod_pregatestestructura</obj_name>
  <obj_hashval>1adc1bd3e1fc7f6fd33e6f228d5d0303</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_tehprod_pregatestestructura()
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  V_REC RECORD;
begin
  --Bogdan 14.09.2020
  UPDATE tmp_prodcomp tmp SET codobiect = (SELECT pc.codobiect FROM prodcomp pc WHERE pc.codprodcomp = tmp.codprodcomp);
  UPDATE tmp_prodcomp     SET observatii = ' ';

  FOR v_rec IN (SELECT codprodcomp, observatii, codobiect, cant FROM tmp_prodcomp ORDER BY observatii) LOOP
    PERFORM PKG_LIST_BASE_TEHPROD_BagaMateriale (v_rec.observatii, v_rec.codobiect, v_rec.cant, v_rec.codprodcomp, 0, v_rec.Codobiect, v_rec.codobiect);
  END LOOP;
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topfurn_getallioart_n</obj_name>
  <obj_hashval>9944054dc1424a073182e618d9ff682e</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topfurn_getallioart_n()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 07 septembrie 2020
  IF current_setting('PKG_LIST_BASE_TOPFURN.vAllIOArt', true)::boolean THEN
    RETURN  1;
  ELSE
    RETURN  0;
  END IF;
END;
$function$
</obj_text>
</row>

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

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

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_np_m_processlist</obj_name>
  <obj_hashval>6ad6fabac22da76a3a8197cde63f7785</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_np_m_processlist(tmptable character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert         varchar := '';
  sFiltru         varchar := '';
  gSuplCols        VARCHAR :=   'nartobj nobj, num1 num1, nart nart, ngest ng, nartamb aa, formatii f, comanda c, nclasea nca, nclaseg ncg, nclasea ca1, nclasea ca2, nclasea ca3, nclasea ca4, ncont cimpl,NARTOBJ OBJGENK,'||
                               'utilaje2c ut2c,utilaje ut,utilaje2 ut2,ninterventiiauto interv,nartobj intervserv,nartobj utilajobj,NCLASEINT CLSINT';
   gUserFields      VARCHAR := '';
  gUserAlias       VARCHAR := '';
  gNullAlias       VARCHAR := '';
  gSuplJoins       VARCHAR := '';
  vToateArt        boolean := ((current_setting('PKG_LIST_SELECTPER.vToateArt' , true)::numeric)=1);
  vToateGest      boolean := ((current_setting('PKG_LIST_SELECTPER.vToateGest', true)::numeric)=1);
BEGIN
  --Adina 05.04.2021 - alstart,alstop
  --Adina 18.02.2021 - dupa modif.Oracle din 17.02.2021
  --Adina 16 septembrie 2020
  call pkg_list_struct_startsuplcols();
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJEXT', 'OEXT', 'OEXT.CODOBIECT = NOBJ.CODOBIECT',NULL);
  call pkg_list_struct_addsupltabs(gSuplCols, 'NARTOBJATR', 'OATR', 'OATR.CODOBIECT = NOBJ.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_NP_M.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  DELETE FROM tmp_manevra_liste WHERE filtru = 'CODNIRSTOC';
  DELETE FROM tmp_manevra_serii;

  IF  PKG_LIST_SELECTPER_DataIni() = PKG_LIST_SELECTPER_DataFin() THEN
    sFiltru := '
      AND i.datadoc = TO_DATE(''' || coalesce(To_Char(PKG_LIST_SELECTPER_DataIni(), 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
  ELSE
    sFiltru := '
      AND i.datadoc BETWEEN TO_DATE(''' || coalesce(To_Char(PKG_LIST_SELECTPER_DataIni(), 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'') AND TO_DATE(''' || coalesce(To_Char(PKG_LIST_SELECTPER_DataFin(), 'dd.mm.yyyy'),'') || ''',''dd.mm.yyyy'')';
  END IF;

  IF  vToateArt = FALSE THEN
    sFiltru := coalesce(sFiltru,'') || '
      AND I1.CODOBIECT::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'') ';
  END IF;

  IF  vToateGest = FALSE THEN
    sFiltru := coalesce(sFiltru,'') || '
      AND I.CODGESTPROD::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
  END IF;

  sInsert :=
  'INSERT INTO ' || TMPTABLE || ' (
    NAV_CODDOC,NAV_TIPDOC,DOCUMENT,PREFIXDOC,NRDOC,DATADOC,DENUMIRE,CANT,PU,UM,CLASA_ART,GEST,CLASA_GEST,
    D1, D2, D3, SCHIMB, FORMATIE, CMD_INTERNA, UMTRANSF, COEFTRANSF, PRETIMP, MONIMP, ANULAT, OPERAT, OPERATOR, INTERVENTIE, UTILAJ, DATASTART, DATASTOP ' || gUserFields || ')
  WITH
    CA AS (
      SELECT c.codca, c.codclasea, c.den_clasea, c.prefix, c.nivel, c.nranalitice, c.codparinte, c.verlistsuplfact, c.verlistsupltoall,
        CASE WHEN cp.simbol IS NULL THEN c.simbol ELSE SubStr(c.simbol,Length(cp.simbol)+2) END SIMBOL
      FROM(
            SELECT * FROM
              (
                 WITH RECURSIVE AA (codca, codclasea, den_clasea, prefix, nivel, nranalitice, codparinte, verlistsuplfact, verlistsupltoall, simbol) AS(
                  SELECT codclasea codca, codclasea, den_clasea, prefix, nivel, nranalitice, codparinte, verlistsuplfact, verlistsupltoall, simbol
                  FROM nclasea
                  UNION ALL
                  SELECT A.codca, a.codparinte codclasea, o.den_clasea, o.prefix, o.nivel, o.nranalitice, o.codparinte, o.verlistsuplfact, o.verlistsupltoall, o.simbol
                  FROM nclasea O  inner join AA a ON o.codclasea = a.codparinte
                )
                 SELECT codca, codclasea, den_clasea, prefix, nivel, nranalitice, codparinte, verlistsuplfact, verlistsupltoall, simbol FROM AA
              ) A_PG
          ) c LEFT JOIN nclasea cp ON cp.codclasea = c.codparinte
    ),
    IG AS (
      SELECT
        i.codintr, i1.codintr1, ns.d1, ns.d2, ns.d3,
        SUM(COALESCE(-l1.cant,nser.cantnir*(case when ns.cantnir=0 then 1 else coalesce(ns.cantfurn,0)/ns.cantnir end),ns.cantfurn,i1.cant) ) cant,
        SUM(COALESCE(-l1.cantum1, nser.cantum1,ns.cantum1)) cantum1,
        SUM(COALESCE(-l1.cantum2, nser.cantum2,ns.cantum2)) cantum2
      FROM intrari i
        INNER JOIN intrari1 i1   ON i1.codintr    = i.codintr
        INNER JOIN COMANDA1 C1   ON I1.CODCMDINT1 = C1.CODCOMANDA1
        INNER JOIN COMANDA C     ON C1.CODCOMANDA = C.CODCOMANDA
        LEFT  JOIN livr1 l1     ON l1.codintr1   = i1.codintr1
        LEFT  JOIN nirstoc ns   ON ns.codobiect  = i1.codobiect AND
                                   (((l1.codlivr1 IS NOT NULL) AND (ns.codnirstoc = l1.codnirstoc)) OR
                                   ((l1.codlivr1 IS     NULL) AND (ns.codintr1 = i1.codintr1)) )
        LEFT  JOIN nir n         ON n.codintr = i.codintr AND n.codnir = ns.codnir
        LEFT  JOIN nirser nser   ON
                                   (((l1.codlivr1 IS NOT NULL) AND (nser.codnirser = l1.codnirser)) OR
                                   ((l1.codlivr1 IS     NULL) AND (nser.codnirstoc = ns.codnirstoc)) )
        LEFT  JOIN nserii s     ON s.codserie = nser.codserie
      WHERE i.tipdoc = 7 AND C.TIPTRANZACTIE = 1 AND C.ANULAT = 0 AND C.OPERAT = 1 ' || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || sFiltru || '
      GROUP BY i.codintr, i1.codintr1, ns.d1, ns.d2, ns.d3 )
  SELECT
    i.codintr,
    i.tipdoc,
    case when I.TIPTRANZACTIE = 10 THEN ''NR'' WHEN I.TIPTRANZACTIE = 9 THEN ''NPR'' ELSE I.PrefixDoc END||i.nrdoc||''/''||to_char(i.datadoc,''dd.mm.yyyy'') AS document,
    case when I.TIPTRANZACTIE = 10 THEN ''NR'' WHEN I.TIPTRANZACTIE = 9 THEN ''NPR'' ELSE I.PrefixDoc END,
    i.nrdoc,
    i.datadoc,
    nobj.denumire,
    ig.cant/num1.paritate,
    coalesce(i1.pu,0)*num1.paritate,
    num1.den_um1,
    coalesce(nca.den_clasea,''-''), coalesce(ng.den_gest,''-''), coalesce(ncg.den_claseg,''-''),
    ig.D1,
    ig.D2,
    ig.D3,
    i.schimb,
    f.den_formatie,
    c.prefixdoc||c.nrdoc||''/''||c.datadoc,
    case
      when num.tipum = 1 then ''Kg''
      when num.tipum = 2 then ''Cm3''
      when num.tipum = 3 then ''M2''
      when num.tipum = 4 then ''M''
      when num.tipum = 5 then ''Buc''
    end,
    num.coef,
    PM.Lei,
    MON.SIMBOL,
    case when i.anulat = 1 then ''DA'' else ''NU'' end,
    case when i.operat = 1 then ''DA'' else ''NU'' end,
    UTI.NUME,
    intervserv.denumire,
    utilajobj.denumire,
    ut2c.datastart,
    ut2c.dataend ' || gUserAlias || '
  FROM ig
    INNER JOIN intrari          i          ON i.codintr        = ig.codintr
    INNER JOIN intrari1         i1          ON i1.codintr1      = ig.codintr1
    INNER JOIN nartobj          nobj        ON i1.codobiect     = nobj.codobiect
    INNER JOIN nart                        ON nobj.codarticol  = nart.codarticol
    INNER JOIN num1                        ON i1.umsec         = num1.codum1
    INNER JOIN num                          ON num1.codum       = num.codum
    LEFT  JOIN NECHIV           EKGEN      ON EKGEN.CODOBIECT  = NOBJ.CODOBIECT AND EKGEN.GENERIC = 1
    LEFT  JOIN NARTOBJ          OBJGENK    ON EKGEN.CODOBIECT  = OBJGENK.CODOBIECT
    LEFT  JOIN nclasea          nca        ON nart.clasa       = nca.codclasea
    LEFT  JOIN ngest            ng          ON ng.codgest       = i.codgestprod
    LEFT  JOIN nclaseg          ncg        ON ncg.codclaseg    = ng.codclasa
    LEFT  JOIN nartamb          aa          ON aa.codobiect     = i1.codobiect AND aa.umsec = i1.umsec
    LEFT  JOIN formatii         f          ON f.codformatie    = i.codformatie
    LEFT  JOIN intrprodlink     il          ON il.codintr1      = i1.codintr1 and il.codliniecomanda is not NULL
    LEFT  JOIN cmdprodmat       cp          ON CP.Codcmdprodmat = CODLINIECOMANDA
    LEFT  JOIN comanda1         cl1        ON cl1.codcomanda1  = CP.codcomanda1
    LEFT  JOIN comanda1         ci1        ON ci1.codcomanda1  = i1.codcmdint1
    LEFT  JOIN comanda          c          ON c.codcomanda     = coalesce(cl1.codcomanda,ci1.codcomanda)
    left  join utilaje2c        ut2c        on ut2c.codcomanda1 = ci1.codcomanda1
    left  join utilaje          ut          on ut2c.codutilaj   = ut.codutilaj
    left  join utilaje2         ut2        on ut2.codutilaj2   = ut2c.codutilaj2
    left  join ninterventiiauto interv      on interv.CODINTERVENTIIAUTO = ut2.interventie
    left  join nartobj          intervserv on intervserv.codobiect      = interv.serviciu
    LEFT  JOIN NCLASEINT        CLSINT       ON INTERV.CLASA              = CLSINT.CODCLASEINT
    left  join nartobj          utilajobj  on utilajobj.codobiect       = ut.codobiect
    LEFT  JOIN ca               ca1        ON ca1.nivel = 1 AND ca1.codca = nca.codclasea
    LEFT  JOIN ca               ca2        ON ca2.nivel = 2 AND ca2.codca = nca.codclasea
    LEFT  JOIN ca               ca3        ON ca3.nivel = 3 AND ca3.codca = nca.codclasea
    LEFT  JOIN ca               ca4        ON ca4.nivel = 4 AND ca4.codca = nca.codclasea
    LEFT  JOIN pretm            pm          ON nobj.codobiect = pm.codobiect AND pm.implicit = 1 AND pm.subunitatea = i.subunitatea
    LEFT  JOIN nmonede          mon        ON mon.codmoneda  = pm.moneda
    LEFT  JOIN nartimplicite    nai        ON nai.codarticol = nart.codarticol AND nai.codsubunit = i.subunitatea
    LEFT  JOIN nartobjimp       noi        ON noi.codobiect  = nobj.codobiect  AND noi.codsubunit = i.subunitatea
    LEFT  JOIN ioart1           ioa1        ON ioa1.codioart  = case when coalesce(noi.contimplicit,0) = 0 then nai.contimplicit else coalesce(noi.contimplicit,0) end
                                              AND (i.An*12+i.Luna) BETWEEN ioa1.ALStart and ioa1.ALStop
    LEFT  JOIN ncont            cimpl      ON cimpl.codcont  = (case when nart.tiparticol=0::varchar then ioa1.cont else nart.contserviciu end)
    LEFT  JOIN TMP_UTILIZATOR   UTI         ON I.USERID = UTI.CODUTILIZATOR' || gSuplJoins || '
  ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_np_processlist</obj_name>
  <obj_hashval>0cccaa3dfd47a58f4f8a35dcdd1db6cf</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_np_processlist(tmptable character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar := '';
  sFiltru     varchar := '';
  gSuplCols   varchar :=  'nartobj nobj, num1 num1, nart nart, ngest ng, nartamb aa, formatii f, comanda c, nclasea nca, nclaseg ncg, nclasea ca1, nclasea ca2, nclasea ca3, nclasea ca4, ncont cimpl,NARTOBJ OBJGENK,' || 'ncont contp, comanda1 ci1, comanda1 cc1, comanda cc,LANSARE LANS,prodcomp pc,intrari i,intrari1 i1,nirstoc ns';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
BEGIN
  --Florin 23.11.2023 - fixat 60167
  --Florin 22.11.2023 - sinc. Oracle
  --Florin 21.06.2023 - sinc. Oracle (15.06.2023)
  --Florin 17.06.2022 - sinc. Oracle
  --Adina 05.04.2021 - alstart,alstop
  --Florin 24.02.2021 - noi.codarticol -&gt; noi.codobiect
  --Adina 18.02.2021 - dupa modif.Oracle din 17.02.2021
  --Adina 07.01.2021 tichet 42053
  --Adina 10.12.2020 tichet 41540
  --Adina 04.12.2020 tichet 41422
  --Florin 08.08.2020 ; Adina 12.11.2020 inlocuit last_value
  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 = NAO.CODOBIECT',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_NP.gSuplCols',gSuplCols,false);

  DELETE FROM tmp_manevra_liste WHERE filtru = 'CODNIRSTOC';
  DELETE FROM tmp_manevra_serii;

  IF current_setting('PKG_LIST_SELECTPER.vDataIni', TRUE) = current_setting('PKG_LIST_SELECTPER.vDataFin', TRUE) THEN
    sFiltru := ' AND i.datadoc = TO_DATE(''' || COALESCE(current_setting('PKG_LIST_SELECTPER.vDataIni', TRUE),'') || ''',''dd.mm.yyyy'')';
  ELSE
    sFiltru := ' AND i.datadoc BETWEEN TO_DATE(''' || COALESCE(current_setting('PKG_LIST_SELECTPER.vDataIni', TRUE),'')
      || ''',''dd.mm.yyyy'') AND TO_DATE(''' || COALESCE(current_setting('PKG_LIST_SELECTPER.vDataFin', TRUE),'') || ''',''dd.mm.yyyy'')';
  END IF;

  IF current_setting('PKG_LIST_SELECTPER.vToateArt', TRUE)::NUMERIC = 0 THEN
    sFiltru := coalesce(sFiltru,'') || '
        AND I1.CODOBIECT::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODOBIECT'') ';
  END IF;

  IF current_setting('PKG_LIST_SELECTPER.vToateGest', TRUE)::NUMERIC = 0 THEN
    sFiltru := COALESCE(sFiltru,'') || '
        AND I.CODGESTPROD::varchar IN ( SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODGEST'') ';
  END IF;

  sInsert := 'INSERT INTO ' || TMPTABLE || ' (
      NAV_CODDOC,NAV_TIPDOC,DOCUMENT,PREFIXDOC,NRDOC,DATADOC,DENUMIRE,CANT,PU,UM,CLASA_ART,GEST,CLASA_GEST,
      D1, D2, D3, SERII, SEROBS, SCHIMB, FORMATIE, CMD_INTERNA, UMTRANSF, COEFTRANSF, PRETIMP, MONIMP, ANULAT, OPERAT, OPERATOR, ContPredare, Rest,
      BC_NrDoc, BC_DataDoc, DEZ_INCHIS, BC_NrDocIntr, BC_DataDocIntr ' || gUserFields || ')
    WITH
      CA AS (
      SELECT x.codca CODCLASEA, c.den_clasea, c.simbol, c.prefix, c.nranalitice, c.codparinte,
             c.VERLISTSUPLFACT, c.VERLISTSUPLTOALL, c.CODIDENT, c.VERLISTSUPLAVIZ, c.DISCOFE,
             Row_Number() OVER (PARTITION BY x.CODCA ORDER BY x.nivel) nivel
      FROM (WITH RECURSIVE a (codca, codclasea, simbol, nivel, codparinte) as
              (
               SELECT codclasea codca , codclasea, simbol, nivel, codparinte
               FROM nclasea
                where COALESCE(codparinte, 0) &lt;&gt; 0
               UNION ALL
               SELECT a.codca , c.codclasea, c.simbol, a.nivel, c.codparinte
               FROM nclasea c INNER JOIN a ON a.codparinte = c.codclasea)
            SELECT * from a
      ) x INNER JOIN nclasea c ON c.codclasea = x.codclasea
      UNION ALL
      SELECT c.codclasea cod, c.den_clasea, c.simbol, c.prefix, c.nranalitice, c.codparinte,
             c.VERLISTSUPLFACT, c.VERLISTSUPLTOALL, c.CODIDENT, c.VERLISTSUPLAVIZ, c.DISCOFE,
             c.nivel
      FROM nclasea c
      WHERE Coalesce(codparinte,0) = 0
      ),
      IG AS (
        SELECT
          ns.codnirstoc, i.codintr, i1.codintr1, ns.d1, ns.d2, ns.d3,
          SUM(COALESCE(-l1.cant,nser.cantnir*(CASE WHEN ns.cantnir = 0 THEN 1 ELSE COALESCE(ns.cantfurn,0)/ns.cantnir END),ns.cantfurn) ) cant,
          SUM(COALESCE(-l1.cantum1, nser.cantum1,ns.cantum1)) cantum1,
          SUM(COALESCE(-l1.cantum2, nser.cantum2,ns.cantum2)) cantum2,
          (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,
          CASE MAX(COALESCE(ns.tipserie,0))
            WHEN 1 THEN STRING_AGG(s.serie, '','')
            WHEN 2 THEN STRING_AGG(s.serie||''(~#''||COALESCE(l1.cant,nser.cantnir)||''#~)'', '','')
            ELSE NULL
          END SERII,
          STRING_AGG(nser.obs, '','') SEROBS
        FROM intrari i
          INNER JOIN intrari1 i1   ON i1.codintr   = i.codintr
          LEFT JOIN livr1     l1   ON l1.codintr1  = i1.codintr1
          LEFT JOIN nirstoc   ns   ON ns.codobiect = i1.codobiect
                                      AND ( ((l1.codlivr1 IS NOT NULL) AND (ns.codnirstoc = l1.codnirstoc)) OR ((l1.codlivr1 IS NULL) AND (ns.codintr1 = i1.codintr1)) )
          LEFT JOIN nir       n    ON n.codintr    = i.codintr AND n.codnir = ns.codnir
          LEFT JOIN nirser    nser ON ( ((l1.codlivr1 IS NOT NULL) AND (nser.codnirser = l1.codnirser)) OR ((l1.codlivr1 IS NULL) AND (nser.codnirstoc = ns.codnirstoc)) )
          LEFT JOIN nserii    s    on s.codserie   = nser.codserie
        WHERE i.tipdoc = 7 ' || COALESCE((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL)),'') || coalesce(sFiltru,'') || '
        GROUP BY i.codintr, i1.codintr1, ns.d1, ns.d2, ns.d3, ns.codnirstoc )
    SELECT
      i.codintr,
      i.tipdoc,
      case when I.TIPTRANZACTIE = 10 THEN ''NR'' WHEN I.TIPTRANZACTIE = 9 THEN ''NPR'' ELSE coalesce(I.PrefixDoc,'''') END||coalesce(i.nrdoc::varchar,'''')||''/''||coalesce(to_char(i.datadoc,''dd.mm.yyyy''),'''') AS document,
      case when I.TIPTRANZACTIE = 10 THEN ''NR'' WHEN I.TIPTRANZACTIE = 9 THEN ''NPR'' ELSE coalesce(I.PrefixDoc,'''') END,
      i.nrdoc,
      i.datadoc,
      nobj.denumire,
      ig.cant/num1.paritate,
      COALESCE(i1.pu,0)*num1.paritate,
      num1.den_um1,
      COALESCE(nca.den_clasea,''-''), COALESCE(ng.den_gest,''-''), COALESCE(ncg.den_claseg,''-''),
      ig.D1,
      ig.D2,
      ig.D3,
      ig.SERII,
      ig.SEROBS,
      i.schimb,
      f.den_formatie,
      coalesce(c.prefixdoc,'''')||coalesce(c.nrdoc::varchar,'''')||''/''||coalesce(to_char(c.datadoc,''dd.mm.yyyy''),''''),
      case
        when num.tipum = 1 then ''Kg''
        when num.tipum = 2 then ''Cm3''
        when num.tipum = 3 then ''M2''
        when num.tipum = 4 then ''M''
        when num.tipum = 5 then ''Buc''
      end,
      num.coef,
      PM.Lei,
      MON.SIMBOL,
      case when i.anulat = 1 then ''DA'' else ''NU'' end,
      case when i.operat = 1 then ''DA'' else ''NU'' end,
      UT.NUME,
      CONTP.Simbol,
      cp.rest,
      DEZ.BC_NrDoc, DEZ.BC_DataDoc, case when dez.inchisa = 0 then ''NU'' else ''DA'' end DEZ_INCHIS, DEZ.BC_NrDocIntr, DEZ.BC_DataDocIntr ' || gUserAlias || '
    FROM ig
      INNER JOIN intrari        i       ON i.codintr         = ig.codintr
      INNER JOIN intrari1       i1      ON i1.codintr1       = ig.codintr1
      INNER JOIN nartobj        nobj    ON i1.codobiect      = nobj.codobiect
      INNER JOIN nart                   ON nobj.codarticol   = nart.codarticol
      INNER JOIN num1                   ON i1.umsec          = num1.codum1
      INNER JOIN num                    ON num1.codum        = num.codum
      INNER JOIN NIRSTOC        NS      ON NS.CODINTR1       = I1.CODINTR1 and ns.codnirstoc = ig.codnirstoc
      INNER JOIN IOART1         IO1     ON IO1.CODIOART1     = (SELECT PKG_CONFIGART_GETCODCARACTLUNA.wme_result FROM PKG_CONFIGART_GETCODCARACTLUNA(NULL, NS.CODIOART, I.AN, I.LUNA))::numeric
      INNER JOIN NCONT          CONTP   ON CONTP.CODCONT     = IO1.CONT
      LEFT  JOIN NECHIV         EKGEN   ON EKGEN.CODOBIECT   = NOBJ.CODOBIECT AND EKGEN.GENERIC = 1
      LEFT  JOIN NARTOBJ        OBJGENK ON EKGEN.CODOBIECT   = OBJGENK.CODOBIECT
      LEFT  JOIN nclasea        nca     ON nart.clasa        = nca.codclasea
      LEFT  JOIN ngest          ng      ON ng.codgest        = i.codgestprod
      LEFT  JOIN nclaseg        ncg     ON ncg.codclaseg     = ng.codclasa
      LEFT  JOIN nartamb        aa      ON aa.codobiect      = i1.codobiect AND aa.umsec = i1.umsec
      LEFT  JOIN formatii       f       ON f.codformatie     = i.codformatie
      LEFT  JOIN intrprodlink   il      ON il.codintr1       = i1.codintr1 and il.codliniecomanda is not NULL
      LEFT  JOIN cmdprodmat     cp      ON CP.Codcmdprodmat  = il.CODLINIECOMANDA
      LEFT  JOIN comanda1       cl1     ON cl1.codcomanda1   = CP.codcomanda1
      LEFT  JOIN comanda1       ci1     ON ci1.codcomanda1   = i1.codcmdint1
      left  join prodcomp       pc      on ci1.codreteta     = pc.codprodcomp
      LEFT  JOIN comanda        c       ON c.codcomanda      = COALESCE(cl1.codcomanda,ci1.codcomanda)
      LEFT  JOIN COMANDA1       CC1     ON CC1.CODCOMANDA1   = (SELECT PKG_COMANDA_DinCmdCli.wme_result FROM PKG_COMANDA_DinCmdCli(NULL,CI1.CodComanda1))::numeric
      LEFT  JOIN COMANDA        CC      ON CC.CODCOMANDA     = CC1.CODCOMANDA
      LEFT  JOIN ca             ca1     ON ca1.nivel         = 1 AND ca1.codclasea = nca.codclasea
      LEFT  JOIN ca             ca2     ON ca2.nivel         = 2 AND ca2.codclasea = nca.codclasea
      LEFT  JOIN ca             ca3     ON ca3.nivel         = 3 AND ca3.codclasea = nca.codclasea
      LEFT  JOIN ca             ca4     ON ca4.nivel         = 4 AND ca4.codclasea = nca.codclasea
      LEFT  JOIN pretm          pm      ON nobj.codobiect    = pm.codobiect AND pm.implicit = 1 AND pm.subunitatea = i.subunitatea
      LEFT  JOIN nmonede        mon     ON mon.codmoneda     = pm.moneda
      LEFT  JOIN nartimplicite  nai     ON nai.codarticol    = nart.codarticol AND nai.codsubunit = i.subunitatea
      LEFT  JOIN nartobjimp     noi     ON noi.codobiect     = nobj.codobiect AND noi.codsubunit = i.subunitatea
      LEFT  JOIN ioart1         ioa1    ON ioa1.codioart     = case when coalesce(noi.contimplicit,0) = 0 then nai.contimplicit else coalesce(noi.contimplicit,0) end
                                           AND (i.An*12+i.Luna) BETWEEN ioa1.ALStart and ioa1.ALStop
      LEFT  JOIN ncont          cimpl   ON cimpl.codcont     = (Case  When nart.tiparticol::numeric=0 then ioa1.cont else nart.contserviciu end)
      LEFT  JOIN TMP_UTILIZATOR UT      ON I.USERID          = UT.CODUTILIZATOR
      LEFT  JOIN LANSARE1       LANS1   ON LANS1.CODCMD1     = CI1.CODCOMANDA1
      LEFT  JOIN LANSARE        LANS    ON LANS1.CODLANSARE  = LANS.CODLANSARE
      LEFT  JOIN (select distinct ies.nrdoc BC_NrDoc, ies.datadoc BC_DataDoc, COALESCE(dz.inchisa,0) inchisa, int.nrdoc BC_NrDocIntr, int.datadoc BC_DataDocIntr,
                        i.codintr
                  from intrari i
                      inner join intrari1      i1   on i1.codintr      = i.codintr
                      inner join dezasamblari1 dz1  on dz1.codintrlink = i.codintr
                      left  join dezasamblari  dz   on dz.codlivr1     = dz1.codlivr1
                      left  join livr1         l1   on l1.codlivr1     = dz.codlivr1
                      left  join livr          l    on l.codlivr       = l1.codlivr
                      left  join iesiri1       ies1 on ies1.codies1    = l1.codies1
                      left  join iesiri        ies  on ies.codies      = l.codies and ies.codies = ies1.codies
                      left  join nirstoc1      ns1  on dz.codnirstoc   = ns1.codnirstoc
                      left  join nirstoc       nso  on nso.codnirstoc  = ns1.codnirstocorig
                      left  join intrari1      int1 on nso.codintr1    = int1.codintr1
                      left  join intrari       int  on int.codintr     = int1.codintr
                  where i.tipdoc = 7 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL)),'') || coalesce(sFiltru,'') || '
                 ) DEZ on DEZ.codintr = i.codintr ' || coalesce(gSuplJoins,'') || '
  ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);

  sInsert := 'INSERT INTO ' || TMPTABLE || ' (
    NAV_CODDOC,NAV_TIPDOC,DOCUMENT,PREFIXDOC,NRDOC,DATADOC,DENUMIRE,CANT,PU,UM,CLASA_ART,GEST,CLASA_GEST,
    D1, D2, D3, SERII, SEROBS, SCHIMB, FORMATIE, CMD_INTERNA, UMTRANSF, COEFTRANSF, PRETIMP, MONIMP, ANULAT, OPERAT, OPERATOR, ContPredare, Rest ' || gUserFields || ')
    WITH
      CA AS (
        SELECT c.codca, c.codclasea, c.den_clasea, c.prefix, c.nivel, c.nranalitice, c.codparinte, c.verlistsuplfact, c.verlistsupltoall,
        CASE WHEN cp.simbol IS NULL THEN c.simbol ELSE SubStr(c.simbol,Length(cp.simbol)+2) END SIMBOL,
        c.CODIDENT, c.VERLISTSUPLAVIZ, c.DISCOFE
        FROM (WITH RECURSIVE a (codca, codclasea, den_clasea, prefix, nivel, nranalitice, codparinte, verlistsuplfact, verlistsupltoall, simbol) as
              (
               SELECT codclasea codca , codclasea, den_clasea, prefix, nivel, nranalitice, codparinte, verlistsuplfact, verlistsupltoall, simbol, CODIDENT, VERLISTSUPLAVIZ, DISCOFE
               FROM nclasea
               UNION ALL
               SELECT a.codca , n.codclasea, n.den_clasea, n.prefix, n.nivel, n.nranalitice, n.codparinte, n.verlistsuplfact, n.verlistsupltoall, n.simbol, n.CODIDENT, n.VERLISTSUPLAVIZ, n.DISCOFE
               FROM nclasea n INNER JOIN a ON a.codparinte = n.codclasea
              )
              SELECT * from a
             ) c LEFT JOIN nclasea cp ON cp.codclasea = c.codparinte
      ),
      IG AS (
        SELECT
          ns.codnirstoc, i.codintr, i1.codintr1, ns.d1, ns.d2, ns.d3, l1.codlivr1,
          COALESCE(-l1.cant,nser.cantnir*(CASE WHEN ns.cantnir = 0 THEN 1 ELSE COALESCE(ns.cantfurn,0)/ns.cantnir END),ns.cantfurn) cant,
          COALESCE(-l1.cantum1, nser.cantum1,ns.cantum1) cantum1,
          COALESCE(-l1.cantum2, nser.cantum2,ns.cantum2) cantum2,
          (Case  When COALESCE(ns.tipserie,0)=1 then ''serie pe bucata'' When COALESCE(ns.tipserie,0)=2 then ''serie pe lot'' else ''fara serie'' end) tipserie,
          CASE COALESCE(ns.tipserie,0)
            WHEN 1 THEN s.serie
            WHEN 2 THEN s.serie
            ELSE NULL
          END SERII,
          nser.obs SEROBS,
          ns.pret - COALESCE(ns.adaos,0) pret
        FROM intrari i
          INNER JOIN intrari1 i1   ON i1.codintr   = i.codintr
          LEFT  JOIN livr1    l1   ON l1.codintr1  = i1.codintr1
          LEFT  JOIN nirstoc  ns   ON ns.codobiect = i1.codobiect AND ( ((l1.codlivr1 IS NOT NULL) AND (ns.codnirstoc = l1.codnirstoc)) OR ((l1.codlivr1 IS NULL) AND (ns.codintr1 = i1.codintr1)) )
          LEFT  JOIN nir      n    ON n.codintr    = i.codintr AND n.codnir = ns.codnir
          LEFT  JOIN nirser   nser ON ( ((l1.codlivr1 IS NOT NULL) AND (nser.codnirser = l1.codnirser)) OR ((l1.codlivr1 IS NULL) AND (nser.codnirstoc = ns.codnirstoc)) )
          LEFT  JOIN nserii   s    on s.codserie   = nser.codserie
        WHERE i.tipdoc = 7 ' || coalesce((SELECT PKG_LIST_BASE_UTILS_COND_SUBUNIT.WME_RESULT FROM PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'I',NULL,NULL,NULL)),'') || coalesce(sFiltru,'') || '
    )
    SELECT
      i.codintr,
      i.tipdoc,
      case when I.TIPTRANZACTIE = 10 THEN ''NR'' WHEN I.TIPTRANZACTIE = 9 THEN ''NPR'' ELSE coalesce(I.PrefixDoc,'''') END||coalesce(i.nrdoc::varchar,'''')||''/''||coalesce(to_char(i.datadoc,''dd.mm.yyyy''),'''') AS document,
      case when I.TIPTRANZACTIE = 10 THEN ''NR'' WHEN I.TIPTRANZACTIE = 9 THEN ''NPR'' ELSE coalesce(I.PrefixDoc,'''') END,
      i.nrdoc,
      i.datadoc,
      nobj.denumire,
      ig.cant/num1.paritate,
      COALESCE(ig.pret,0)*num1.paritate,
      num1.den_um1,
      COALESCE(nca.den_clasea,''-''), COALESCE(ng.den_gest,''-''), COALESCE(ncg.den_claseg,''-''),
      ig.D1,
      ig.D2,
      ig.D3,
      ig.SERII,
      ig.SEROBS,
      i.schimb,
      f.den_formatie,
      coalesce(c.prefixdoc,'''')||coalesce(c.nrdoc::varchar,'''')||''/''||coalesce(to_char(c.datadoc,''dd.mm.yyyy''),''''),
      case
        when num.tipum = 1 then ''Kg''
        when num.tipum = 2 then ''Cm3''
        when num.tipum = 3 then ''M2''
        when num.tipum = 4 then ''M''
        when num.tipum = 5 then ''Buc''
      end,
      num.coef,
      PM.Lei,
      MON.SIMBOL,
      case when i.anulat = 1 then ''DA'' else ''NU'' end,
      case when i.operat = 1 then ''DA'' else ''NU'' end,
      UT.NUME,
      CONTP.Simbol,
      cp.rest ' || gUserAlias || '
    FROM ig
      INNER JOIN intrari        i       ON i.codintr         = ig.codintr
      INNER JOIN intrari1       i1      ON i1.codintr1       = ig.codintr1
      INNER JOIN nartobj        nobj    ON i1.codobiect      = nobj.codobiect
      INNER JOIN nart                   ON nobj.codarticol   = nart.codarticol
      INNER JOIN num1                   ON i1.umsec          = num1.codum1
      INNER JOIN num                    ON num1.codum        = num.codum
      INNER JOIN LIVR                   ON I.CODINTR         = LIVR.CODINTR
      INNER JOIN LIVR1                  ON LIVR1.CODLIVR     = LIVR.CODLIVR AND LIVR1.CODINTR1 = I1.CODINTR1 and ig.codlivr1 = livr1.codlivr1
      INNER JOIN NIRSTOC        NS      ON NS.CODNIRSTOC     = LIVR1.CODNIRSTOC and ns.codnirstoc = ig.codnirstoc
      INNER JOIN IOART1         IO1     ON IO1.CODIOART1     = (SELECT PKG_CONFIGART_GETCODCARACTLUNA.wme_result FROM PKG_CONFIGART_GETCODCARACTLUNA(NULL, NS.CODIOART, I.AN, I.LUNA))::numeric
      INNER JOIN NCONT          CONTP   ON CONTP.CODCONT     = IO1.CONT
      LEFT  JOIN NECHIV         EKGEN   ON EKGEN.CODOBIECT   = NOBJ.CODOBIECT AND EKGEN.GENERIC = 1
      LEFT  JOIN NARTOBJ        OBJGENK ON EKGEN.CODOBIECT   = OBJGENK.CODOBIECT
      LEFT  JOIN nclasea        nca     ON nart.clasa        = nca.codclasea
      LEFT  JOIN ngest          ng      ON ng.codgest        = i.codgestprod
      LEFT  JOIN nclaseg        ncg     ON ncg.codclaseg     = ng.codclasa
      LEFT  JOIN nartamb        aa      ON aa.codobiect      = i1.codobiect AND aa.umsec = i1.umsec
      LEFT  JOIN formatii       f       ON f.codformatie     = i.codformatie
      LEFT  JOIN intrprodlink   il      ON il.codintr1       = i1.codintr1 and il.codliniecomanda is not NULL
      LEFT  JOIN cmdprodmat     cp      ON CP.Codcmdprodmat  = il.CODLINIECOMANDA
      LEFT  JOIN comanda1       cl1     ON cl1.codcomanda1   = CP.codcomanda1
      LEFT  JOIN comanda1       ci1     ON ci1.codcomanda1   = i1.codcmdint1
      left  join prodcomp       pc      on ci1.codreteta     = pc.codprodcomp
      LEFT  JOIN comanda        c       ON c.codcomanda      = COALESCE(cl1.codcomanda,ci1.codcomanda)
      LEFT  JOIN COMANDA1       CC1     ON CC1.CODCOMANDA1   = (SELECT PKG_COMANDA_DinCmdCli.wme_result FROM PKG_COMANDA_DinCmdCli(NULL,CI1.CodComanda1))::numeric
      LEFT  JOIN COMANDA        CC      ON CC.CODCOMANDA     = CC1.CODCOMANDA
      LEFT  JOIN ca             ca1     ON ca1.nivel         = 1 AND ca1.codclasea = nca.codclasea
      LEFT  JOIN ca             ca2     ON ca2.nivel         = 2 AND ca2.codclasea = nca.codclasea
      LEFT  JOIN ca             ca3     ON ca3.nivel         = 3 AND ca3.codclasea = nca.codclasea
      LEFT  JOIN ca             ca4     ON ca4.nivel         = 4 AND ca4.codclasea = nca.codclasea
      LEFT  JOIN pretm          pm      ON nobj.codobiect    = pm.codobiect AND pm.implicit = 1 AND pm.subunitatea = i.subunitatea
      LEFT  JOIN nmonede        mon     ON mon.codmoneda     = pm.moneda
      LEFT  JOIN nartimplicite  nai     ON nai.codarticol    = nart.codarticol AND nai.codsubunit = i.subunitatea
      LEFT  JOIN nartobjimp     noi     ON noi.codobiect     = nobj.codobiect AND noi.codsubunit = i.subunitatea
      LEFT  JOIN ioart1         ioa1    ON ioa1.codioart     = case when coalesce(noi.contimplicit,0) = 0 then nai.contimplicit else coalesce(noi.contimplicit,0) end
                                           AND (i.An*12+i.Luna) BETWEEN ioa1.ALStart and ioa1.ALStop
      LEFT  JOIN ncont          cimpl   ON cimpl.codcont     = (Case  When nart.tiparticol::numeric=0 then ioa1.cont else nart.contserviciu end)
      LEFT  JOIN TMP_UTILIZATOR UT      ON I.USERID          = UT.CODUTILIZATOR
      LEFT  JOIN LANSARE1       LANS1   ON LANS1.CODCMD1     = CI1.CODCOMANDA1
      LEFT  JOIN LANSARE        LANS    ON LANS1.CODLANSARE  = LANS.CODLANSARE' || gSuplJoins || '
  ';
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert, aListID, aListVer);
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_raportgestcval_processlist</obj_name>
  <obj_hashval>96fd3ebe6b647a1a0f9c9ee1e0b3b42b</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_raportgestcval_processlist(tmpname character varying, alistid numeric, alistver numeric)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert     varchar :='';
  sSelect     varchar :='';
  sDataIni    varchar := coalesce(to_char((SELECT WME_RESULT FROM PKG_LIST_SELECTGEST2_ZiuaIni(NULL,NULL)), 'fm00'),'') || '.' || coalesce(to_char(getlunalucru(), 'fm00'),'') || '.' || coalesce(to_char(getanlucru(), 'fm0000'),'');
  sDataFin    varchar := coalesce(to_char((SELECT WME_RESULT FROM PKG_LIST_SELECTGEST2_ZiuaFin(NULL,NULL)), 'fm00'),'') || '.' || coalesce(to_char(getlunalucru(), 'fm00'),'') || '.' || coalesce(to_char(getanlucru(), 'fm0000'),'');
  sCondData   varchar :='';
  sCondIOArt  varchar :='';
  gSuplCols   varchar := 'NGEST NG, NPERS OPER';
  gUserFields VARCHAR := '';
  gUserAlias  VARCHAR := '';
  gNullAlias  VARCHAR := '';
  gSuplJoins  VARCHAR := '';
  vGestAcces  INTEGER;
  pGest       VARCHAR(500);
BEGIN
  --Florin 17.01.2023 - sinc. Oracle
  --Florin 21.06.2022 - sinc. Oracle
  --Florin 02.06.2022 - sinc. Oracle
  --Florin 07.07.2021 - sinc Oracle (38139)
  --Adina 07.04.2021 - alstart,alstop
  --Adina 02.12.2020 tichet 41388
  --Adina iulie 2020
   vGestAcces := to_number(Coalesce(fnc_getvalconstantalucru('GestAccesListeStoc'),'2'));
   if vGestAcces &lt;&gt; 1 THEN
     pGest := ' AND (select wme_result from PKG_NOMGEST_GESTIUNE_DEDICATA(null, NG.CODGEST)) &gt; 0 ';
   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_RAPORTGESTCVAL.gSuplCols',gSuplCols,false);

   IF  (SELECT WME_RESULT FROM PKG_LIST_SELECTGEST2_ZiuaIni(NULL,NULL)) = (SELECT WME_RESULT FROM PKG_LIST_SELECTGEST2_ZiuaFin(NULL,NULL))
   THEN sCondData := ' = to_date(''' || coalesce(sDataIni,'') || ''',''DD.MM.YYYY'') ';
   ELSE sCondData := ' BETWEEN to_date(''' || coalesce(sDataIni,'') || ''',''DD.MM.YYYY'') AND to_date(''' || coalesce(sDataFin,'') || ''',''DD.MM.YYYY'') ';
   END IF;

    IF  NOT (SELECT WME_RESULT FROM PKG_LIST_SELECTGEST2_ToateIOART(NULL,NULL)) THEN
      sCondIOArt := '
          AND IO.CODIOART::varchar IN (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'')';
    ELSE
      IF NOT COALESCE(AccesGranted(current_setting('PKG_GLOBALS.USERID', true)::NUMERIC,'BLIND'),0) &gt; 0 THEN
        sCondIOArt := '
          AND IO1.DIFPRET = 1 ';
      END IF;
    END IF;

   sInsert :=
    'INSERT INTO '||tmpName||' (
        NAV_CodDoc, NAV_TipDoc, PrefixDoc, NrDoc, DataDoc, DataNirLivr, Document, TipDoc, PROVSI,
        AdDebit, ValDFTVA, ValDCTVA, TVAD, PROVD,
        AdCredit, ValCFTVA, ValCCTVA, TVAC, PROVC,
        SoldFinFTVA, SoldFinCTVA, SoldAd,
        SursaDest, DenIOART, SoldIn, AchizIn, Coef,
        DenGest, DenCONT, SimbCONT, RecLivr, Zi, ZiDoc '||gUserFields||' )';

   sSelect := '
      WITH
       IOA1 AS
       (
        SELECT IO.CODIOART, IO.DEN_IOART, NC.DEN_CONT, NC.SIMBOL SIMB_CONT
        FROM IOART1 IO1
             join IOART IO       on IO.CODIOART = IO1.CODIOART AND '||getAnLunaLucru()::varchar||' BETWEEN IO1.ALStart and IO1.ALStop '||sCondIOArt||'
             left join  NCONT NC on NC.CODCONT  = IO1.CONT
       ),
       SM AS
       (
        SELECT N.GEST, NS_pg0.CODIOART, Coalesce(NS_pg0.TVA,0) TVA, NSM.REST * NS_pg0.PRET SOLD, NSM.REST * NS_pg0.ADAOS ADAOS, NS_pg0.CANTNIR * NS_pg0.PRET SOLDINTR, NS_pg0.CANTNIR * NS_pg0.ADAOS ADAOSINTR, NULL USERID, Coalesce(NSM.REST * NS_pg0.PROVIZION,0) PROVSI
        FROM (
              SELECT   CODNIRSTOC, SUM (REST) REST
              FROM (
                    SELECT CODNIRSTOC, REST
                    FROM NIRLUNA
                    WHERE (AN * 12 + LUNA + 1) = '||getAnLunaLucru()::varchar||'
                   union all
                    SELECT NS_pg1.CODNIRSTOC, NS_pg1.CANTNIR REST
                    FROM NIRSTOC NS_pg1
                         INNER JOIN NIR N     ON N.CODNIR  = NS_pg1.CODNIR
                         INNER JOIN INTRARI I ON I.CODINTR = N.CODINTR
                    WHERE I.TIPDOC IN (1, 2, 3, 4, 5, 6, 7) AND I.ANULAT = 0 AND I.OPERAT = 1
                          AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
                          AND N.DATANIR &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'')
                   union all
                    SELECT NS_pg2.CODNIRSTOC, NS_pg2.CANTNIR REST
                    FROM NIRSTOC NS_pg2
                         INNER JOIN NIR    N ON N.CODNIR    = NS_pg2.CODNIR
                         INNER JOIN TRANSF T ON T.CODTRANSF = N.CODTRANSF
                    WHERE T.TIPDOC IN (12, 13) AND T.ANULAT = 0 AND T.OPERAT = 1 AND N.OPERAT = 1
                          AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
                          AND N.DATANIR &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'')
                   union all
                    SELECT L1.CODNIRSTOC, - L1.CANT REST
                    FROM LIVR1 L1
                         INNER JOIN LIVR    L ON L.CODLIVR = L1.CODLIVR
                         INNER JOIN INTRARI I ON I.CODINTR = L.CODINTR
                    WHERE I.TIPDOC IN (1, 2, 3, 4, 5, 6, 7) AND I.OPERAT = 1 AND I.ANULAT = 0
                          AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
                          AND L.DATALIVR &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'')
                   union all
                    SELECT L1.CODNIRSTOC, - L1.CANT REST
                    FROM LIVR1 L1
                         INNER JOIN LIVR   L ON L.CODLIVR   = L1.CODLIVR
                         INNER JOIN TRANSF T ON T.CODTRANSF = L.CODTRANSF
                    WHERE T.TIPDOC IN (12, 13) AND T.OPERAT = 1 AND T.ANULAT = 0
                          AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
                          AND L.DATALIVR &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'')
                   union all
                    SELECT L1.CODNIRSTOC, (case when I.TIPDOC=15 then 1 else -1 end) * L1.CANT REST
                    FROM LIVR1 L1
                         INNER JOIN LIVR L ON L.CODLIVR = L1.CODLIVR
                         INNER JOIN IESIRI I ON I.CODIES = L.CODIES
                    WHERE I.TIPDOC IN (14, 15, 16, 19, 20, 21, 22, 23, 24) AND I.OPERAT = 1 AND I.ANULAT = 0
                          AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
                          AND L.DATALIVR &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'')
                   ) a_pg
              GROUP BY CODNIRSTOC
             ) NSM
               INNER JOIN NIRSTOC NS_pg0 ON NS_pg0.CODNIRSTOC = NSM.CODNIRSTOC
               INNER JOIN NIR     N      ON N.CODNIR = NS_pg0.CODNIR
               INNER JOIN NGEST G ON G.CODGEST = N.GEST '||coalesce((select wme_result from pkg_list_base_raportgestCval_JOINTMP('','N.GEST'))::varchar,'')||'
        UNION ALL -- STOC INI. VALORIC
        SELECT GEST, CODIOART, TVA, SOLD, ADAOS, SOLDINTR, ADAOSINTR, NULL USERID, 0 PROVSI
        FROM STOCVALLUNA SVL '||coalesce((select wme_result from pkg_list_base_raportgestCval_JOINTMP('','SVL.GEST'))::varchar,'')||'
        WHERE (AN * 12 + LUNA + 1)= '||getAnLunaLucru()::varchar||'
        UNION ALL -- LIVRARI VALORICE
        SELECT LV.GEST, LV.CODIOART, Coalesce(LV.TVANEEX, 0) TVA, - LV.PRETINREG * L1.CANT SOLD, - (LV.PRETINREG - LV.PRETACHIZ) * L1.CANT ADAOS, 0 SOLDINTR, 0 ADAOSINTR, NULL USERID, 0 PROVSI
        FROM LIVRVAL LV '||coalesce((select wme_result from pkg_list_base_raportgestCval_JOINTMP('','LV.GEST'))::varchar,'')||'
             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
        WHERE I.TIPDOC IN (1, 2, 3, 4, 5, 6, 7) AND I.OPERAT = 1 AND I.ANULAT = 0
              AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
              AND L.DATALIVR &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'')
        UNION ALL -- LIVRARI VALORICE
        SELECT LV.GEST, LV.CODIOART, Coalesce(LV.TVANEEX, 0) TVA, - LV.PRETINREG * L1.CANT SOLD, - (LV.PRETINREG - LV.PRETACHIZ) * L1.CANT ADAOS, 0 SOLDINTR, 0 ADAOSINTR, NULL USERID, 0 PROVSI
        FROM LIVRVAL LV '||coalesce((select wme_result from pkg_list_base_raportgestCval_JOINTMP('','LV.GEST'))::varchar,'')||'
             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
        WHERE T.TIPDOC IN (12, 13) AND T.OPERAT = 1 AND T.ANULAT = 0
              AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
              AND L.DATALIVR &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'')
        UNION ALL -- LIVRARI VALORICE
        SELECT LV.GEST, LV.CODIOART, Coalesce(LV.TVANEEX, 0) TVA,
          (case when I.TIPDOC=15 then 1 else -1 end) * LV.PRETINREG * L1.CANT SOLD, (case when I.TIPDOC=15 then 1 else -1 end) * (LV.PRETINREG - LV.PRETACHIZ) * L1.CANT ADAOS,
          (case when I.TIPDOC=15 then LV.PRETINREG * L1.CANT else 0 end) SOLDINTR, (case when I.TIPDOC=15 then (LV.PRETINREG - LV.PRETACHIZ) * L1.CANT else 0 end) ADAOSINTR, NULL USERID, 0 PROVSI
        FROM LIVRVAL LV '||coalesce((select wme_result from pkg_list_base_raportgestCval_JOINTMP('','LV.GEST'))::varchar,'')||'
             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
        WHERE I.TIPDOC IN (14, 15, 16, 19, 20, 21, 22, 23, 24) AND I.OPERAT = 1 AND I.ANULAT = 0
              AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
              AND L.DATALIVR &lt; to_date('''||sDataIni||''',''DD.MM.YYYY'')
      ) --END WITH
      SELECT
        NULL CodDoc, NULL TipDoc, '' '' PrefixDoc, NULL NrDoc, to_date('''||sDataIni||''',''DD.MM.YYYY'') DataDoc, to_date('''||sDataIni||''',''DD.MM.YYYY'') DATANIRLIVR, ''Sold initial'' Doc, '' '' TipDoc,  SUM(SM.PROVSI),
        0 AdDebit,  0 ValDFTva, 0 ValDCTva, 0 TVAD, 0 PROVD,
        0 AdCredit, 0 ValCFTva, 0 ValCCTva, 0 TvaC, 0 PROVC,
        SUM(SM.SOLD / (1+SM.TVA)) SoldFinFTva, SUM(SM.SOLD) SoldFinCTva, SUM(SM.ADAOS - SM.SOLD*Coalesce(SM.TVA,0)/Coalesce(1+SM.TVA,1)) SoldAd,
        NULL SursaDest, IOA1.DEN_IOART,
        SUM(SM.SOLDINTR) SoldIn, SUM(SM.SOLDINTR - SM.ADAOSINTR) AchizIn,
        (case when SUM(SM.SOLDINTR - SM.ADAOSINTR)=0 then 0 else SUM(SM.SOLDINTR) / SUM(SM.SOLDINTR - SM.ADAOSINTR) end) Coef,
        NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
        NULL RecLivr, 0 Zi, 0 ZiDoc '||gUserAlias||'
      FROM SM
        INNER JOIN IOA1      ON IOA1.CODIOART = SM.CODIOART
        INNER JOIN NGEST NG  ON NG.CODGEST    = SM.GEST '||
        coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG','CODSUBUNIT',NULL,NULL))::varchar,'')||'
        LEFT JOIN NPERS OPER ON OPER.LOGONNAME::varchar = SM.USERID'||
        gSuplJoins||'
      WHERE 1 = 1 '||pGest||'
      GROUP BY NG.DEN_GEST, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT'||gUserAlias||'
      UNION ALL -- INTRARI
      SELECT
        I.CODINTR CodDoc, I.TIPDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC, N.DATANIR DATANIRLIVR,
      --i.prefixdoc ||i.seriadoc||i.nrdoc ||''/''||to_char(i.datadoc,''dd.mm.yyyy'') Doc,
        coalesce(i.prefixdoc,'''') ||coalesce(i.seriadoc,'''')||coalesce(i.nrdoc::varchar,'''') ||''/''||coalesce(to_char(i.datadoc,''dd.mm.yyyy''),'''') Doc,
        coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',I.TIPDOC)),''''), 0 PROVSI,
        SUM(NS_pg3.CANTNIR * (NS_pg3.ADAOS - NS_pg3.PRET * Coalesce(NS_pg3.TVA,0) / Coalesce(1+NS_pg3.TVA,1) )) AdDebit, SUM(NS_pg3.CANTNIR * NS_pg3.PRET / Coalesce(1+NS_pg3.TVA,1)) ValDFTva, SUM(NS_pg3.CANTNIR * NS_pg3.PRET) ValDCTva,
        SUM(NS_pg3.CANTNIR * NS_pg3.PRET * Coalesce(NS_pg3.TVA,0) / Coalesce(1+NS_pg3.TVA,1)) TVAD, SUM(NS_pg3.CANTNIR * Coalesce(NS_pg3.PROVIZION,0)) PROVD,
        0 AdCredit, 0 ValCFTva, 0 ValCCTva, 0 TvaC, 0 PROVC,
        SUM(NS_pg3.CANTNIR * NS_pg3.PRET / Coalesce(1+NS_pg3.TVA,1)) SoldFinFTva, SUM(NS_pg3.CANTNIR * NS_pg3.PRET) SoldFinCTva, 0 SoldAd,
        (case when I.TIPDOC=6 then S.DEN_SUBUNIT when I.TIPDOC=7 then G.DEN_GEST else NP.DEN_PART end) SursaDest, IOA1.DEN_IOART,
        SUM(NS_pg3.CANTNIR * NS_pg3.PRET) SoldIn, SUM(NS_pg3.CANTNIR * (NS_pg3.PRET - NS_pg3.ADAOS)) AchizIn,
        (case when SUM(NS_pg3.CANTNIR * (NS_pg3.PRET - NS_pg3.ADAOS))=0 then 0 else SUM(NS_pg3.CANTNIR * NS_pg3.PRET) / SUM(NS_pg3.CANTNIR * (NS_pg3.PRET - NS_pg3.ADAOS)) end) Coef,
        NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
        N.NRNIR||''/''||to_char(N.DATANIR,''dd.mm.yyyy'') RecLivr, TO_CHAR(N.DATANIR,''DD'')::numeric Zi, TO_CHAR(I.DATADOC,''DD'')::numeric ZiDoc '||gUserAlias||'
      FROM NIRSTOC NS_pg3
        INNER JOIN IOA1          ON IOA1.CODIOART  = NS_pg3.CODIOART
        INNER JOIN NIR      N    ON N.CODNIR       = NS_pg3.CODNIR'||coalesce((select wme_result from pkg_list_base_raportgestCval_JOINTMP('','N.GEST'))::varchar,'')||'
        INNER JOIN NGEST    NG   ON NG.CODGEST     = N.GEST '|| coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG','CODSUBUNIT',NULL,NULL))::varchar,'')||'
        INNER JOIN INTRARI  I    ON I.CODINTR      = N.CODINTR
        LEFT  JOIN NPART    NP   ON NP.CODPART     = I.PARTENER
        LEFT  JOIN NGEST    G    ON G.CODGEST      = I.CODGESTPROD
        LEFT  JOIN NSUBUNIT S    ON S.CODSUBUNIT   = I.CODSUBUNIT
        LEFT  JOIN NPERS    OPER ON OPER.LOGONNAME = I.USERID'||
        gSuplJoins||'
      WHERE I.TIPDOC IN (1, 2, 3, 4, 5, 6, 7) AND I.ANULAT = 0 AND I.OPERAT = 1'||pGest||'
        AND N.DATANIR'||sCondData||'
        AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
      GROUP BY I.CODINTR, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC, N.NRNIR, N.DATANIR, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST, NP.DEN_PART, S.DEN_SUBUNIT, G.DEN_GEST'||gUserAlias||'
      UNION ALL -- INTRARI DIN TRANSFERURI
      SELECT
        T.CODTRANSF CodDoc, T.TIPDOC, T.PREFIXDOC, T.NRDOC, T.DATADOC, N.DATANIR DATANIRLIVR,
      --t.prefixdoc ||t.seriadoc||t.nrdoc||''/''||to_char(t.datadoc,''dd.mm.yyyy'') Doc,
        coalesce(t.prefixdoc,'''') ||coalesce(t.seriadoc,'''')||coalesce(t.nrdoc::varchar,'''')||''/''||coalesce(to_char(t.datadoc,''dd.mm.yyyy''),'''') Doc,
        coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',T.TIPDOC)),''''), 0 PROVSI,
        SUM(NS_pg4.CANTNIR * (NS_pg4.ADAOS - NS_pg4.PRET * Coalesce(NS_pg4.TVA,0) / Coalesce(1+NS_pg4.TVA,1) )) AdDebit, SUm(NS_pg4.CANTNIR * NS_pg4.PRET / Coalesce(1+NS_pg4.TVA,1)) ValDFTva, SUM(NS_pg4.CANTNIR * NS_pg4.PRET) ValDCTva,
        SUM(NS_pg4.CANTNIR * NS_pg4.PRET * Coalesce(NS_pg4.TVA,0) / Coalesce(1+NS_pg4.TVA,1)) TVAD, SUM(NS_pg4.CANTNIR * Coalesce(NS_pg4.PROVIZION,0)) PROVD,
        0 AdCredit, 0 ValCFTva, 0 ValCCTva, 0 TvaC, 0 PROVC,
        SUM(NS_pg4.CANTNIR * NS_pg4.PRET / Coalesce(1+NS_pg4.TVA,1)) SoldFinFTva, SUM(NS_pg4.CANTNIR * NS_pg4.PRET) SoldFinCTva, 0 SoldAd,
        NG_S.DEN_GEST SursaDest, IOA1.DEN_IOART,
        SUM(NS_pg4.CANTNIR * NS_pg4.PRET) SoldIn, SUM(NS_pg4.CANTNIR * (NS_pg4.PRET - NS_pg4.ADAOS)) AchizIn,
        (case when SUM(NS_pg4.CANTNIR * (NS_pg4.PRET - NS_pg4.ADAOS))=0 then 0 else SUM(NS_pg4.CANTNIR * NS_pg4.PRET) / SUM(NS_pg4.CANTNIR * (NS_pg4.PRET - NS_pg4.ADAOS)) end) Coef,
        NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
        N.NRNIR||''/''||to_char(N.DATANIR,''dd.mm.yyyy'') RecLivr, TO_CHAR(N.DATANIR'||',''DD'')::numeric Zi, TO_CHAR(T.DATADOC,''DD'')::numeric ZiDoc '||gUserAlias||'
      FROM TRANSF T
        INNER JOIN NIR     N      ON N.CODTRANSF     = T.CODTRANSF'||coalesce((select wme_result from pkg_list_base_raportgestCval_JOINTMP('','N.GEST'))::varchar,'')||'
        INNER JOIN NIRSTOC NS_pg4 ON NS_pg4.CODNIR   = N.CODNIR
        INNER JOIN IOA1           ON IOA1.CODIOART   = NS_pg4.CODIOART
        INNER JOIN NGEST   NG     ON NG.CODGEST      = N.GEST '|| coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG','CODSUBUNIT',NULL,NULL))::varchar,'')||'
        LEFT JOIN NIRSTOC  NS_S   ON NS_S.CODNIRSTOC = NS_pg4.CODNIRSTOCPARINTE AND (NS_pg4.CODNIRSTOCPARINTE IS NOT NULL)
        LEFT JOIN NIR      N_S    ON N_S.CODNIR      = NS_S.CODNIR
        LEFT JOIN LIVRVAL  LV_S   ON LV_S.CODLIVR1   = NS_pg4.CODLIVR1
        LEFT JOIN NGEST    NG_S   ON NG_S.CODGEST    = Coalesce(N_S.GEST,LV_S.GEST)
        LEFT JOIN NPERS    OPER   ON OPER.LOGONNAME  = T.USERID'||
        gSuplJoins||'
      WHERE T.TIPDOC = 12 AND T.ANULAT = 0 AND T.OPERAT = 1 AND N.OPERAT = 1'||pGest||'
        AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
        AND N.DATANIR'||sCondData||'
      GROUP BY T.CODTRANSF, T.TIPDOC, T.PREFIXDOC, T.SERIADOC, T.NRDOC, T.DATADOC, N.NRNIR, N.DATANIR, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST, NG_S.DEN_GEST'||gUserAlias||'
      UNION ALL -- IESIRI PRIN TRANSFER STOC
      SELECT
        T.CODTRANSF CodDoc, T.TIPDOC, T.PREFIXDOC, T.NRDOC, T.DATADOC, L.DATALIVR DATANIRLIVR,
      --t.prefixdoc ||t.seriadoc||t.nrdoc||''/''||to_char(t.datadoc,''dd.mm.yyyy'') Doc,
        coalesce(t.prefixdoc,'''') ||coalesce(t.seriadoc,'''')||coalesce(t.nrdoc::varchar,'''')||''/''||coalesce(to_char(t.datadoc,''dd.mm.yyyy''),'''') Doc,
        coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',T.TIPDOC)),''''), 0 PROVSI,
        0 Addebit, 0 ValDFTva, 0 ValDCTva, 0 TvaD, 0 PROVD,
        SUM(NS_D.CANTNIR * (NS_pg5.ADAOS - NS_pg5.PRET * Coalesce(NS_pg5.TVA,0) / Coalesce(1+NS_pg5.TVA,1) )) Adcredit, SUM(NS_D.CANTNIR * NS_pg5.PRET / Coalesce(1+NS_pg5.TVA,1)) ValCFTva, SUM(NS_D.CANTNIR * NS_pg5.PRET) ValCCTva,
        SUM(NS_D.CANTNIR * NS_pg5.PRET * Coalesce(NS_pg5.TVA,0) / Coalesce(1+NS_pg5.TVA,1)) TvaC, SUM(NS_D.CANTNIR * Coalesce(NS_pg5.PROVIZION,0)) PROVC,
        -SUM(NS_D.CANTNIR * NS_pg5.PRET / Coalesce(1+NS_pg5.TVA,1)) SoldFinFTva, -SUM(NS_D.CANTNIR * NS_pg5.PRET) SoldFinCTva, 0 SoldAd,
        NG_D.DEN_GEST SursaDest, IOA1.DEN_IOART,
        0 SoldIn, 0 AchizIn,
        0 Coef,
        NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
        L.NRLIVR||''/''||to_char(L.DATALIVR,''dd.mm.yyyy'') RecLivr, TO_CHAR(L.DATALIVR,''DD'')::numeric Zi, TO_CHAR(T.DATADOC,''DD'')::numeric ZiDoc '||gUserAlias||'
      FROM TRANSF T
        INNER JOIN LIVR    L      ON L.CODTRANSF       = T.CODTRANSF
        INNER JOIN LIVR1   L1     ON L1.CODLIVR        = L.CODLIVR
        INNER JOIN NIRSTOC NS_pg5 ON NS_pg5.CODNIRSTOC = L1.CODNIRSTOC
        INNER JOIN NIR     N      ON N.CODNIR          = NS_pg5.CODNIR'||coalesce((select wme_result from pkg_list_base_raportgestCval_JOINTMP('','N.GEST'))::varchar,'')||'
        INNER JOIN IOA1           ON IOA1.CODIOART     = NS_pg5.CODIOART
        INNER JOIN NGEST   NG     ON NG.CODGEST        = N.GEST '|| coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG','CODSUBUNIT',NULL,NULL))::varchar,'')||'
        INNER JOIN NIRSTOC NS_D   ON NS_D.CODLIVR1     = L1.CODLIVR1
        INNER JOIN NIR     N_D    ON N_D.CODNIR        = NS_D.CODNIR
        LEFT  JOIN NGEST   NG_D   ON NG_D.CODGEST      = N_D.GEST
        LEFT  JOIN NPERS   OPER   ON OPER.LOGONNAME    = T.USERID'||
        gSuplJoins||'
      WHERE T.TIPDOC = 12 AND T.OPERAT = 1 AND T.ANULAT = 0'||pGest||'
        AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
        AND L.DATALIVR'||sCondData||'
      GROUP BY T.CODTRANSF, T.TIPDOC, T.PREFIXDOC, T.SERIADOC, T.NRDOC, T.DATADOC,  L.NRLIVR, L.DATALIVR, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST, NG_D.DEN_GEST'||gUserAlias||'
      UNION ALL -- IESIRI PRIN TRANSFER VALORIC
      SELECT
        T.CODTRANSF CodDoc, T.TIPDOC, T.PREFIXDOC, T.NRDOC, T.DATADOC, L.DATALIVR DATANIRLIVR,
      --t.prefixdoc ||t.seriadoc||t.nrdoc||''/''||to_char(t.datadoc,''dd.mm.yyyy'') Doc,
        coalesce(t.prefixdoc,'''') ||coalesce(t.seriadoc,'''')||coalesce(t.nrdoc::varchar,'''')||''/''||coalesce(to_char(t.datadoc,''dd.mm.yyyy''),'''') Doc,
        coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',T.TIPDOC)),''''), 0 PROVSI,
        0 Addebit, 0 ValDFTva, 0 ValDCTva, 0 TvaD, 0 PROVD,
        SUM(NS_D1.CANTNIR * (LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0)) - LV.PRETACHIZ)) AdCredit,
        SUM(NS_D1.CANTNIR *  LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0))) ValCFTva, SUM(NS_D1.CANTNIR * LV.PRETINREG) ValCCTva,
        SUM(NS_D1.CANTNIR *  LV.PRETINREG * Coalesce(LV.TVANEEX, 0) / (1+Coalesce(LV.TVANEEX, 0))) TvaC, 0 PROVC,
        -SUM(NS_D1.CANTNIR * LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0))) SoldFinFTva, -SUM(NS_D1.CANTNIR * LV.PRETINREG) SoldFinCTva, 0 SoldAd,
        NG_D.DEN_GEST SursaDest, IOA1.DEN_IOART,
        0 SoldIn, 0 AchizIn,
        0 Coef,
        NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
        L.NRLIVR||''/''||to_char(L.DATALIVR,''dd.mm.yyyy'') RecLivr, TO_CHAR(L.DATALIVR,''DD'')::numeric Zi, TO_CHAR(T.DATADOC,''DD'')::numeric ZiDoc '||gUserAlias||'
      FROM TRANSF T
        INNER JOIN LIVR    L     ON L.CODTRANSF      = T.CODTRANSF
        INNER JOIN LIVR1   L1    ON L1.CODLIVR       = L.CODLIVR
        INNER JOIN LIVRVAL LV    ON LV.CODLIVR1      = L1.CODLIVR1'||coalesce((select wme_result from pkg_list_base_raportgestCval_JOINTMP('','LV.GEST'))::varchar,'')||'
        INNER JOIN IOA1          ON IOA1.CODIOART    = LV.CODIOART
        INNER JOIN NGEST   NG    ON NG.CODGEST       = LV.GEST '|| coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG','CODSUBUNIT',NULL,NULL))::varchar,'')||'
        INNER JOIN NIRSTOC NS_D1 ON NS_D1.CODTRANSF1 = L1.CODIES1
        INNER JOIN NIR     N_D   ON N_D.CODNIR       = NS_D1.CODNIR
        LEFT  JOIN NGEST   NG_D  ON NG_D.CODGEST     = N_D.GEST
        LEFT  JOIN NPERS   OPER  ON OPER.LOGONNAME   = T.USERID'||
        gSuplJoins||'
      WHERE T.TIPDOC = 12 AND T.OPERAT = 1 AND T.ANULAT = 0'||pGest||'
        AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
        AND L.DATALIVR'||sCondData||'
      GROUP BY T.CODTRANSF, T.TIPDOC, T.PREFIXDOC, T.SERIADOC, T.NRDOC, T.DATADOC, L.NRLIVR, L.DATALIVR, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST, NG_D.DEN_GEST'||gUserAlias||'
      UNION ALL -- MODIFICARI DE PRET
      SELECT
        T.CODTRANSF CodDoc, T.TIPDOC, T.PREFIXDOC, T.NRDOC, T.DATADOC, N.DATANIR DATANIRLIVR,
      --t.prefixdoc ||t.seriadoc||t.nrdoc||''/''||to_char(t.datadoc,''dd.mm.yyyy'') Doc,
        coalesce(t.prefixdoc,'''') ||coalesce(t.seriadoc,'''')||coalesce(t.nrdoc::varchar,'''')||''/''||coalesce(to_char(t.datadoc,''dd.mm.yyyy''),'''') Doc,
        coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',T.TIPDOC)),''''), 0 PROVSI,
        SUM(NS_pg6.CANTNIR * (NS_pg6.ADAOS - NS_pg6.PRET * Coalesce(NS_pg6.TVA,0) / Coalesce(1+NS_pg6.TVA,1) )) AdDebit, SUm(NS_pg6.CANTNIR * NS_pg6.PRET / Coalesce(1+NS_pg6.TVA,1)) ValDFTva, SUM(NS_pg6.CANTNIR * NS_pg6.PRET) ValDCTva,
        SUM(NS_pg6.CANTNIR * NS_pg6.PRET * Coalesce(NS_pg6.TVA,0) / Coalesce(1+NS_pg6.TVA,1)) TVAD, SUM(NS_pg6.CANTNIR * Coalesce(NS_pg6.PROVIZION,0)) PROVD,
        SUM(NS_pg6.CANTNIR * (case when NS_pg6.CODNIRSTOCPARINTE IS NULL then (LV_S.PRETINREG / (1+LV_S.TVANEEX) - LV_S.PRETACHIZ) else (NS_S1.ADAOS - NS_S1.PRET * NS_S1.TVA / (1+NS_S1.TVA)) end)) AdCredit,
        SUM(NS_pg6.CANTNIR * (case when NS_pg6.CODNIRSTOCPARINTE IS NULL then  LV_S.PRETINREG / (1+LV_S.TVANEEX) else NS_S1.PRET / (1+NS_S1.TVA) end)) ValCFTva,
        SUM(NS_pg6.CANTNIR * (case when NS_pg6.CODNIRSTOCPARINTE IS NULL then  LV_S.PRETINREG else NS_S1.PRET end)) ValCCTva,
        SUM(NS_pg6.CANTNIR * (case when NS_pg6.CODNIRSTOCPARINTE IS NULL then  LV_S.PRETINREG * LV_S.TVANEEX / (1+LV_S.TVANEEX) else NS_S1.PRET * NS_S1.TVA / (1+NS_S1.TVA) end)) TvaC, SUM(NS_pg6.CANTNIR * Coalesce(NS_S1.PROVIZION,0)) PROVC,
        SUM(NS_pg6.CANTNIR * NS_pg6.PRET / Coalesce(1+NS_pg6.TVA,1)) - SUM(NS_pg6.CANTNIR * (case when NS_pg6.CODNIRSTOCPARINTE IS NULL then LV_S.PRETINREG / (1+LV_S.TVANEEX) else NS_S1.PRET / (1+NS_S1.TVA) end))  SoldFinFTva,
        SUM(NS_pg6.CANTNIR * NS_pg6.PRET) - SUM(NS_pg6.CANTNIR * (case when NS_pg6.CODNIRSTOCPARINTE IS NULL then LV_S.PRETINREG else NS_S1.PRET end)) SoldFinCTva, 0 SoldAd,
        NG.DEN_GEST SursaDest, IOA1.DEN_IOART,
        SUM(NS_pg6.CANTNIR * NS_pg6.PRET) SoldIn, SUM(NS_pg6.CANTNIR * (NS_pg6.PRET - NS_pg6.ADAOS)) AchizIn,
        (case when SUM(NS_pg6.CANTNIR * (NS_pg6.PRET - NS_pg6.ADAOS))=0 then 0 else SUM(NS_pg6.CANTNIR * NS_pg6.PRET) / SUM(NS_pg6.CANTNIR * (NS_pg6.PRET - NS_pg6.ADAOS)) end) Coef,
        NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
        N.NRNIR||''/''||to_char(N.DATANIR,''dd.mm.yyyy'') RecLivr, TO_CHAR(N.DATANIR'||',''DD'')::numeric Zi, TO_CHAR(T.DATADOC,''DD'')::numeric ZiDoc '||gUserAlias||'
      FROM TRANSF T
        INNER JOIN NIR     N      ON N.CODTRANSF      = T.CODTRANSF'||coalesce((select wme_result from pkg_list_base_raportgestCval_JOINTMP('','N.GEST'))::varchar,'')||'
        INNER JOIN NIRSTOC NS_pg6 ON NS_pg6.CODNIR    = N.CODNIR
        INNER JOIN IOA1           ON IOA1.CODIOART    = NS_pg6.CODIOART
        INNER JOIN NGEST   NG     ON NG.CODGEST       = N.GEST '|| coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG','CODSUBUNIT',NULL,NULL))::varchar,'')||'
        LEFT JOIN NIRSTOC  NS_S1  ON NS_S1.CODNIRSTOC = NS_pg6.CODNIRSTOCPARINTE AND (NS_pg6.CODNIRSTOCPARINTE IS NOT NULL)
        LEFT JOIN NIR      N_S    ON N_S.CODNIR       = NS_S1.CODNIR
        LEFT JOIN LIVR1    L1_S   ON L1_S.CODLIVR1    = NS_pg6.CODLIVR1 AND (NS_pg6.CODNIRSTOCPARINTE IS NULL)
        LEFT JOIN LIVRVAL  LV_S   ON LV_S.CODLIVR1    = L1_S.CODLIVR1
        LEFT JOIN NGEST    NG_S   ON NG_S.CODGEST     = Coalesce(N_S.GEST,LV_S.GEST)
        LEFT JOIN NPERS    OPER   ON OPER.LOGONNAME   = T.USERID'||
        gSuplJoins||'
      WHERE T.TIPDOC = 13 AND T.ANULAT = 0 AND T.OPERAT = 1 AND N.OPERAT = 1'||pGest||'
        AND T.AN = '||GetANLUCRU()::varchar||' AND T.LUNA = '||GETLUNALUCRU()::varchar||'
        AND N.DATANIR'||sCondData||'
      GROUP BY T.CODTRANSF, T.TIPDOC, T.PREFIXDOC, T.SERIADOC, T.NRDOC, T.DATADOC, N.NRNIR, N.DATANIR, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST, NG_S.DEN_GEST'||gUserAlias||'
      UNION ALL -- RETUR INTRARI STOC
      SELECT
        I.CODINTR CodDoc, I.TIPDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC, L.DATALIVR DATANIRLIVR,
      --i.prefixdoc ||i.seriadoc||i.nrdoc ||''/''||to_char(i.datadoc,''dd.mm.yyyy'') Doc,
        coalesce(i.prefixdoc,'''') ||coalesce(i.seriadoc,'''')||coalesce(i.nrdoc::varchar,'''') ||''/''||coalesce(to_char(i.datadoc,''dd.mm.yyyy''),'''') Doc,
        coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',I.TIPDOC)),''''), 0 PROVSI,
        - SUM(L1.CANT * (NS_pg7.ADAOS - NS_pg7.PRET * Coalesce(NS_pg7.TVA,0) / Coalesce(1+NS_pg7.TVA,1) )) AdDebit, - SUM(L1.CANT * NS_pg7.PRET / Coalesce(1+NS_pg7.TVA,1)) ValDFTva,
        - SUM(L1.CANT * NS_pg7.PRET) ValDCTva, - SUM(L1.CANT * NS_pg7.PRET * Coalesce(NS_pg7.TVA,0) / Coalesce(1+NS_pg7.TVA,1)) TvaD, -SUM(L1.CANT * Coalesce(NS_pg7.PROVIZION,0)) PROVD,
        0 Adcredit, 0 ValCFTva, 0 ValCCTva, 0 TvaC, 0 PROVC,
        -SUM(L1.CANT * NS_pg7.PRET / Coalesce(1+NS_pg7.TVA,1)) SoldFinFTva, -SUM(L1.CANT * NS_pg7.PRET) SoldFinCTva, 0 SoldAd,
        (case when I.TIPDOC=6 then S.DEN_SUBUNIT when I.TIPDOC=7 then G.DEN_GEST else NP.DEN_PART end) SursaDest, IOA1.DEN_IOART,
        0 SoldIn, 0 AchizIn,
        0 Coef,
        NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
        L.NRLIVR||''/''||to_char(L.DATALIVR,''dd.mm.yyyy'') RecLivr, TO_CHAR(L.DATALIVR,''DD'')::numeric Zi, TO_CHAR(I.DATADOC,''DD'')::numeric ZiDoc '||gUserAlias||'
      FROM INTRARI I
        INNER JOIN LIVR     L      ON L.CODINTR         = I.CODINTR
        INNER JOIN LIVR1    L1     ON L1.CODLIVR        = L.CODLIVR
        INNER JOIN NIRSTOC  NS_pg7 ON NS_pg7.CODNIRSTOC = L1.CODNIRSTOC
        INNER JOIN NIR      N      ON N.CODNIR          = NS_pg7.CODNIR'||coalesce((select wme_result from pkg_list_base_raportgestCval_JOINTMP('','N.GEST'))::varchar,'')||'
        INNER JOIN IOA1            ON IOA1.CODIOART     = NS_pg7.CODIOART
        INNER JOIN NGEST    NG     ON NG.CODGEST        = N.GEST '|| coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG','CODSUBUNIT',NULL,NULL))::varchar,'')||'
        LEFT  JOIN NPART    NP     ON NP.CODPART        = I.PARTENER
        LEFT  JOIN NGEST    G      ON G.CODGEST         = I.CODGESTPROD
        LEFT  JOIN NSUBUNIT S      ON S.CODSUBUNIT      = I.CODSUBUNIT
        LEFT  JOIN NPERS    OPER   ON OPER.LOGONNAME    = I.USERID'||
        gSuplJoins||'
      WHERE I.TIPDOC IN (1, 2, 3, 4, 5, 6, 7) AND I.OPERAT = 1 AND I.ANULAT = 0'||pGest||'
        AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
        AND L.DATALIVR'||sCondData||'
      GROUP BY I.CODINTR, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC,  L.NRLIVR, L.DATALIVR, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST, NP.DEN_PART, S.DEN_SUBUNIT, G.DEN_GEST'||gUserAlias||'
      UNION ALL -- RETUR INTRARI VALORIC
      SELECT
        I.CODINTR CodDoc, I.TIPDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC, L.DATALIVR DATANIRLIVR,
      --i.prefixdoc ||i.seriadoc||i.nrdoc ||''/''||to_char(i.datadoc,''dd.mm.yyyy'') Doc,
        coalesce(i.prefixdoc,'''') ||coalesce(i.seriadoc,'''')||coalesce(i.nrdoc::varchar,'''') ||''/''||coalesce(to_char(i.datadoc,''dd.mm.yyyy''),'''') Doc,
        coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',I.TIPDOC)),''''), 0 PROVSI,
        - SUM(L1.CANT * (LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0)) - LV.PRETACHIZ) ) AdDebit, - SUM(L1.CANT * LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0))) ValDFTva,
        - SUM(L1.CANT * LV.PRETINREG) ValDCTva, - SUM(L1.CANT * LV.PRETINREG * Coalesce(LV.TVANEEX, 0) / (1+Coalesce(LV.TVANEEX, 0))) TvaD, 0 PROVD,
        0 Adcredit, 0 ValCFTva, 0 ValCCTva, 0 TvaC, 0 PROVC,
        -SUM(L1.CANT * LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0))) SoldFinFTva, -SUM(L1.CANT * LV.PRETINREG) SoldFinCTva, 0 SoldAd,
        (case when I.TIPDOC=6 then S.DEN_SUBUNIT when I.TIPDOC=7 then G.DEN_GEST else NP.DEN_PART end) SursaDest, IOA1.DEN_IOART,
        0 SoldIn, 0 AchizIn,
        0 Coef,
        NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
        L.NRLIVR||''/''||to_char(L.DATALIVR,''dd.mm.yyyy'') RecLivr, TO_CHAR(L.DATALIVR,''DD'')::numeric Zi, TO_CHAR(I.DATADOC,''DD'')::numeric ZiDoc '||gUserAlias||'
      FROM INTRARI I
        INNER JOIN LIVR    L    ON L.CODINTR      = I.CODINTR
        INNER JOIN LIVR1   L1   ON L1.CODLIVR     = L.CODLIVR
        INNER JOIN LIVRVAL LV   ON LV.CODLIVR1    = L1.CODLIVR1'||coalesce((select wme_result from pkg_list_base_raportgestCval_JOINTMP('','LV.GEST'))::varchar,'')||'
        INNER JOIN IOA1         ON IOA1.CODIOART  = LV.CODIOART
        INNER JOIN NGEST   NG   ON NG.CODGEST     = LV.GEST '|| coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG','CODSUBUNIT',NULL,NULL))::varchar,'')||'
        LEFT JOIN NPART    NP   ON NP.CODPART     = I.PARTENER
        LEFT JOIN NGEST    G    ON G.CODGEST      = I.CODGESTPROD
        LEFT JOIN NSUBUNIT S    ON S.CODSUBUNIT   = I.CODSUBUNIT
        LEFT JOIN NPERS    OPER ON OPER.LOGONNAME = I.USERID'||
        gSuplJoins||'
      WHERE I.TIPDOC IN (1, 2, 3, 4, 5, 6, 7) AND I.OPERAT = 1 AND I.ANULAT = 0'||pGest||'
        AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
        AND L.DATALIVR'||sCondData||'
      GROUP BY I.CODINTR, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC, L.NRLIVR, L.DATALIVR, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST, NP.DEN_PART, S.DEN_SUBUNIT, G.DEN_GEST'||gUserAlias||'
      UNION ALL  -- IESIRI STOC
      SELECT
        I.CODIES CodDoc, I.TIPDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC, L.DATALIVR DATANIRLIVR,
      --i.prefixdoc ||i.seriadoc||i.nrdoc ||''/''||to_char(i.datadoc,''dd.mm.yyyy'') Doc,
        coalesce(i.prefixdoc,'''') ||coalesce(i.seriadoc,'''')||coalesce(i.nrdoc::varchar,'''') ||''/''||coalesce(to_char(i.datadoc,''dd.mm.yyyy''),'''') Doc,
        coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',I.TIPDOC)),''''), 0 PROVSI,
        0 AdDebit, 0 ValDFTva, 0 ValDCTva, 0 TvaD, 0 PROVD,
        SUM(L1.CANT * (NS_pg8.ADAOS - NS_pg8.PRET * Coalesce(NS_pg8.TVA,0) / Coalesce(1+NS_pg8.TVA,1) )) Adcredit, SUM(L1.CANT * NS_pg8.PRET / Coalesce(1+NS_pg8.TVA,1)) ValCFTva, SUM(L1.CANT * NS_pg8.PRET) ValCCTva,
        SUM(L1.CANT * NS_pg8.PRET * Coalesce(NS_pg8.TVA,0) / Coalesce(1+NS_pg8.TVA,1)) TvaC, SUM(L1.CANT * Coalesce(NS_pg8.PROVIZION,0)) PROVC,
        -SUM(L1.CANT * NS_pg8.PRET / Coalesce(1+NS_pg8.TVA,1)) SoldFinFTva, -SUM(L1.CANT * NS_pg8.PRET) SoldFinCTva, 0 SoldAd,
        (case when I.TIPDOC=14 then ''-'' when I.TIPDOC=16 then ''-'' when I.TIPDOC=23 then NSU.DEN_SUBUNIT when I.TIPDOC=24 then NG.DEN_GEST else NP.DEN_PART end) SursaDest, IOA1.DEN_IOART,
        0 SoldIn, 0 AchizIn,
        0 Coef,
        NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
        L.NRLIVR||''/''||to_char(L.DATALIVR,''dd.mm.yyyy'') RecLivr, TO_CHAR(L.DATALIVR,''DD'')::numeric Zi, TO_CHAR(I.DATADOC,''DD'')::numeric ZiDoc '||gUserAlias||'
      FROM IESIRI I
        INNER JOIN LIVR     L      ON L.CODIES          = I.CODIES
        INNER JOIN LIVR1    L1     ON L1.CODLIVR        = L.CODLIVR
        INNER JOIN NIRSTOC  NS_pg8 ON NS_pg8.CODNIRSTOC = L1.CODNIRSTOC
        INNER JOIN NIR      N      ON N.CODNIR          = NS_pg8.CODNIR'||coalesce((select wme_result from pkg_list_base_raportgestCval_JOINTMP('','N.GEST'))::varchar,'')||'
        INNER JOIN IOA1            ON IOA1.CODIOART     = NS_pg8.CODIOART
        INNER JOIN NGEST    NG     ON NG.CODGEST        = N.GEST '|| coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG','CODSUBUNIT',NULL,NULL))::varchar,'')||'
        LEFT  JOIN NPART    NP     ON NP.CODPART        = I.PARTENER
        LEFT  JOIN NGEST    G      ON G.CODGEST         = I.CODGESTPROD
        LEFT  JOIN NSUBUNIT NSU    ON NSU.CODSUBUNIT    = I.CODSUBUNIT
        LEFT  JOIN NPERS    OPER   ON OPER.LOGONNAME    = I.USERID'||
        gSuplJoins||'
      WHERE I.TIPDOC IN (14, 16, 19, 20, 21, 22, 23, 24) AND I.OPERAT = 1 AND I.ANULAT = 0'||pGest||'
        AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
        AND L.DATALIVR'||sCondData||'
      GROUP BY I.CODIES, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC,  L.NRLIVR, L.DATALIVR, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST, NP.DEN_PART, NSU.DEN_SUBUNIT, G.DEN_GEST'||gUserAlias||'
      UNION ALL  -- IESIRI VALORIC
      SELECT
        I.CODIES CodDoc, I.TIPDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC, L.DATALIVR DATANIRLIVR,
      --i.prefixdoc ||i.seriadoc||i.nrdoc ||''/''||to_char(i.datadoc,''dd.mm.yyyy'') Doc,
        coalesce(i.prefixdoc,'''') ||coalesce(i.seriadoc,'''')||coalesce(i.nrdoc::varchar,'''') ||''/''||coalesce(to_char(i.datadoc,''dd.mm.yyyy''),'''') Doc,
        coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',I.TIPDOC)),''''), 0 PROVSI,
        0 AdDebit, 0 ValDFTva, 0 ValDCTva, 0 TvaD, 0 PROVD,
        SUM(L1.CANT * (LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0)) - LV.PRETACHIZ) ) Adcredit, SUM(L1.CANT * LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0))) ValCFTva, SUM(L1.CANT * LV.PRETINREG) ValCCTva,
        SUM(L1.CANT * LV.PRETINREG * Coalesce(LV.TVANEEX, 0) / (1+Coalesce(LV.TVANEEX, 0))) TvaC, 0 PROVC,
        -SUM(L1.CANT * LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0))) SoldFinFTva, -SUM(L1.CANT * LV.PRETINREG) SoldFinCTva, 0 SoldAd,
        (case when I.TIPDOC=14 then ''-'' when I.TIPDOC=16 then ''-'' when I.TIPDOC=23 then NS.DEN_SUBUNIT when I.TIPDOC=24 then NG.DEN_GEST else NP.DEN_PART end) SursaDest, IOA1.DEN_IOART,
        0 SoldIn, 0 AchizIn,
        0 Coef,
        NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
        L.NRLIVR||''/''||to_char(L.DATALIVR,''dd.mm.yyyy'') RecLivr, TO_CHAR(L.DATALIVR,''DD'')::numeric Zi, TO_CHAR(I.DATADOC,''DD'')::numeric ZiDoc '||gUserAlias||'
      FROM IESIRI I
        INNER JOIN LIVR     L    ON L.CODIES       = I.CODIES
        INNER JOIN LIVR1    L1   ON L1.CODLIVR     = L.CODLIVR
        INNER JOIN LIVRVAL  LV   ON LV.CODLIVR1    = L1.CODLIVR1'||coalesce((select wme_result from pkg_list_base_raportgestCval_JOINTMP('','LV.GEST'))::varchar,'')||'
        INNER JOIN IOA1          ON IOA1.CODIOART  = LV.CODIOART
        INNER JOIN NGEST    NG   ON NG.CODGEST     = LV.GEST '|| coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG','CODSUBUNIT',NULL,NULL))::varchar,'')||'
        LEFT  JOIN NPART    NP   ON NP.CODPART     = I.PARTENER
        LEFT  JOIN NGEST    G    ON G.CODGEST      = I.CODGESTPROD
        LEFT  JOIN NSUBUNIT NS   ON NS.CODSUBUNIT  = I.CODSUBUNIT
        LEFT  JOIN NPERS    OPER ON OPER.LOGONNAME = I.USERID'||
        gSuplJoins||'
      WHERE I.TIPDOC IN (14, 16, 19, 20, 21, 22, 23, 24) AND I.OPERAT = 1 AND I.ANULAT = 0'||pGest||'
        AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
        AND L.DATALIVR'||sCondData||'
      GROUP BY I.CODIES, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC, L.NRLIVR, L.DATALIVR, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST, NP.DEN_PART, NS.DEN_SUBUNIT, G.DEN_GEST'||gUserAlias||'
      UNION ALL -- MARIRI DE STOC
      SELECT
        I.CODIES CodDoc, I.TIPDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC, L.DATALIVR DATANIRLIVR,
      --i.prefixdoc ||i.seriadoc||i.nrdoc ||''/''||to_char(i.datadoc,''dd.mm.yyyy'') Doc,
        coalesce(i.prefixdoc,'''') ||coalesce(i.seriadoc,'''')||coalesce(i.nrdoc::varchar,'''') ||''/''||coalesce(to_char(i.datadoc,''dd.mm.yyyy''),'''') Doc,
        coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',I.TIPDOC)),''''), 0 PROVSI,
        SUM(L1.CANT * (NS_pg9.ADAOS - NS_pg9.PRET * Coalesce(NS_pg9.TVA,0) / Coalesce(1+NS_pg9.TVA,1) )) AdDebit, SUM(L1.CANT * NS_pg9.PRET / Coalesce(1+NS_pg9.TVA,1)) ValDFTva, SUM(L1.CANT * NS_pg9.PRET) ValDCTva,
        SUM(L1.CANT * NS_pg9.PRET * Coalesce(NS_pg9.TVA,0) / Coalesce(1+NS_pg9.TVA,1)) TVAD, SUM(L1.CANT * Coalesce(NS_pg9.PROVIZION,0)) PROVD,
        0 AdCredit, 0 ValCFTva, 0 ValCCTva, 0 TvaC, 0 PROVC,
        SUM(L1.CANT * NS_pg9.PRET / Coalesce(1+NS_pg9.TVA,1)) SoldFinFTva, SUM(L1.CANT * NS_pg9.PRET) SoldFinCTva, 0 SoldAd,
        NG.DEN_GEST SursaDest, IOA1.DEN_IOART,
        SUM(L1.CANT * NS_pg9.PRET) SoldIn, SUM(L1.CANT * (NS_pg9.PRET - NS_pg9.ADAOS)) AchizIn,
        (case when SUM(L1.CANT * (NS_pg9.PRET - NS_pg9.ADAOS))=0 then 0 else SUM(L1.CANT * NS_pg9.PRET) / SUM(L1.CANT * (NS_pg9.PRET - NS_pg9.ADAOS)) end) Coef,
        NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
        L.NRLIVR||''/''||to_char(L.DATALIVR,''dd.mm.yyyy'') RecLivr, TO_CHAR(L.DATALIVR,''DD'')::numeric Zi, TO_CHAR(I.DATADOC,''DD'')::numeric ZiDoc '||gUserAlias||'
      FROM IESIRI I
        INNER JOIN LIVR    L      ON L.CODIES          = I.CODIES
        INNER JOIN LIVR1   L1     ON L1.CODLIVR        = L.CODLIVR
        INNER JOIN NIRSTOC NS_pg9 ON NS_pg9.CODNIRSTOC = L1.CODNIRSTOC
        INNER JOIN NIR     N      ON N.CODNIR          = NS_pg9.CODNIR'||coalesce((select wme_result from pkg_list_base_raportgestCval_JOINTMP('','N.GEST'))::varchar,'')||'
        INNER JOIN IOA1           ON IOA1.CODIOART     = NS_pg9.CODIOART
        INNER JOIN NGEST   NG     ON NG.CODGEST        = N.GEST '|| coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG','CODSUBUNIT',NULL,NULL))::varchar,'')||'
        LEFT  JOIN NPERS   OPER   ON OPER.LOGONNAME    = I.USERID'||
        gSuplJoins||'
      WHERE I.TIPDOC = 15 AND I.OPERAT = 1 AND I.ANULAT = 0'||pGest||'
        AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
        AND L.DATALIVR'||sCondData||'
      GROUP BY I.CODIES, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC,  L.NRLIVR, L.DATALIVR, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST'||gUserAlias||'
      UNION ALL -- MARIRI DE STOC VALORIC
      SELECT
        I.CODIES CodDoc, I.TIPDOC, I.PREFIXDOC, I.NRDOC, I.DATADOC, L.DATALIVR DATANIRLIVR,
      --i.prefixdoc ||i.seriadoc||i.nrdoc ||''/''||to_char(i.datadoc,''dd.mm.yyyy'') Doc,
        coalesce(i.prefixdoc,'''') ||coalesce(i.seriadoc,'''')||coalesce(i.nrdoc::varchar,'''') ||''/''||coalesce(to_char(i.datadoc,''dd.mm.yyyy''),'''') Doc,
        coalesce((select wme_result from pkg_list_base_utils_decode_tipdoc('''',I.TIPDOC)),''''), 0 PROVSI,
        SUM(L1.CANT * (LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0)) - LV.PRETACHIZ)) AdDebit, SUM(L1.CANT * LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0))) ValDFTva, SUM(L1.CANT * LV.PRETINREG) ValDCTva,
        SUM(L1.CANT * LV.PRETINREG * Coalesce(LV.TVANEEX, 0) / (1+Coalesce(LV.TVANEEX, 0))) TvaD, 0 PROVD,
        0 AdCredit, 0 ValCFTva, 0 ValCCTva, 0 TvaC, 0 PROVC,
        SUM(L1.CANT * LV.PRETINREG / (1+Coalesce(LV.TVANEEX, 0))) SoldFinFTva, SUM(L1.CANT * LV.PRETINREG) SoldFinCTva, 0 SoldAd,
        NG.DEN_GEST SursaDest, IOA1.DEN_IOART,
        SUM(L1.CANT * LV.PRETINREG) SoldIn, SUM(L1.CANT * LV.PRETINREG) AchizIn,
        (case when SUM(L1.CANT * LV.PRETINREG)=0 then 0 else SUM(L1.CANT * LV.PRETINREG) / SUM(L1.CANT * LV.PRETINREG) end) Coef,
        NG.DEN_GEST, IOA1.DEN_CONT, IOA1.SIMB_CONT,
        L.NRLIVR||''/''||to_char(L.DATALIVR,''dd.mm.yyyy'') RecLivr, TO_CHAR(L.DATALIVR,''DD'')::numeric Zi, TO_CHAR(I.DATADOC,''DD'')::numeric ZiDoc '||gUserAlias||'
      FROM IESIRI I
        INNER JOIN LIVR    L    ON L.CODIES       = I.CODIES
        INNER JOIN LIVR1   L1   ON L1.CODLIVR     = L.CODLIVR
        INNER JOIN LIVRVAL LV   ON LV.CODLIVR1    = L1.CODLIVR1'||coalesce((select wme_result from pkg_list_base_raportgestCval_JOINTMP('','LV.GEST'))::varchar,'')||'
        INNER JOIN IOA1         ON IOA1.CODIOART  = LV.CODIOART
        INNER JOIN NGEST   NG   ON NG.CODGEST     = LV.GEST '|| coalesce((select wme_result from PKG_LIST_BASE_UTILS_COND_SUBUNIT(NULL,'NG','CODSUBUNIT',NULL,NULL))::varchar,'')||'
        LEFT  JOIN NPERS   OPER ON OPER.LOGONNAME = I.USERID'||
        gSuplJoins||'
      WHERE I.TIPDOC = 15 AND I.OPERAT = 1 AND I.ANULAT = 0'||pGest||'
        AND I.AN = '||GetANLUCRU()::varchar||' AND I.LUNA = '||GETLUNALUCRU()::varchar||'
        AND L.DATALIVR'||sCondData||'
      GROUP BY I.CODIES, I.TIPDOC, I.PREFIXDOC, I.SERIADOC, I.NRDOC, I.DATADOC, L.NRLIVR, L.DATALIVR, IOA1.DEN_IOART, IOA1.DEN_CONT, IOA1.SIMB_CONT, NG.DEN_GEST'||gUserAlias;
INSERT INTO x (view_name, test) VALUES ('sSelect', sSelect);
   PERFORM LIST_EXECUTE_IMMEDIATE(coalesce(sInsert,'') || coalesce(sSelect,''), aListID, aListVer);
   PERFORM LIST_EXECUTE_IMMEDIATE('UPDATE '||tmpName||' SET SoldAd = AdDebit - AdCredit WHERE SoldAd = 0' , aListID, aListVer);
end;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topclientiold_getallcls_n</obj_name>
  <obj_hashval>b84c08819701b82e6d954da19f66c214</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topclientiold_getallcls_n()
 RETURNS numeric
 LANGUAGE plpgsql
AS $function$
BEGIN
  --Adina 19.10.2020
  IF current_setting('PKG_LIST_BASE_TOPCLIENTIOLD.vAllIOArt',true)::boolean THEN RETURN 1; ELSE RETURN 0; END IF;
END;
$function$
</obj_text>
</row>

<row>
  <obj_type>FUNCTION</obj_type>
  <obj_name>pkg_list_base_topfurn_processlist</obj_name>
  <obj_hashval>338cd8668b7f8d9e911bfda76a36adde</obj_hashval>
  <obj_text>CREATE OR REPLACE FUNCTION pkg_list_base_topfurn_processlist(tmpname character varying, alistid numeric DEFAULT 0, alistver numeric DEFAULT 0)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sInsert       varchar := '';
  sSelect       varchar := '';
  vCondData     varchar := '';
  sCursRef       varchar := '1';
  sMonSitV       varchar := fnc_GetValConstanta('MonedaSitV', getANLUCRU(), getLUNALUCRU());
  sBanSitV       varchar := fnc_GetValConstanta('BancaSitV' , getANLUCRU(), getLUNALUCRU());
  sMon           varchar := '0';
  gSuplCols     VARCHAR := 'NARTOBJ NAO, NMONEDE M, NCONT C, NUM NUM, NPART P, NPARTCODFISC CF, NAGENDA AG, NLOCALIT LOC, NJUDET JUD, NMONEDE MON, NART ART, NCLASEA CLSA, NCLASEP CLSP ';
   gUserFields   VARCHAR := '';
  gUserAlias     VARCHAR := '';
  gNullAlias     VARCHAR := '';
  gSuplJoins     VARCHAR := '';
  vDataINI      varchar := COALESCE(current_setting('PKG_LIST_BASE_TOPFURN.vDataINI', true),'');
  vDataFIN      varchar := COALESCE(current_setting('PKG_LIST_BASE_TOPFURN.vDataFIN', true),'');
  vInLei        NUMERIC := current_setting('PKG_LIST_BASE_TOPFURN.InLei'    , true)::NUMERIC;
  vAllIOArt     boolean := current_setting('PKG_LIST_BASE_TOPFURN.vAllIOArt', true)::boolean;
BEGIN
  --Florin 16.02.2023 - sinc. Oracle
  --Florin 12.01.2023 - sinc. Oracle
  --Florin 18.07.2022 - fixat 54942
  --Florin 07.07.2022 - sinc. Oracle
  --Laura 26.10.2021 - sinc Oracle (25.10.2021)
  --Laura 17.09.2021 - sinc Oracle (16.09.2021)
  --Adina 29.06.2021 - in selectul final am uitat sa adaug ValTotCuTVA si ValTotCuTVA_Val
  --Adina 25.06.2021 - sinc.Oracle doar pe laura01 la zi
  --Adina 05.04.2021 - sinc.Oracle
  --Adina 19.01.2021 - sinc.Oracle
  --Adina 07 septembrie 2020; 24.11.2020 tichet 41240
  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, '', '', '',NULL);
  CALL pkg_list_struct_getsuplcols(aLISTID, alistver, gUserFields, gUserAlias, gNullAlias, gSuplJoins, gSuplCols);
  PERFORM set_config('PKG_LIST_BASE_TOPFURN.gSuplCols',gSuplCols,false);
  gUserFields := coalesce(gUserFields,'');
  gUserAlias  := coalesce(gUserAlias ,'');
  gNullAlias  := coalesce(gNullAlias ,'');
  gSuplJoins  := coalesce(gSuplJoins ,'');
  gSuplCols   := coalesce(gSuplCols  ,'');

  vCondData := 'BETWEEN TO_DATE (''' || vDataINI || ''',''DD.MM.YYYY'') AND TO_DATE (''' || vDataFIN || ''',''DD.MM.YYYY'')';

  IF sMonSitV IS NOT NULL  AND sBanSitV IS NOT NULL  AND  vInLei &lt;&gt; 1 THEN
    sCursRef := '(Select wme_result From PKG_LIST_BASE_UTILS_GETCURSREFERINTA(null,' || coalesce(sMonSitV,'') || ',' || coalesce(sBanSitV,'') || ', to_char(I.DataDoc, ''dd.mm.yyyy'')) )';
    sMon := sMonSitV;
  END IF;

  DELETE FROM TMP_CMD_TMP;
  DELETE FROM TMP_CMD_TMP1;
  DELETE FROM TMP_LST_TOP;
  PERFORM pkg_list_base_topfurn_setnrfact_art();
  PERFORM pkg_list_base_topfurn_setnrfact_part();


  sInsert :=
  'INSERT INTO ' || tmpName || '(
    DenArt, DenUM, Cant, Pret, Valoare, ValCuTVA, Pret_Val, Valoare_Val, ValCuTVA_Val, Valuta, Furnizor,
    ValTot, ValTotCuTVA, ValTot_Val, ValTotCuTVA_Val,
    NrFactPerArt,
    NrFactPerClient ' || gUserFields || ')';

  sSelect := '
    INSERT INTO TMP_LST_TOP
    SELECT
      I.Partener CodPart,
      SUM( (CASE WHEN I1.TipLinie IN (''G'') THEN I1.RestFact ELSE I1.PU*COALESCE(sign(i1.cant)*lv1.cant,NS.CANTNIR,I1.CANT) END - CASE WHEN I.TipDOC IN (3)     THEN I1.Tva*COALESCE(sign(i1.cant)*lv1.cant,NS.CANTNIR,I1.CANT)/I1.CANT ELSE 0 END ) * CASE WHEN Coalesce(I.CURS,0) = 0 THEN 1 ELSE I.CURS END ) ValTot,
      SUM( (CASE WHEN I1.TipLinie IN (''G'') THEN I1.RestFact ELSE I1.PU*COALESCE(sign(i1.cant)*lv1.cant,NS.CANTNIR,I1.CANT) END + CASE WHEN not I.TipDOC IN (3) THEN I1.Tva*COALESCE(sign(i1.cant)*lv1.cant,NS.CANTNIR,I1.CANT)/I1.CANT ELSE 0 END ) * CASE WHEN Coalesce(I.CURS,0) = 0 THEN 1 ELSE I.CURS END ) ValTotCuTVA,
      ' || coalesce(CASE WHEN  vInLei = 1 THEN '0'
                         ELSE 'SUM( (CASE WHEN I1.TipLinie IN (''G'') THEN I1.RestFact ELSE I1.PU*COALESCE(sign(i1.cant)*lv1.cant,NS.CANTNIR,I1.CANT) END - CASE WHEN I.TipDOC IN (3)     THEN I1.Tva*COALESCE(sign(i1.cant)*lv1.cant,NS.CANTNIR,I1.CANT)/I1.CANT ELSE 0 END ) * CASE WHEN Coalesce(I.CURS,0) = 0 THEN 1 ELSE I.CURS END /' || coalesce(sCursRef,'') || ')'
                     END ,'') || ' ValTot_Val,'
        || coalesce(CASE WHEN  vInLei = 1 THEN '0'
                         ELSE 'SUM( (CASE WHEN I1.TipLinie IN (''G'') THEN I1.RestFact ELSE I1.PU*COALESCE(sign(i1.cant)*lv1.cant,NS.CANTNIR,I1.CANT) END + CASE WHEN not I.TipDOC IN (3) THEN I1.Tva*COALESCE(sign(i1.cant)*lv1.cant,NS.CANTNIR,I1.CANT)/I1.CANT ELSE 0 END ) * CASE WHEN Coalesce(I.CURS,0) = 0 THEN 1 ELSE I.CURS END /' || coalesce(sCursRef,'') || ')'
                     END ,'') || ' ValTotCuTVA_Val
    FROM INTRARI I
         INNER JOIN INTRARI1 I1  ON I1.CODINTR    = I.CODINTR
         INNER JOIN NPART    P   ON I.PARTENER    = P.CODPART
         INNER JOIN NARTOBJ O    ON O.CODOBIECT   = I1.CODOBIECT
         INNER JOIN NART A       ON A.CODARTICOL  = O.CODARTICOL
         LEFT  JOIN DVI1         ON DVI1.CODINTR1 = I1.CODINTR1
         LEFT  JOIN INTRLINK L   ON L.CODINTR1    = I1.CODINTR1
         LEFT  JOIN INTRARI1 AE1 ON AE1.CODINTR1  = L.CODLINIEAVIZ
         LEFT  JOIN LIVR1    LV1 ON LV1.CODINTR1  = I1.CODINTR1
         LEFT  JOIN NIRSTOC  NS  ON COALESCE(AE1.CODINTR1,I1.CODINTR1) = NS.CODINTR1 OR DVI1.CODDVI1 = NS.CODDVI1 OR LV1.CODNIRSTOC = NS.CODNIRSTOC
    WHERE I.DATADOC ' || vCondData || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
          AND I.TipDoc &lt;&gt; 2 AND NOT (I.TIPDOC &lt;&gt; 9 AND COALESCE(I.TIPFACTURA,0) = 9) AND NVL(I.Anulat, 0) = 0 AND NVL(I.Initializari, 0) = 0 AND I.Operat = 1
          AND ((' || coalesce(PKG_LIST_BASE_TOPFURN_GETALLIOART_N()::varchar,'') || ' = 1) OR (NS.CODNIRSTOC IS NULL) OR (EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART'' AND coalesce(VALOARE,'''') = coalesce(NS.CODIOART::varchar,''''))))
          AND  (' || coalesce(PKG_LIST_BASE_TOPFURN_GETALLIOART_N()::varchar,'') || ' = 1  OR I1.TIPLINIE = ''=''   )
          AND (pkg_list_base_topfurn_getallcls_n() = 1 OR EXISTS (SELECT TMP.VALOARE FROM TMP_MANEVRA_LISTE TMP WHERE TMP.FILTRU = ''CODCLASEA'' AND TMP.VALOARE = A.CLASA::varchar))
AND I.PARTENER &gt; 0 AND COALESCE(I1.CANT,0) &lt;&gt; 0
  GROUP BY I.Partener';
  --insert into x(test) values(sselect);
  PERFORM LIST_EXECUTE_IMMEDIATE(sSelect, aListID, aListVer);

  sSelect :='
  SELECT
    coalesce(NAO.Denumire,C.Den_Cont), NUM.Den_UM DenUM, V.Cant Cant, coalesce(V.Val/V.Cant,0) Pret,
    coalesce(V.Val, 0) Valoare,
    coalesce(V.ValCuTVA, 0) ValCuTVA,
    coalesce(V.Val_Val/V.Cant,0) Pret_Val,
    coalesce(V.Val_Val,0)  Valoare_Val,
    coalesce(V.ValCuTVA_Val,0)  ValCuTVA_Val,
    M.SIMBOL Valuta, P.Den_Part,
    ValClient.ValTot, ValClient.ValTotCuTVA, ValClient.ValTot_Val, ValClient.ValTotCuTVA_Val,
    CASE
      WHEN COALESCE(NAO.CodObiect, -1) = -1 THEN COALESCE(FPAC.VAL,0)
      ELSE COALESCE(FPA.VAL,0)
    end,
    COALESCE(FP.RESTA,0) '||gUserAlias||'
  FROM (
        SELECT
          I.Partener CodPart, I1.CodObiect, NULL CodCont, ' || coalesce(sMon,'') || ' Moneda, SUM(coalesce(sign(i1.cant)*lv1.cant,ns.Cantnir,i1.cant)) Cant,
          SUM( (I1.PU*coalesce(sign(i1.cant)*lv1.cant,ns.Cantnir,i1.cant) - CASE WHEN I.TipDOC IN (3)     THEN coalesce(sign(i1.cant)*lv1.cant,ns.Cantnir,i1.cant)/I1.CANT*I1.Tva ELSE 0 END ) * CASE WHEN Coalesce(I.CURS,0) = 0 THEN 1 ELSE I.CURS END  ) Val,
          SUM( (I1.PU*coalesce(sign(i1.cant)*lv1.cant,ns.Cantnir,i1.cant) + CASE WHEN not I.TipDOC IN (3) THEN coalesce(sign(i1.cant)*lv1.cant,ns.Cantnir,i1.cant)/I1.CANT*I1.Tva ELSE 0 END ) * CASE WHEN Coalesce(I.CURS,0) = 0 THEN 1 ELSE I.CURS END  ) ValCuTVA,
          ' || coalesce(CASE WHEN  vInLei = 1 THEN '0' ELSE 'SUM( (I1.PU*coalesce(ns.Cantnir,i1.cant) - CASE WHEN I.TipDOC IN (3)     THEN coalesce(sign(i1.cant)*lv1.cant,ns.Cantnir,i1.cant)/I1.CANT*I1.Tva ELSE 0 END ) * CASE WHEN Coalesce(I.CURS,0) = 0 THEN 1 ELSE I.CURS END  /' || coalesce(sCursRef,'') || ')'
                         END ,'') || ' Val_Val,'
             || coalesce(CASE WHEN  vInLei = 1 THEN '0' ELSE 'SUM( (I1.PU*coalesce(ns.Cantnir,i1.cant) + CASE WHEN not I.TipDOC IN (3) THEN coalesce(sign(i1.cant)*lv1.cant,ns.Cantnir,i1.cant)/I1.CANT*I1.Tva ELSE 0 END ) * CASE WHEN Coalesce(I.CURS,0) = 0 THEN 1 ELSE I.CURS END  /' || coalesce(sCursRef,'') || ')'
                         END ,'') || ' ValCuTVA_Val
        FROM INTRARI I
             INNER JOIN INTRARI1 I1  ON I1.CODINTR    = I.CODINTR
             INNER JOIN NARTOBJ  OBJ ON I1.Codobiect  = OBJ.CodObiect
             INNER JOIN NART     A   ON A.CODARTICOL  = OBJ.CODARTICOL
             INNER JOIN NPART    P   ON I.PARTENER    = P.CODPART
             LEFT  JOIN DVI1         ON DVI1.CODINTR1 = I1.CODINTR1
             LEFT  JOIN INTRLINK L   ON L.CODINTR1    = I1.CODINTR1
             LEFT  JOIN INTRARI1 AE1 ON AE1.CODINTR1  = L.CODLINIEAVIZ
             LEFT  JOIN LIVR1    LV1 ON LV1.CODINTR1  = I1.CODINTR1
             LEFT  JOIN NIRSTOC  NS  ON COALESCE(AE1.CODINTR1,I1.CODINTR1) = NS.CODINTR1 OR DVI1.CODDVI1 = NS.CODDVI1 OR LV1.CODNIRSTOC = NS.CODNIRSTOC
        WHERE I.DATADOC ' || vCondData || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
              AND I.TipDoc &lt;&gt; 2 AND NOT (I.TIPDOC &lt;&gt; 9 AND COALESCE(I.TIPFACTURA,0) = 9) AND NVL(I.Anulat, 0) = 0 AND NVL(I.Initializari, 0) = 0 AND I.Operat = 1
              AND  ('||pkg_list_base_topfurn_getallioart_n()||' = 1  OR I1.TIPLINIE = ''=''   ) AND I1.TipLinie &lt;&gt; ''G''
              AND (('||pkg_list_base_topfurn_getallioart_n()||' = 1) OR (NS.CODNIRSTOC IS NULL) OR (EXISTS (SELECT VALOARE FROM TMP_MANEVRA_LISTE WHERE FILTRU = ''CODIOART''  AND coalesce(VALOARE,'''') = coalesce(NS.CODIOART::varchar,''''))))
              AND ('||pkg_list_base_topfurn_getallcls_n()||' = 1 OR EXISTS (SELECT TMP.VALOARE FROM TMP_MANEVRA_LISTE TMP WHERE TMP.FILTRU = ''CODCLASEA'' AND TMP.VALOARE = A.CLASA::varchar))
              AND COALESCE(I1.CANT,0) &lt;&gt; 0
        GROUP BY I1.CODOBIECT, I.Partener, Sign(I1.Cant)
        UNION ALL
        SELECT I.Partener CodPart, null CodObiect, C.CodCont, ' || coalesce(sMon,'') || ' Moneda, SUM(I1.Cant) Cant,
          SUM( (I1.RestFact - CASE WHEN I.TipDOC IN (3)     THEN I1.Tva ELSE 0 END ) * CASE WHEN Coalesce(I.CURS,0) = 0 THEN 1 ELSE I.CURS END ) Val,
          SUM( (I1.RestFact + CASE WHEN not I.TipDOC IN (3) THEN I1.Tva ELSE 0 END ) * CASE WHEN Coalesce(I.CURS,0) = 0 THEN 1 ELSE I.CURS END ) ValCuTVA,
          ' || coalesce(CASE WHEN  vInLei = 1 THEN '0' ELSE 'SUM( (I1.RestFact - CASE WHEN I.TipDOC IN (3)     THEN I1.Tva ELSE 0 END ) * CASE WHEN Coalesce(I.CURS,0) = 0 THEN 1 ELSE I.CURS END /' || coalesce(sCursRef,'') || ')'
                         END ,'') || ' Val_Val,'
             || coalesce(CASE WHEN  vInLei = 1 THEN '0' ELSE 'SUM( (I1.RestFact + CASE WHEN not I.TipDOC IN (3) THEN I1.Tva ELSE 0 END ) * CASE WHEN Coalesce(I.CURS,0) = 0 THEN 1 ELSE I.CURS END /' || coalesce(sCursRef,'') || ')'
                         END ,'') || ' ValCuTVA_Val
        FROM INTRARI I
             INNER JOIN INTRARI1 I1 ON I1.CODINTR      = I.CODINTR
             INNER JOIN NPART    P  ON I.PARTENER      = P.CODPART
             INNER JOIN NCONT    C  ON I1.ContDiscount = C.CodCont
        WHERE I.DATADOC ' || vCondData || coalesce(PKG_LIST_BASE_UTILS_COND_SUBUNIT('I',NULL,NULL,NULL),'') || '
          AND I.TipDoc &lt;&gt; 2 AND coalesce(I.Anulat, 0) = 0 AND coalesce(I.Initializari, 0) = 0 AND I.Operat = 1
          AND ('||pkg_list_base_topfurn_getallioart_n()||' = 1 OR I1.TIPLINIE = ''='') AND I1.TipLinie = ''G'' AND COALESCE(I1.CANT, 0) &lt;&gt; 0
        GROUP BY C.CodCont, I.Partener, Sign(I1.Cant)
       )  V
          LEFT JOIN TMP_LST_TOP ValClient ON V.CodPart = ValClient.CodPart
          LEFT JOIN TMP_CMD_TMP FP ON FP.CODOBIECT = V.CODPART AND FP.TIP = ''FACTPART''
          LEFT JOIN TMP_CMD_TMP1 FPA ON FPA.COD1 = V.CODPART AND FPA.COD2 = V.CODOBIECT AND FPA.TIP = ''FACTART''
          LEFT JOIN NMONEDE      M    ON M.CODMONEDA    = V.MONEDA
          LEFT JOIN NARTOBJ      NAO  ON NAO.CODOBIECT  = V.CODOBIECT
          LEFT JOIN NART         ART  ON NAO.CodArticol = ART.CodArticol
          LEFT JOIN NCLASEA      CLSA ON ART.Clasa      = CLSA.CodClaseA
          LEFT JOIN NUM               ON ART.UM         = NUM.CODUM
          LEFT JOIN NPART        P    ON V.CodPart      = P.CodPart
          LEFT JOIN NPARTCODFISC CF   ON P.CodPart      = CF.CodPart     AND CF.Principal = 1
          LEFT JOIN NCLASEP      CLSP ON P.CodClasa     = CLSP.CodClaseP
          LEFT JOIN NAGENDA      AG   ON AG.CodPart     = V.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 NJUDET       JUD  ON LOC.CodJudet   = JUD.CodJudet
          LEFT JOIN NCONT C ON V.CodCont = C.CodCont
          LEFT JOIN TMP_CMD_TMP1 FPAC ON FPAC.COD1 = V.CODPART AND FPAC.COD2 = C.CODCONT AND FPA.TIP = ''-FACTART'''||
          gSuplJoins||'
  WHERE V.CANT &lt;&gt; 0
  ORDER BY ValClient.ValTot DESC';
  --insert into x(test) values(sselect);
  PERFORM LIST_EXECUTE_IMMEDIATE(sInsert || sSelect, aListID, aListVer);

  DELETE FROM TMP_CMD_TMP;
  DELETE FROM TMP_CMD_TMP1;
END;
$function$
</obj_text>
</row>

</table>
