--
-- PostgreSQL database dump
--

SET statement_timeout = 0;
SET client_encoding = 'LATIN1';
SET standard_conforming_strings = off;
SET check_function_bodies = false;
SET client_min_messages = warning;
SET escape_string_warning = off;

--
-- Name: plpgsql; Type: PROCEDURAL LANGUAGE; Schema: -; Owner: estlm
--

CREATE PROCEDURAL LANGUAGE plpgsql;


ALTER PROCEDURAL LANGUAGE plpgsql OWNER TO estlm;

SET search_path = public, pg_catalog;

--
-- Name: act_talon(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION act_talon(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select tal_valor from talon where tal_id = $1;$_$;


ALTER FUNCTION public.act_talon(integer) OWNER TO estlm;

--
-- Name: anioastoh(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION anioastoh(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select ash_anio from astoh where ash_id= $1;$_$;


ALTER FUNCTION public.anioastoh(integer) OWNER TO estlm;

--
-- Name: ashdeastc(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION ashdeastc(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select astc_idastoh from astoctas where astc_id= $1 ;$_$;


ALTER FUNCTION public.ashdeastc(integer) OWNER TO estlm;

--
-- Name: astcdecomp(integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION astcdecomp(integer, integer) RETURNS integer
    LANGUAGE sql
    AS $_$select astc_id from astoctas where astc_idastoh= $1 and astc_ctacble= $2 limit 1 ;$_$;


ALTER FUNCTION public.astcdecomp(integer, integer) OWNER TO estlm;

--
-- Name: astcdecompximp(integer, integer, numeric); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION astcdecompximp(integer, integer, numeric) RETURNS integer
    LANGUAGE sql
    AS $_$select astc_id from astoctas where astc_idastoh= $1 and astc_ctacble= $2 and astc_importe= $3 limit 1 ;$_$;


ALTER FUNCTION public.astcdecompximp(integer, integer, numeric) OWNER TO estlm;

--
-- Name: cierre_ejercicio(character varying, date, integer, integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION cierre_ejercicio(character varying, date, integer, integer, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
comprobante	 alias for $1;
fecha		 alias for $2;
tipo		 alias for $3; -- 1 Resultado, 2 Patrimoniales
codemp		 alias for $4;
idptov		 alias for $5;
ret 		 boolean;
registro	 record;
elcomprob 	 integer;
cuentardo 	 integer;
nrocomp 	 integer;
cuenta 	 	 integer;
subcuenta 	 integer;
resultad 	 numeric(15,2);
tituloa	 	 character varying;
idastoh 	 integer;
begin
ret:='f';
    select idcomp(comprobante,idptov) into elcomprob;
    select numtalon(idptov,elcomprob,1) into nrocomp;
    select comp_nombre || ' EJERCICIO CERRADO AL ' || fecha into tituloa from comprob where comp_id=elcomprob;

    insert into astoh (ash_codemp,ash_idptov,ash_anio,ash_mes,ash_comprob,ash_numero,ash_titulo,ash_fecomp,ash_fecval,ash_leyen,ash_nro2,ash_estado) 
	values (codemp,idptov,date_part('year',fecha)::int2,date_part('month',fecha)::int2,elcomprob,nrocomp,tituloa,fecha,fecha,'Cierre de Cuentas del Ejercicio ',0,-1);

    select ash_id into idastoh from astoh where ash_codemp=codemp and ash_idptov=idptov and ash_comprob=elcomprob and ash_numero=nrocomp;

    select idcbl(codemp,valvaramb(codemp,0,'CTARDOE')::integer)  into cuentardo;   

    if(int4eq(tipo,1::int4)) then
	for registro in select 
	    astc_ctacble, sum(astc_importe * -1) as cuanto from astoctas 
	      where astc_estado=2 and astc_codemp=codemp and date_le(astc_fecval,fecha) and codcble(astc_ctacble)>=3000 and codcomp(astc_comprob) not in ('AR','Ar') and astc_fecval>'30-06-2008' group by 1  
	    loop
		if(registro.cuanto != 0) then
		    insert into astoctas (astc_idastoh,astc_ctacble,astc_importe,astc_codemp,astc_idptov,astc_comprob,astc_numero,astc_fecval,astc_estado) 
    	    	     values (idastoh,registro.astc_ctacble,registro.cuanto,codemp,idptov,elcomprob,nrocomp,fecha,-1);	
		end if;
	    end loop; 

	select sum(astc_importe * -1) into resultad from astoctas where astc_idastoh=idastoh;

	
	if(resultad != 0) then
	    insert into astoctas (astc_idastoh,astc_ctacble,astc_importe,astc_codemp,astc_idptov,astc_comprob,astc_numero,astc_fecval,astc_estado) 
    	     values (idastoh,cuentardo,resultad,codemp,idptov,elcomprob,nrocomp,fecha,-1);	
	end if;
	ret:='t';


      else

	for registro in select 
	    astc_ctacble, sum(astc_importe * -1) as cuanto from astoctas 
	      where astc_estado=2 and astc_codemp=codemp and astc_idptov=idptov and date_le(astc_fecval,fecha) and codcomp(astc_comprob) not in ('AR','Ar') and astc_fecval>'31-12-2011'  group by 1
	    loop
		if(registro.cuanto != 0) then
		    insert into astoctas (astc_idastoh,astc_ctacble,astc_importe,astc_codemp,astc_idptov,astc_comprob,astc_numero,astc_fecval,astc_estado) 
		     values (idastoh,registro.astc_ctacble,registro.cuanto,codemp,idptov,elcomprob,nrocomp,fecha,-1);	
		end if;
	    end loop; 

	ret:='t';

    end if;
    return ret;
end;$_$;


ALTER FUNCTION public.cierre_ejercicio(character varying, date, integer, integer, integer) OWNER TO estlm;

--
-- Name: cliedeastc(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION cliedeastc(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select astc_ctacte from astoctas where astc_idastoh= $1 and astc_ctacble=idcbl(astc_codemp,valvaramb(astc_codemp,astc_idptov,'DEUDXV')::integer) limit 1;$_$;


ALTER FUNCTION public.cliedeastc(integer) OWNER TO estlm;

--
-- Name: climodfac(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION climodfac(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select cli_modfac from clientes where cli_id= $1 ;$_$;


ALTER FUNCTION public.climodfac(integer) OWNER TO estlm;

--
-- Name: codcble(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION codcble(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select cbl_codigo::int2 from ctacble where cbl_id= $1 ;$_$;


ALTER FUNCTION public.codcble(integer) OWNER TO estlm;

--
-- Name: codcli(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION codcli(integer) RETURNS character varying
    LANGUAGE sql
    AS $_$select cli_codigo from clientes where cli_id= $1 ;$_$;


ALTER FUNCTION public.codcli(integer) OWNER TO estlm;

--
-- Name: codclideastoh(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION codclideastoh(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select emi_codcli from emiti where emi_idastoh= $1 ;$_$;


ALTER FUNCTION public.codclideastoh(integer) OWNER TO estlm;

--
-- Name: codcomp(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION codcomp(integer) RETURNS character
    LANGUAGE sql
    AS $_$select comp_codigo from comprob where comp_id= $1 ;$_$;


ALTER FUNCTION public.codcomp(integer) OWNER TO estlm;

--
-- Name: codcompash(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION codcompash(integer) RETURNS character
    LANGUAGE sql
    AS $_$select comp_codigo from comprob,astoh where comp_id=ash_comprob and ash_id= $1 ;$_$;


ALTER FUNCTION public.codcompash(integer) OWNER TO estlm;

--
-- Name: codcompastc(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION codcompastc(integer) RETURNS character
    LANGUAGE sql
    AS $_$select comp_codigo from comprob,astoctas where comp_id=astc_comprob and astc_id= $1 ;$_$;


ALTER FUNCTION public.codcompastc(integer) OWNER TO estlm;

--
-- Name: codctes(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION codctes(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select cte_codigo from ctes where cte_id= $1 ;$_$;


ALTER FUNCTION public.codctes(integer) OWNER TO estlm;

--
-- Name: codempcli(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION codempcli(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select cli_codemp from clientes where cli_id= $1;$_$;


ALTER FUNCTION public.codempcli(integer) OWNER TO estlm;

--
-- Name: codprov(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION codprov(integer) RETURNS character varying
    LANGUAGE sql
    AS $_$select prov_codigo from prove where prov_id= $1 ;$_$;


ALTER FUNCTION public.codprov(integer) OWNER TO estlm;

--
-- Name: codprovdeastoh(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION codprovdeastoh(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select cpra_prove from compra where cpra_idastoh= $1 ;$_$;


ALTER FUNCTION public.codprovdeastoh(integer) OWNER TO estlm;

--
-- Name: codptv(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION codptv(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select ptv_codigo from ptovta where ptv_id= $1 ;$_$;


ALTER FUNCTION public.codptv(integer) OWNER TO estlm;

--
-- Name: compbte_fe(character varying); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION compbte_fe(character varying) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	comp		ALIAS FOR $1; -- Comprobante 
    BEGIN
	if trim(comp)='FA' then
	    RETURN 1;
	  else
	    if trim(comp)='DA' then
		RETURN 2;
	      else
		if trim(comp)='CA' then
		    RETURN 3;
		  else
		    if trim(comp)='FB' then
			RETURN 6;
		      else
			if trim(comp)='DB' then
			    RETURN 7;
			  else
			    if trim(comp)='CB' then
				RETURN 8;
			    end if;
			end if;
		    end if;
		end if;
	    end if;
	end if;
    END;$_$;


ALTER FUNCTION public.compbte_fe(character varying) OWNER TO zona;

--
-- Name: compdeastc(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION compdeastc(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select astc_comprob from astoctas where astc_id= $1 ;$_$;


ALTER FUNCTION public.compdeastc(integer) OWNER TO estlm;

--
-- Name: compnro(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION compnro(integer) RETURNS character
    LANGUAGE sql
    AS $_$select a.comp_codigo::character varying||'  -  '||b.ash_numero from comprob a, astoh  b where b.ash_id= $1 and b.ash_comprob=a.comp_id;$_$;


ALTER FUNCTION public.compnro(integer) OWNER TO estlm;

--
-- Name: compnrodeastoctas(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION compnrodeastoctas(integer) RETURNS character varying
    LANGUAGE sql
    AS $_$select comp_codigo::character varying||' - '||astc_numero 
    from comprob,astoctas where comp_id=astc_comprob and astc_id= $1 ;$_$;


ALTER FUNCTION public.compnrodeastoctas(integer) OWNER TO estlm;

--
-- Name: conchequsado(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION conchequsado(integer) RETURNS bigint
    LANGUAGE sql
    AS $_$select count(*) from cheques,astoctas where chq_idastoc=astc_id and astc_idastoh= $1 and chq_idastoce is not null ;$_$;


ALTER FUNCTION public.conchequsado(integer) OWNER TO estlm;

--
-- Name: condocusado(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION condocusado(integer) RETURNS bigint
    LANGUAGE sql
    AS $_$select count(*) from docum,astoctas where doc_idastoc=astc_id and astc_idastoh= $1 and doc_idastoce is not null ;$_$;


ALTER FUNCTION public.condocusado(integer) OWNER TO estlm;

--
-- Name: condolusado(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION condolusado(integer) RETURNS bigint
    LANGUAGE sql
    AS $_$select count(*) from monex,astoctas where mne_idastoc=astc_id and astc_idastoh= $1 and mne_idastoce is not null ;$_$;


ALTER FUNCTION public.condolusado(integer) OWNER TO estlm;

--
-- Name: confactur1confactur(smallint, smallint, date); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION confactur1confactur(smallint, smallint, date) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
anio 		 alias for $1;
mes 		 alias for $2;
fechah 		 alias for $3;
ret 		 boolean;
registro	 record;
directo		 int4;
indirecto	 int4;
tipoper		 int4;
hay	 	 int4;
auxot		 varchar;
begin
ret:='t';
update confactur1 set cfc1_anio=anio, cfc1_mes=mes, cfc1_estado=4 where cfc1_estado=1 and cfc1_fecha <= fechah;

insert into confactur (cfc_usuario,cfc_fecha,cfc_anio,cfc_mes,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_dias,cfc_leyen,cfc_idoper,cfc_estado,cfc_idemiti,cfc_indirecto,cfc_ticket,cfc_ptov) 
select cfc1_usuario,cfc1_fecha,anio,mes,cfc1_idart,cfc1_canti,cfc1_precio,cfc1_importe,cfc1_dias,cfc1_leyen,cfc1_idoper,1,cfc1_idemiti,cfc1_indirecto,cfc1_ticket,cfc1_ptov
 from confactur1 where cfc1_estado=4;
update confactur1 set cfc1_estado=50 where cfc1_estado=4;
return ret;
end;$_$;


ALTER FUNCTION public.confactur1confactur(smallint, smallint, date) OWNER TO estlm;

--
-- Name: conivacli(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION conivacli(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select cli_coniva from clientes where cli_id= $1 ;$_$;


ALTER FUNCTION public.conivacli(integer) OWNER TO estlm;

--
-- Name: conivaprov(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION conivaprov(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select prov_coniva from prove where prov_id= $1 ;$_$;


ALTER FUNCTION public.conivaprov(integer) OWNER TO estlm;

--
-- Name: conpagcli(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION conpagcli(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select cli_conpag from clientes where cli_id= $1 ;$_$;


ALTER FUNCTION public.conpagcli(integer) OWNER TO estlm;

--
-- Name: contindlocador(integer, integer, smallint, smallint, smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION contindlocador(integer, integer, smallint, smallint, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
unifusu		 alias for $1;
indlocad	 alias for $2;
unifun		 alias for $3;
tipo_contrato 	 alias for $4;
modo 		 alias for $5; 	-- 1 solo busca indirecto locador
				-- 2 busca Indirecto locador o reciprocidad
unicont		 int2;
tipusu		 int2;
pame		 int2;
ret 		 boolean;
registro	 RECORD;
hayuno	 	 int2;
hayunoaprob	 int2;

begin

pame:=2;
ret:='f';
hayuno:=0;
hayunoaprob:=0;


select usu_tipusu into tipusu from usuarios where usu_codigo=indlocad;
if(int2eq(tipusu,3::int2)) then
    pame:=1;
end if; 


if(unifusu!=indlocad) then

    if(int2eq(pame,1::int2)) then    

	    for registro in select 
		* from contratos where contr_locador=unifusu and contr_locatario=indlocad and tipo_de_contrato(contr_idsubt)=tipo_contrato and int2eq(contr_estado,1::int2)
	    loop
		if int2eq(unifun,registro.contr_unifun::int2) then  
		hayunoaprob:=1;
		ret:='t'; 
		end if;
	    end loop;
    end if;


    if(int2eq(modo,2::int2) and int2eq(pame,2::int2)) then    

	    for registro in select 
		* from contratos where contr_locador=unifusu 
		and contr_locatario=indlocad 
		and tipo_de_contrato(contr_idsubt) in (2::int2,4::int2,5::int2) 
		and int2eq(contr_estado,1::int2)
	    loop
		ret:='t';
	    end loop;

    end if;

end if;

if(int4eq(unifusu,indlocad)) then
    ret:='t';
end if;

return ret;
END;$_$;


ALTER FUNCTION public.contindlocador(integer, integer, smallint, smallint, smallint) OWNER TO estlm;

--
-- Name: copio_artic_descrip(integer, integer, character varying); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION copio_artic_descrip(integer, integer, character varying) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
operacion	 alias for $1;
item_a_modificar alias for $2;
ladesc	 	 alias for $3;
ret 		 boolean;
registro	 record;
begin

ret:='f';

for registro in select 
    * from subitem where sitem_idoper=operacion and sitem_iditem=item_a_modificar
    loop
	update articu set artic_descrip=ladesc where trim(artic_descrip) like '' and artic_id=registro.sitem_artic;
    ret:='t';
    end loop; 

return ret;
end;$_$;


ALTER FUNCTION public.copio_artic_descrip(integer, integer, character varying) OWNER TO estlm;

--
-- Name: cotpeso(date); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION cotpeso(date) RETURNS numeric
    LANGUAGE sql
    AS $_$select cot_cotiz from cotiza WHERE int2eq(cot_moneda,1::int2) and  date_le(cot_fecha, $1 ::date) order by cot_fecha desc limit 1;$_$;


ALTER FUNCTION public.cotpeso(date) OWNER TO estlm;

--
-- Name: cual_comprob(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION cual_comprob(integer, integer, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	empori		ALIAS FOR $1; 
	empdest		ALIAS FOR $2;
	dato		ALIAS FOR $3;
	cual		character varying;
	retorna		integer;
    BEGIN
	select comp_codigo into cual from comprob where comp_id=dato;
	select comp_id into retorna from comprob where comp_codemp=empdest and bpchareq(comp_codigo,cual);
	RETURN retorna;
    END;$_$;


ALTER FUNCTION public.cual_comprob(integer, integer, integer) OWNER TO estlm;

--
-- Name: cual_consignatario(character varying); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION cual_consignatario(character varying) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	cuit		ALIAS FOR $1; -- Cuit 
	consi		int4;
    BEGIN
	select csg_id into consi from consig where bpchareq(csg_nrocuit,cuit);
		if not found then
		    insert into consig (csg_nrocuit,csg_nombre) values (cuit,'DATO DESCONOCIDO');
		    select csg_id into consi from consig where bpchareq(csg_nrocuit,cuit);
		end if;

	RETURN consi;
    END;$_$;


ALTER FUNCTION public.cual_consignatario(character varying) OWNER TO estlm;

--
-- Name: cual_cuenta(integer, integer, character varying); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION cual_cuenta(integer, integer, character varying) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	empori		ALIAS FOR $1; 
	empdest		ALIAS FOR $2;
	dato		ALIAS FOR $3;
	cual		integer;
	retorna		integer;
    BEGIN
	select codcble(comp_cuenta) into cual from comprob where comp_codemp=empori and bpchareq(comp_codigo,dato);
	select cbl_id into retorna from ctacble where cbl_codemp=empdest and int4eq(cbl_codigo::integer,cual);
	RETURN retorna;
    END;$_$;


ALTER FUNCTION public.cual_cuenta(integer, integer, character varying) OWNER TO estlm;

--
-- Name: cual_despachante(character varying); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION cual_despachante(character varying) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	cuit		ALIAS FOR $1; -- Cuit Despachante
	despa		int4;
    BEGIN
	select desp_id into despa from despach where bpchareq(desp_nrcuit,cuit);
		if not found then
		    insert into despach (desp_tipo,desp_nrcuit,desp_nroreg,desp_nombre) values (1,cuit,'S/D','DATO DESCONOCIDO');
		    select desp_id into despa from despach where bpchareq(desp_nrcuit,cuit);
		end if;

	RETURN despa;
    END;$_$;


ALTER FUNCTION public.cual_despachante(character varying) OWNER TO estlm;

--
-- Name: cual_idsub(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION cual_idsub(integer, integer, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	empori		ALIAS FOR $1; 
	empdest		ALIAS FOR $2;
	dato		ALIAS FOR $3;
	cual		character varying;
	retorna		integer;
    BEGIN
	select subd_nombre into cual from subd where subd_id=dato;
	select subd_id into retorna from subd where subd_codemp=empdest and bpchareq(subd_nombre,cual);
	RETURN retorna;
    END;$_$;


ALTER FUNCTION public.cual_idsub(integer, integer, integer) OWNER TO estlm;

--
-- Name: cual_moneda(character varying); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION cual_moneda(character varying) RETURNS smallint
    LANGUAGE sql
    AS $_$select mon_codigo from moneda where bpchareq(trim(mon_simbol),trim($1));$_$;


ALTER FUNCTION public.cual_moneda(character varying) OWNER TO estlm;

--
-- Name: cuit_fe(character varying); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cuit_fe(character varying) RETURNS character
    LANGUAGE sql
    AS $_$select regexp_replace(regexp_replace(trim($1), '-', ''),'-','');$_$;


ALTER FUNCTION public.cuit_fe(character varying) OWNER TO zona;

--
-- Name: cuitcli(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION cuitcli(integer) RETURNS character
    LANGUAGE sql
    AS $_$select cli_nrcuit from clientes where cli_id= $1 ;$_$;


ALTER FUNCTION public.cuitcli(integer) OWNER TO estlm;

--
-- Name: cuitprov(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION cuitprov(integer) RETURNS character
    LANGUAGE sql
    AS $_$select prov_nrcuit from prove where prov_id= $1 ;$_$;


ALTER FUNCTION public.cuitprov(integer) OWNER TO estlm;

--
-- Name: descartic(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION descartic(integer) RETURNS character
    LANGUAGE sql
    AS $_$select art_codigo||'  -  '||art_nombre from articvta where art_id= $1 ;$_$;


ALTER FUNCTION public.descartic(integer) OWNER TO estlm;

--
-- Name: desccble(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION desccble(integer) RETURNS character
    LANGUAGE sql
    AS $_$select cbl_codigo||'  -  '||cbl_nombre from ctacble where cbl_id= $1 ;$_$;


ALTER FUNCTION public.desccble(integer) OWNER TO estlm;

--
-- Name: desccblep(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION desccblep(integer) RETURNS character
    LANGUAGE sql
    AS $_$select cbl_present||'  -  '||cbl_nombre from ctacble where cbl_id= $1 ;$_$;


ALTER FUNCTION public.desccblep(integer) OWNER TO estlm;

--
-- Name: descchq(smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION descchq(smallint) RETURNS character
    LANGUAGE sql
    AS $_$select bco_codigo||'  -  '||bco_nombre from bancos where bco_codigo= $1 ;$_$;


ALTER FUNCTION public.descchq(smallint) OWNER TO estlm;

--
-- Name: descchqf(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION descchqf(integer) RETURNS character varying
    LANGUAGE sql
    AS $_$select bco_nombre||'  - Nro: '||chq_nucheq||'  - Fecha: '||chq_fecheq||'  - Importe: $ '||chq_importe from cheques,bancos where chq_codbco=bco_codigo and chq_id= $1 ;$_$;


ALTER FUNCTION public.descchqf(integer) OWNER TO estlm;

--
-- Name: descchqt(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION descchqt(integer) RETURNS character varying
    LANGUAGE sql
    AS $_$select bco_nombre||'  - Nro: '||chq_nucheq||'  - Fecha: '||chq_fecheq||'  - Importe: $ '||chq_importe from cheques,bancos where chq_codbco=bco_codigo and chq_id= $1 and chq_idastoce is not null ;$_$;


ALTER FUNCTION public.descchqt(integer) OWNER TO estlm;

--
-- Name: desccli(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION desccli(integer) RETURNS character
    LANGUAGE sql
    AS $_$select cli_codigo||'  -  '||cli_nombre from clientes where cli_id= $1 ;$_$;


ALTER FUNCTION public.desccli(integer) OWNER TO estlm;

--
-- Name: desccli_emiti(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION desccli_emiti(integer) RETURNS character
    LANGUAGE sql
    AS $_$select a.cli_codigo||'  -  '||a.cli_nombre from clientes a, emiti b where a.cli_id=b.emi_codcli and b.emi_id= $1 ;$_$;


ALTER FUNCTION public.desccli_emiti(integer) OWNER TO estlm;

--
-- Name: desccomp(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION desccomp(integer) RETURNS character
    LANGUAGE sql
    AS $_$select trim(comp_codigo)::character varying||'  -  '||rpad(comp_nombre,40,' ') from comprob where comp_id= $1 ;$_$;


ALTER FUNCTION public.desccomp(integer) OWNER TO estlm;

--
-- Name: desccompdeastoctas(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION desccompdeastoctas(integer) RETURNS character varying
    LANGUAGE sql
    AS $_$select comp_codigo::character varying||'  -  '||comp_nombre||'  Nro:  '||astc_numero 
    from comprob,astoctas where comp_id=astc_comprob and astc_id= $1 ;$_$;


ALTER FUNCTION public.desccompdeastoctas(integer) OWNER TO estlm;

--
-- Name: desccompdeastoh(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION desccompdeastoh(integer) RETURNS character varying
    LANGUAGE sql
    AS $_$select comp_codigo::character varying||'  -  '||comp_nombre||'  Nro:  '||ash_numero 
    from comprob,astoh where comp_id=ash_comprob and ash_id= $1 ;$_$;


ALTER FUNCTION public.desccompdeastoh(integer) OWNER TO estlm;

--
-- Name: descctes(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION descctes(integer) RETURNS character
    LANGUAGE sql
    AS $_$select cte_codigo||'  -  '||cte_nombre from ctes where cte_id= $1 ;$_$;


ALTER FUNCTION public.descctes(integer) OWNER TO estlm;

--
-- Name: descemp(integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION descemp(integer, integer) RETURNS character
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	empres		ALIAS FOR $1; 
	ptovt		ALIAS FOR $2; 
	cuantos		integer;
	nomemp 		varchar;
	nomptov		varchar;
	retval 		varchar;
    BEGIN
    
    select count(*) into cuantos from
    	 ptovta where int4eq(empres,ptv_codemp);
    
	 if int4eq(cuantos,1) then
		select emp_nombre into retval from empresa where int4eq(empres,emp_codigo);
	    else
		select emp_nombre into nomemp from empresa where int4eq(empres,emp_codigo);
		select ptv_nombre into nomptov from ptovta where int4eq(ptovt,ptv_id) and int4eq(empres,ptv_codemp);
		retval:= nomemp ||'  -  '|| nomptov;
	 end if;		
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.descemp(integer, integer) OWNER TO estlm;

--
-- Name: descempptv(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION descempptv(integer) RETURNS character
    LANGUAGE sql
    AS $_$select a.emp_nombre||'  -  '||b.ptv_nombre from ptovta b, empresa a where a.emp_codigo=b.ptv_codemp and ptv_id= $1 ;$_$;


ALTER FUNCTION public.descempptv(integer) OWNER TO estlm;

--
-- Name: descfacg(integer, integer, integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION descfacg(integer, integer, integer, integer) RETURNS character varying
    LANGUAGE sql
    AS $_$select desccomp(astc_comprob)||'  Nro  '||astc_numero from astoctas where astc_codemp= $1 and astc_tipcta= $2 and astc_ctacte= $3 and astc_grupo= $4 order by astc_fecval asc,astc_importe desc limit 1;$_$;


ALTER FUNCTION public.descfacg(integer, integer, integer, integer) OWNER TO estlm;

--
-- Name: descfactcpra(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION descfactcpra(integer) RETURNS character varying
    LANGUAGE sql
    AS $_$select 'Prov: '|| cpra_nomprov || '  Factura:  '|| cpra_lecomp ||' - '|| lpad(cpra_sucomp::text,4,'0') ||' - '|| lpad(cpra_nucomp::text,8,'0') from compra where cpra_id= $1 ;$_$;


ALTER FUNCTION public.descfactcpra(integer) OWNER TO estlm;

--
-- Name: descfc(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION descfc(integer) RETURNS character varying
    LANGUAGE sql
    AS $_$select cpra_lecomp ||' - '|| lpad(cpra_sucomp::text,4,'0') ||' - '|| lpad(cpra_nucomp::text,8,'0') from compra where cpra_idastoh= $1 ;$_$;


ALTER FUNCTION public.descfc(integer) OWNER TO estlm;

--
-- Name: descmon(smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION descmon(smallint) RETURNS character
    LANGUAGE sql
    AS $_$select mon_codigo||'  -  '||mon_nombre from moneda where mon_codigo= $1 ;$_$;


ALTER FUNCTION public.descmon(smallint) OWNER TO estlm;

--
-- Name: descprov(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION descprov(integer) RETURNS character
    LANGUAGE sql
    AS $_$select prov_codigo||'  -  '||prov_nombre from prove where prov_id= $1 ;$_$;


ALTER FUNCTION public.descprov(integer) OWNER TO estlm;

--
-- Name: descptv(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION descptv(integer) RETURNS character
    LANGUAGE sql
    AS $_$select ptv_codigo||'  -  '||ptv_nombre from ptovta where ptv_id= $1 ;$_$;


ALTER FUNCTION public.descptv(integer) OWNER TO estlm;

--
-- Name: diasconpag(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION diasconpag(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select cdp_dias from conpag where cdp_codigo= $1 ;$_$;


ALTER FUNCTION public.diasconpag(integer) OWNER TO estlm;

--
-- Name: dsctocli(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION dsctocli(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select cli_descto from clientes where cli_id= $1;$_$;


ALTER FUNCTION public.dsctocli(integer) OWNER TO estlm;

--
-- Name: elimino_op_malas(smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION elimino_op_malas(smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	estado		ALIAS FOR $1; 
	ret 		boolean;
	operacion	int4;
	registro 	RECORD;
    BEGIN
    ret:='f';

    for registro in select op_id as x
    	    from operaciones where op_estado in (1,11) and op_tipoper>100
		loop

		    select ret_id into operacion from retiros where ret_idopera=registro.x;
		    if not found then
			update operaciones set op_fecha_close=date(now()) where op_id=registro.x and op_fecha_close is null;
			ret:='t';
		    end if;		
		end loop; 
    
    update operaciones set op_estado=estado where op_estado in (1,11) and op_tipoper>100 and op_fecha_close=date(now()) ;

return ret;
	
    END;$_$;


ALTER FUNCTION public.elimino_op_malas(smallint) OWNER TO estlm;

--
-- Name: elimino_rexp_vencidas(smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION elimino_rexp_vencidas(smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	estado		ALIAS FOR $1; 
	ret 		boolean;
	operacion	int4;
	registro 	RECORD;
    BEGIN
    ret:='f';

update operaciones set op_estado=estado where op_estado in (1,11) and op_tipoper in (101,105) and op_fechain < date(now())-31 and op_vence=1;

return ret;
	
    END;$_$;


ALTER FUNCTION public.elimino_rexp_vencidas(smallint) OWNER TO estlm;

--
-- Name: elimino_wop_vacias(smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION elimino_wop_vacias(smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	estado		ALIAS FOR $1; 
	ret 		boolean;
	operacion	int4;
	registro 	RECORD;
    BEGIN
    ret:='f';

    for registro in select wop_id as x
    	    from woperaciones where wop_estado in (1,11) and wop_tipoper>100
		loop

		    select wret2_id into operacion from wret2 where wret2_idopera=registro.x;
		    if not found then
			ret:='t';
			update woperaciones set wop_bultos=-1 where wop_id=registro.x ;
		    end if;		
		end loop; 
    
    update woperaciones set wop_estado=999 where wop_bultos=-1 ;


return ret;
	
    END;$_$;


ALTER FUNCTION public.elimino_wop_vacias(smallint) OWNER TO estlm;

--
-- Name: elprecio(integer, integer, character varying); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION elprecio(integer, integer, character varying) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	codemp		ALIAS FOR $1; 
	cli		ALIAS FOR $2; 
	articulo	ALIAS FOR $3; 
	idart 		integer;
	retval 		numeric(15,2);
    BEGIN
    select idarticvta(codemp,articulo) into idart;
    select ltp_precio into retval from
    	 listpre where int4eq(cli,ltp_idcli) and int4eq(idart,ltp_idart);

    if not found then
	    select art_precio into retval from
    		articvta where int4eq(idart,art_id);
    end if;

    if retval is null then
    retval:=0;
    end if;
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.elprecio(integer, integer, character varying) OWNER TO estlm;

--
-- Name: elprecioid(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION elprecioid(integer, integer, integer) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	codemp		ALIAS FOR $1; 
	cli		ALIAS FOR $2; 
	idart		ALIAS FOR $3; 
	retval 		numeric;
    BEGIN
    select ltp_precio into retval from
    	 listpre where int4eq(cli,ltp_idcli) and int4eq(idart,ltp_idart);

    if not found then
	    select art_precio into retval from
    		articvta where int4eq(idart,art_id);
    end if;

    if retval is null then
    retval:=0;
    end if;
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.elprecioid(integer, integer, integer) OWNER TO estlm;

--
-- Name: es_sensible(character varying); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION es_sensible(character varying) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
laposa		alias for $1;
ret		int4;
begin
    select 2 into ret from posarest where bpchareq(posar_codigo,laposa);
    if not found then
	select 2 into ret from posarest where bpchareq(posar_codigo,substr(laposa,1,14));
	if not found then
	    select 2 into ret from posarest where bpchareq(posar_codigo,substr(laposa,1,13));
	    if not found then
		select 2 into ret from posarest where bpchareq(posar_codigo,substr(laposa,1,12));
		if not found then
		    select 2 into ret from posarest where bpchareq(posar_codigo,substr(laposa,1,11));
		    if not found then
			select 2 into ret from posarest where bpchareq(posar_codigo,substr(laposa,1,10));
			if not found then
			    select 2 into ret from posarest where bpchareq(posar_codigo,substr(laposa,1,9));
			    if not found then
				select 2 into ret from posarest where bpchareq(posar_codigo,substr(laposa,1,8));
			        if not found then
			    	    select 2 into ret from posarest where bpchareq(posar_codigo,substr(laposa,1,7));
				    if not found then
					select 2 into ret from posarest where bpchareq(posar_codigo,substr(laposa,1,6));
				        if not found then
					    select 2 into ret from posarest where bpchareq(posar_codigo,substr(laposa,1,5));
				    	    if not found then
						select 2 into ret from posarest where bpchareq(posar_codigo,substr(laposa,1,4));
					    end if;
				        end if;
				    end if;
			        end if;
			    end if;
		        end if;
		    end if;
		end if;
	    end if;
	end if;
    end if;

    if ret is null then
	ret:=1;
    end if;
    
    return ret;
end;$_$;


ALTER FUNCTION public.es_sensible(character varying) OWNER TO estlm;

--
-- Name: estado_opera(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION estado_opera(integer) RETURNS smallint
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	operacion	ALIAS FOR $1; -- id de la Operacion.
	retval		int2;
    BEGIN

    SELECT  op_estado INTO retval
	    FROM operaciones   WHERE int4eq(op_id,operacion);

    RETURN retval;
    END;$_$;


ALTER FUNCTION public.estado_opera(integer) OWNER TO estlm;

--
-- Name: eval_funcion(text); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION eval_funcion(text) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	res		record;
    BEGIN
	for res in execute 'select '||$1||' as result' loop
	return res.result;
	end loop;
END;$_$;


ALTER FUNCTION public.eval_funcion(text) OWNER TO estlm;

--
-- Name: existe_modopub(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION existe_modopub(integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	operacion	ALIAS FOR $1; -- id  Operacion
	operador	int4;
	retval 		boolean;
    BEGIN
    retval:='f';
    select mod_idoperador into operador from modopub where mod_idoper=operacion;
    if found then
	retval:='t';
    end if;		
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.existe_modopub(integer) OWNER TO estlm;

--
-- Name: f_ad_retiros(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_ad_retiros() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    estado 		int2;
    dato 		varchar;
    aux_texto 		text;
    BEGIN

    select op_estado into estado from operaciones 
	where OLD.ret_idopera = op_id;

    if (int2lt(estado,100::int2)) then
        update subitem 
	set sitem_cantcomp= sitem_cantcomp - OLD.ret_cantidad 
	where sitem_id=OLD.ret_idsitem;
    END IF;

    if(int2eq(estado,999::int2) ) then
        update subitem 
	set sitem_cantcomp= sitem_cantcomp - OLD.ret_cantidad 
	where sitem_id=OLD.ret_idsitem;
    END IF;

    if(int2gt(estado,100::int2) and int2ne(estado,999::int2)) then
        update subitem 
	set sitem_cantret= sitem_cantret - OLD.ret_cantidad 
	where sitem_id=OLD.ret_idsitem;
	aux_texto:='El usuario autorizado ha borrado el retiro de la operacion publicada '||OLD.ret_idopera||' que era del subitem '||OLD.ret_idsitem ||' con una cantidad de '||OLD.ret_cantidad ||' el dia de hoy';
	insert into noticias(not_tipo,not_numero,not_texto)values(59,OLD.ret_idopera,aux_texto);
    END IF;

    RETURN OLD;
    END;$$;


ALTER FUNCTION public.f_ad_retiros() OWNER TO estlm;

--
-- Name: f_ad_seguros(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_ad_seguros() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    BEGIN

    if(int2ne(OLD.seg_estado,1::int2)) then
    update unifun set unif_seguro=unif_seguro-OLD.seg_impmoncte where unif_codigo=OLD.seg_unifun;
    end if;
    
    RETURN OLD;
    END;$$;


ALTER FUNCTION public.f_ad_seguros() OWNER TO estlm;

--
-- Name: f_ad_subitem(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_ad_subitem() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
aux_texto 	text;
BEGIN

if int2eq(estadop(OLD.sitem_idoper),101::int2) THEN
    aux_texto:='El usuario autorizado ha borrado el subitem '||OLD.sitem_id ||' de la operacion publicada '||OLD.sitem_idoper||' que tenia un importe de '||OLD.sitem_importe||' del articulo '||OLD.sitem_artic||' con una cantidad de '||OLD.sitem_canting||' el dia de hoy';
    insert into noticias(not_tipo,not_numero,not_texto)values(49,OLD.sitem_idoper,aux_texto);
end if;

RETURN OLD;
END;$$;


ALTER FUNCTION public.f_ad_subitem() OWNER TO estlm;

--
-- Name: f_ad_volegr(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_ad_volegr() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    aux_texto 		text;
    BEGIN

    update voling set vol_cantret= vol_cantret - OLD.vole_cantret where vol_idoper=OLD.vole_idoperi;

    RETURN OLD;
    END;$$;


ALTER FUNCTION public.f_ad_volegr() OWNER TO estlm;

--
-- Name: f_ad_wret2(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_ad_wret2() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    estado 		int2;
    dato 		varchar;
    aux_texto 		text;
    BEGIN

        update wsubitem set wsitem_cantcompw= wsitem_cantcompw - OLD.wret2_cantidad where wsitem_id=OLD.wret2_idsitem;

    RETURN OLD;
    END;$$;


ALTER FUNCTION public.f_ad_wret2() OWNER TO estlm;

--
-- Name: f_ai_artseg(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_ai_artseg() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    BEGIN
    if(int4eq(NEW.as_tipo,1::int4))  THEN 
	    update livianos set lv_estado=NEW.as_estado where lv_id=NEW.as_idorig;
	else
	    update gente set gte_estado=NEW.as_estado,gte_fechas=NEW.as_fechas where gte_id=NEW.as_idorig;
    END IF;
    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_ai_artseg() OWNER TO estlm;

--
-- Name: f_ai_astoctas(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_ai_astoctas() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
	ctabco		integer;
	tctabco		integer;
    BEGIN
    select idcbl(NEW.astc_codemp, valvaramb(NEW.astc_codemp,NEW.astc_idptov,'BANCO')::smallint) into ctabco;
    select valvaramb(NEW.astc_codemp,NEW.astc_idptov,'TCTBANCO') into tctabco;

    if(int4eq(NEW.astc_ctacble,ctabco))  THEN 

	if(NEW.astc_fecvto is null)  THEN 
	    update astoctas set astc_fecvto=NEW.astc_fecval where astc_id=NEW.astc_id;
	END IF;

	if (NEW.astc_tipcta is null) then 
	    update astoctas set astc_tipcta=tctabco where astc_id=NEW.astc_id;
	END IF;

    END IF;
    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_ai_astoctas() OWNER TO estlm;

--
-- Name: f_ai_clientes(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_ai_clientes() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    BEGIN
	insert into sucursalc (sucu_cliente,sucu_nombre) values (NEW.cli_id,NEW.cli_nombre);
    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_ai_clientes() OWNER TO estlm;

--
-- Name: f_ai_contratos(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_ai_contratos() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    BEGIN
    if int4eq(tipo_de_contrato(NEW.contr_idsubt),1) then
	update unifun set unif_usuario=NEW.contr_locatario, unif_estado=1::int2
	where unif_codigo=NEW.contr_unifun;

    end if;
    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_ai_contratos() OWNER TO estlm;

--
-- Name: f_ai_empresa(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_ai_empresa() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    BEGIN
    insert into ptovta (ptv_codemp,ptv_codigo,ptv_nombre,ptv_direcc,ptv_locali,ptv_codpos,ptv_provin,ptv_pais,ptv_codact,ptv_descact)
	 values (NEW.emp_codigo,1,NEW.emp_nombre,NEW.emp_direcc,NEW.emp_locali,NEW.emp_codpos,NEW.emp_provin,NEW.emp_pais,NEW.emp_codact,NEW.emp_descact);
    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_ai_empresa() OWNER TO estlm;

--
-- Name: f_ai_facturacion(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_ai_facturacion() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    BEGIN
	if NEW.fac_anio is null then NEW.fac_anio=date_part('year',NEW.fac_fecha)::int2; end if;
	if NEW.fac_anio is null then NEW.fac_mes=date_part('month',NEW.fac_fecha)::int2; end if;
    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_ai_facturacion() OWNER TO estlm;

--
-- Name: f_ai_item(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_ai_item() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
	tipodeop	int4;
	essensi		int4;
	esta		int4;
BEGIN


    select tipoperdeop(NEW.item_idoper) into tipodeop;
	if int4lt(tipodeop,6) then
	    select es_sensible(NEW.item_posa) into essensi;
	    if int4eq(essensi,2) then
	    select opr_idoper into esta from operest where opr_idoper=NEW.item_idoper and opr_compbte=compbteoper(NEW.item_idoper);
		if not found then
		    insert into operest (opr_idoper,opr_compbte) values (NEW.item_idoper,compbteoper(NEW.item_idoper));
		end if;
	    end if;
	end if;

RETURN NEW;
END;$$;


ALTER FUNCTION public.f_ai_item() OWNER TO estlm;

--
-- Name: f_ai_operaciones(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_ai_operaciones() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
	operacion	int4;
    BEGIN
    update talonop set talop_numero=talop_numero+1 where talop_usuario=NEW.op_directo and talop_tipoper=NEW.op_tipoper;
    update talonop set talop_numero=talop_numero+1 where talop_usuario=1 and talop_tipoper=NEW.op_tipoper;
    select auxo_idoper into operacion from auxoper where auxo_idoper=NEW.op_id;
    if not found then
	insert into auxoper(auxo_idoper) values(NEW.op_id);

	if(int4lt(NEW.op_tipoper,100::int4)) THEN 
	    insert into voling(vol_idoper,vol_directo,vol_indirecto,vol_cliente,vol_compbte,vol_comptrans) values (NEW.op_id,NEW.op_directo,NEW.op_indirecto,idcli(NEW.op_directo,NEW.op_indirecto),NEW.op_compbte,NEW.op_comptrans);
	end if;
    end if;
    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_ai_operaciones() OWNER TO estlm;

--
-- Name: f_ai_retiros(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_ai_retiros() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    existe	int4;
    BEGIN
        update subitem set sitem_cantcomp=sitem_cantcomp+NEW.ret_cantidad where sitem_id=NEW.ret_idsitem;

--estas 4 lineas son las que hay que comentariar si no funca
	select vole_idoper into existe from volegr where vole_idoper=NEW.ret_idopera and vole_idoperi=sitemop(NEW.ret_idsitem);
	if not found then
	    insert into volegr(vole_idoper,vole_idoperi,vole_directo,vole_indirecto,vole_cliente,vole_compbte) values(NEW.ret_idopera,sitemop(NEW.ret_idsitem),directodeop(NEW.ret_idopera),indirectodeop(NEW.ret_idopera),idcli(directodeop(NEW.ret_idopera),indirectodeop(NEW.ret_idopera)),compbteret_idsitem(NEW.ret_idsitem));
	end if;

    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_ai_retiros() OWNER TO estlm;

--
-- Name: f_ai_seguros(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_ai_seguros() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    segvie 		numeric;
    BEGIN

    select unif_seguro into segvie from unifun where unif_codigo=NEW.seg_unifun;
    if segvie is null then segvie:=0; end if;

    update unifun set unif_seguro= segvie + NEW.seg_impmoncte where unif_codigo=NEW.seg_unifun;

    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_ai_seguros() OWNER TO estlm;

--
-- Name: f_ai_subitemd(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_ai_subitemd() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
	operacion	int4;
    BEGIN
	insert into stockd(stk_idsitem,stk_iditem,stk_idoper,stk_codigo,stk_artic,stk_canting,stk_cantret,stk_cantcomp,stk_cantmala,stk_importe,stk_imp_dolar,stk_volumen,stk_peso,stk_tipemb,stk_deposito,stk_idacta,stk_estado,stk_directo,stk_indirecto,stk_compbte,stk_cliente,stk_comptras) values (NEW.sitemd_id,NEW.sitemd_iditem,NEW.sitemd_idoper,NEW.sitemd_codigo,iddearticudm(NEW.sitemd_artic),NEW.sitemd_canting,NEW.sitemd_cantret,NEW.sitemd_cantcomp,NEW.sitemd_cantmala,NEW.sitemd_importe,NEW.sitemd_imp_dolar,NEW.sitemd_volumen,NEW.sitemd_peso,NEW.sitemd_tipemb,NEW.sitemd_deposito,NEW.sitemd_idacta,NEW.sitemd_estado,NEW.sitemd_directo,NEW.sitemd_indirecto,NEW.sitemd_compbte,NEW.sitemd_cliente,NEW.sitemd_comptras);
    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_ai_subitemd() OWNER TO estlm;

--
-- Name: f_ai_usuarios(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_ai_usuarios() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    BEGIN
    insert into talonop values(NEW.usu_codigo,1,1);
    insert into talonop values(NEW.usu_codigo,5,1);
    insert into talonop values(NEW.usu_codigo,10,1);
    insert into talonop values(NEW.usu_codigo,20,1);
    insert into talonop values(NEW.usu_codigo,30,1);
    insert into talonop values(NEW.usu_codigo,101,1);
    insert into talonop values(NEW.usu_codigo,105,1);
    insert into talonop values(NEW.usu_codigo,110,1);
    insert into talonop values(NEW.usu_codigo,120,1);
    insert into talonop values(NEW.usu_codigo,130,1);
    insert into talonop values(NEW.usu_codigo,2,1);
    insert into talonop values(NEW.usu_codigo,3,1);
    insert into talonop values(NEW.usu_codigo,4,1);
    insert into talonop values(NEW.usu_codigo,102,1);
    insert into talonop values(NEW.usu_codigo,103,1);

    insert into sucursales (suc_cliente,suc_codigo,suc_nombre) values(NEW.usu_codigo,1::int2,NEW.usu_nombre);

    if(int2eq(NEW.usu_tipusu,1::int2) or int2eq(NEW.usu_tipusu,3::int2)) then
	insert into clientes (cli_codemp,cli_idptov,cli_codigo,cli_codaso,cli_nrcuit,cli_tipcli,cli_nombre,cli_fantasy,cli_nomabre,cli_coniva,cli_conpag,cli_catego,cli_limcred,cli_interes,cli_grupo,cli_saldo,cli_estado) values (1,1,NEW.usu_codigo,NEW.usu_codigo,NEW.usu_nrocuit,NEW.usu_tipusu,NEW.usu_nombre,NEW.usu_fantasy,NEW.usu_nomabre,NEW.usu_coniva,NEW.usu_conpago,NEW.usu_catego,NEW.usu_limcred,NEW.usu_tasaint,NEW.usu_grupo,NEW.usu_saldo,NEW.usu_estado);
    end if;

    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_ai_usuarios() OWNER TO estlm;

--
-- Name: f_ai_wret2(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_ai_wret2() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    BEGIN
        update wsubitem set wsitem_cantcompw=wsitem_cantcompw+NEW.wret2_cantidad where wsitem_id=NEW.wret2_idsitem;
    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_ai_wret2() OWNER TO estlm;

--
-- Name: f_au_artseg(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_artseg() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
BEGIN
if(int2ne(NEW.as_estado,OLD.as_estado)) THEN 
    if(int4eq(NEW.as_tipo,1::int4))  THEN 
	    update livianos set lv_estado=NEW.as_estado where lv_id=NEW.as_idorig;
	else
	    update gente set gte_estado=NEW.as_estado,gte_fechas=NEW.as_fechas where gte_id=NEW.as_idorig;
    END IF;
END IF;
RETURN NEW;
END;$$;


ALTER FUNCTION public.f_au_artseg() OWNER TO estlm;

--
-- Name: f_au_astoctas(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_astoctas() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
	total	numeric;
	dias	numeric;
BEGIN

    if int4ne(NEW.astc_estado,OLD.astc_estado) THEN 
	update cheques set chq_estado=NEW.astc_estado where chq_idastoc=OLD.astc_id and chq_idastoce is null;
	update monex set mne_estado=NEW.astc_estado where mne_idastoc=OLD.astc_id;
	update docum set doc_estado=NEW.astc_estado where doc_idastoc=OLD.astc_id;
	END IF;

    if int4ne(NEW.astc_ctacte,OLD.astc_ctacte) THEN 
	if int4eq(OLD.astc_ctacble,18) THEN 
	    update emiti set emi_codcli=NEW.astc_ctacte where emi_idastoh=OLD.astc_idastoh;
	END IF;
	
	if int4eq(OLD.astc_ctacble,134) THEN 
		update compra set cpra_prove=NEW.astc_ctacte where cpra_idastoh=OLD.astc_idastoh;
	END IF;
    END IF;

    if (int4ne(NEW.astc_estado,OLD.astc_estado) and int4eq(NEW.astc_estado,2)) THEN 
	select sum(astc_importe) into total from astoctas where astc_idastoh=OLD.astc_idastoh and astc_importe>0;
	update compra set cpra_total=total where cpra_idastoh=OLD.astc_idastoh;
    END IF;


    if (int4eq(NEW.astc_estado,999) and int2eq(NEW.astc_cierra,2::int2) and (int4eq(NEW.astc_ctacble,idcbl(NEW.astc_codemp,valvaramb(NEW.astc_codemp,1,'DEUDXV')::integer)) or int4eq(NEW.astc_ctacble,idcbl(NEW.astc_codemp,valvaramb(NEW.astc_codemp,1,'DEUDXC')::integer))))  THEN 
	update astoctas set astc_cierra=1 where astc_ctacble=NEW.astc_ctacble and astc_tipcta=NEW.astc_tipcta and astc_ctacte=NEW.astc_ctacte and astc_grupo=NEW.astc_grupo and astc_idastoh!=OLD.astc_idastoh;
    END IF;

    if (int4ne(NEW.astc_estado,OLD.astc_estado)  and int2eq(NEW.astc_cierra,2::int2) and int4eq(NEW.astc_ctacble,idcbl(NEW.astc_codemp,valvaramb(NEW.astc_codemp,1,'DEUDXV')::integer))) THEN 
	select diasconpag(emi_conpag) into dias from emiti where emi_idastoh=NEW.astc_idastoh;
	    if found then
		update astoctas set astc_fecvto=astc_fecval+dias::integer where astc_id=NEW.astc_id;
	    end if;
    END IF;


    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_au_astoctas() OWNER TO estlm;

--
-- Name: f_au_astoh(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_astoh() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
BEGIN

    if int4ne(NEW.ash_estado,OLD.ash_estado) THEN 
	update astoctas set astc_estado=NEW.ash_estado where astc_idastoh=OLD.ash_id;
	update compra set cpra_estado=NEW.ash_estado where cpra_idastoh=OLD.ash_id;
	update emiti set emi_estado=NEW.ash_estado where emi_idastoh=OLD.ash_id;
	delete from astoctas where astc_importe=0 and astc_idastoh=OLD.ash_id;
	END IF;

    if (int4ne(NEW.ash_estado,OLD.ash_estado) and int4eq(NEW.ash_estado,999))  THEN 
	update astoctas set astc_cierra=1,astc_idashce=NULL where astc_idastoh=OLD.ash_id;
	END IF;

    if date_ne(NEW.ash_fecval,OLD.ash_fecval) THEN 
	update astoctas set astc_fecval=NEW.ash_fecval where astc_idastoh=OLD.ash_id;
	update compra set cpra_fecval=NEW.ash_fecval where cpra_idastoh=OLD.ash_id;
	update emiti set emi_fecval=NEW.ash_fecval where emi_idastoh=OLD.ash_id;
	update astoh set ash_anio=date_part('year',NEW.ash_fecval),ash_mes=date_part('month',NEW.ash_fecval) where ash_id=OLD.ash_id;
	END IF;

    if date_ne(NEW.ash_fecomp,OLD.ash_fecomp) THEN 
	update compra set cpra_fecori=NEW.ash_fecomp where cpra_idastoh=OLD.ash_id;
	END IF;

    if int4ne(NEW.ash_comprob,OLD.ash_comprob) THEN 
	update astoctas set astc_comprob=NEW.ash_comprob where astc_idastoh=OLD.ash_id;
	update compra set cpra_comprob=NEW.ash_comprob where cpra_idastoh=OLD.ash_id;
	update emiti set emi_comprob=NEW.ash_comprob where emi_idastoh=OLD.ash_id;
	END IF;

    if int4ne(NEW.ash_numero,OLD.ash_numero) THEN 
	update astoctas set astc_numero=NEW.ash_numero where astc_idastoh=OLD.ash_id;
	update compra set cpra_numero=NEW.ash_numero where cpra_idastoh=OLD.ash_id;
	update emiti set emi_numero=NEW.ash_numero where emi_idastoh=OLD.ash_id;
	END IF;

    if int4ne(NEW.ash_codemp,OLD.ash_codemp) THEN 
	update astoctas set astc_codemp=NEW.ash_codemp where astc_idastoh=OLD.ash_id;
	update compra set cpra_codemp=NEW.ash_codemp where cpra_idastoh=OLD.ash_id;
	update emiti set emi_codemp=NEW.ash_codemp where emi_idastoh=OLD.ash_id;
	END IF;

    if int4ne(NEW.ash_idptov,OLD.ash_idptov) THEN 
	update astoctas set astc_idptov=NEW.ash_idptov where astc_idastoh=OLD.ash_id;
	update compra set cpra_idptov=NEW.ash_idptov where cpra_idastoh=OLD.ash_id;
	update emiti set emi_idptov=NEW.ash_idptov where emi_idastoh=OLD.ash_id;
	END IF;

    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_au_astoh() OWNER TO estlm;

--
-- Name: f_au_clientes(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_clientes() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
BEGIN

    if bpcharne(NEW.cli_nombre,OLD.cli_nombre) THEN 
	update sucursalc set sucu_nombre=NEW.cli_nombre where sucu_cliente=OLD.cli_id and sucu_nombre=OLD.cli_nombre;
	END IF;
    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_au_clientes() OWNER TO estlm;

--
-- Name: f_au_compra(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_compra() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
BEGIN
    if(int4ne(NEW.cpra_prove,OLD.cpra_prove)) THEN 
	update compra set cpra_nomprov=nomprove(NEW.cpra_prove), cpra_nrcuit=cuitprov(NEW.cpra_prove),cpra_coniva=conivaprov(NEW.cpra_prove) where cpra_id=OLD.cpra_id;
    END IF;
RETURN NEW;
END;$$;


ALTER FUNCTION public.f_au_compra() OWNER TO estlm;

--
-- Name: f_au_contratos(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_contratos() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
	operacion	int4;
    BEGIN

    if(int2eq(OLD.contr_estado,1::int2) and int2eq(NEW.contr_estado,2::int2) and int4lt(NEW.contr_idsubt,7)) then 

	select contr_id into operacion from contratos where int4lt(contr_idsubt,7) and contr_locatario=NEW.contr_locatario and contr_locador=NEW.contr_locador and contr_estado=1 and contr_id!=OLD.contr_id;
	if not found then
	    select contr_id into operacion from contratos where int4eq(contr_idsubt,11) and contr_locatario=NEW.contr_locatario and contr_estado=1;
	    if not found then
		update contratos set contr_estado=0 where contr_locador=NEW.contr_locatario and contr_estado=1 and contr_idsubt>6;
	    end if;
	end if;

    END IF;


    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_au_contratos() OWNER TO estlm;

--
-- Name: f_au_emiti(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_emiti() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
BEGIN

    if int4ne(NEW.emi_estado,OLD.emi_estado) THEN 
	update movsto set movs_estado=NEW.emi_estado where movs_idemiti=OLD.emi_id;

	if int4eq(NEW.emi_estado,2) THEN 
	    update astoctas set astc_fecvto=astc_fecval+diasconpag(NEW.emi_conpag) where astc_idastoh=OLD.emi_idastoh and astc_ctacble=idcbl(astc_codemp,valvaramb(astc_codemp,0,'DEUDXV')::integer);
	    END IF;

	END IF;

    if int4ne(NEW.emi_codcli,OLD.emi_codcli) THEN 
	update emiti set emi_nomcli=nomcli(NEW.emi_codcli),emi_nrcuit=cuitcli(NEW.emi_codcli),emi_conivac=conivacli(NEW.emi_codcli) where emi_id=OLD.emi_id;
	END IF;



    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_au_emiti() OWNER TO estlm;

--
-- Name: f_au_feccontra(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_feccontra() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    BEGIN

	if(int4eq(NEW.fechac_codevent,5) and date_ne(OLD.fechac_fecha,NEW.fechac_fecha)) then
    	    update tarifas set tari_fhasta=NEW.fechac_fecha where tari_idcontr=NEW.fechac_idcontra;
	end if;

RETURN NEW;
END;$$;


ALTER FUNCTION public.f_au_feccontra() OWNER TO estlm;

--
-- Name: f_au_gente(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_gente() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
BEGIN
if(int2ne(NEW.gte_estado,OLD.gte_estado)) THEN 
    if(int4eq(NEW.gte_estado,31::int4) or int4eq(NEW.gte_estado,21::int4) )  THEN 
	update carvis set cvt_estado=2 where cvt_gente=NEW.gte_id;
    END IF;
END IF;
RETURN NEW;
END;$$;


ALTER FUNCTION public.f_au_gente() OWNER TO estlm;

--
-- Name: f_au_inout(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_inout() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
BEGIN
if(int2ne(NEW.io_estado,OLD.io_estado)) THEN 
    update ingxl set igxl_estado=NEW.io_estado where igxl_io=NEW.io_id;
    update visita set vt_estado=NEW.io_estado where vt_gente=NEW.io_gente;
END IF;
RETURN NEW;
END;$$;


ALTER FUNCTION public.f_au_inout() OWNER TO estlm;

--
-- Name: f_au_item(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_item() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
	aux_texto 	text;
BEGIN
if int2gt(estadop(NEW.item_idoper),100::int2) THEN

    if (int2ne(NEW.item_item,OLD.item_item)) then
	    aux_texto:='El usuario autorizado ha modificado el numero de  item '||NEW.item_id ||' de la operacion publicada '||NEW.item_idoper||' que tenia un codigo '||OLD.item_item||' por el codigo '||NEW.item_item||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(31,NEW.item_idoper,aux_texto);
        end if;

    if (int2ne(NEW.item_moneda,OLD.item_moneda)) then
	    aux_texto:='El usuario autorizado ha modificado el numero de  item '||NEW.item_id ||' de la operacion publicada '||NEW.item_idoper||' que tenia la moneda '||OLD.item_moneda||' por la moneda '||NEW.item_moneda||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(32,NEW.item_idoper,aux_texto);
        end if;

    if (int4ne(NEW.item_tipprod,OLD.item_tipprod)) then
	    aux_texto:='El usuario autorizado ha modificado el numero de  item '||NEW.item_id ||' de la operacion publicada '||NEW.item_idoper||' que tenia tipo de producto '||OLD.item_tipprod||' por el tipo de producto '||NEW.item_tipprod||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(33,NEW.item_idoper,aux_texto);
        end if;

    if (int2ne(NEW.item_unimed,OLD.item_unimed)) then
	    aux_texto:='El usuario autorizado ha modificado el numero de  item '||NEW.item_id ||' de la operacion publicada '||NEW.item_idoper||' que tenia unimed '||OLD.item_unimed||' por la unimed '||NEW.item_unimed||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(34,NEW.item_idoper,aux_texto);
        end if;

    if (bpcharne(NEW.item_posa,OLD.item_posa)) then
	    aux_texto:='El usuario autorizado ha modificado el numero de  item '||NEW.item_id ||' de la operacion publicada '||NEW.item_idoper||' que tenia posicion arancelaria '||OLD.item_posa||' por la pocision arancelaria '||NEW.item_posa||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(35,NEW.item_idoper,aux_texto);
        end if;
end if;
RETURN NEW;
END;$$;


ALTER FUNCTION public.f_au_item() OWNER TO estlm;

--
-- Name: f_au_operaciones(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_operaciones() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
aux_texto 	text;
mal		int2;
trans 		boolean;
notid		int4;
existe		int4;
BEGIN


if(int2eq(NEW.op_estado,1::int2) and int2eq(OLD.op_estado,11::int2)) THEN 
    if(int4eq(NEW.op_tipoper,101::int4) or int4eq(NEW.op_tipoper,105::int4))  THEN 
	aux_texto:=substr(nomusu(NEW.op_indirecto),1,25) || ' / ' || substr(traigo_simbtipoper(NEW.op_tipoper),1,3) || '-'|| NEW.op_nrotaldir;
	select cfc1_id into existe from confactur1 where cfc1_idoper=NEW.op_id;
	if not found then
--	    insert into confactur1 (cfc1_usuario,cfc1_fecha,cfc1_idart,cfc1_canti,cfc1_precio,cfc1_importe,cfc1_idoper,cfc1_leyen,cfc1_estado,cfc1_anio,cfc1_mes,cfc1_indirecto) values (NEW.op_directo,NEW.op_fechain,35::int4,1::numeric,20::numeric,20::numeric,NEW.op_id,aux_texto,1::int2,date_part('year',NEW.op_fechain),date_part('month',NEW.op_fechain),NEW.op_indirecto);
	    insert into confactur1 (cfc1_usuario,cfc1_fecha,cfc1_idart,cfc1_canti,cfc1_precio,cfc1_importe,cfc1_idoper,cfc1_leyen,cfc1_estado,cfc1_anio,cfc1_mes,cfc1_indirecto) values (NEW.op_directo,NEW.op_fechain,35::int4,1::numeric,valtari(NEW.op_directo,35,0::numeric,0::int2,NEW.op_fechain),valtari(NEW.op_directo,35,0::numeric,0::int2,NEW.op_fechain),NEW.op_id,aux_texto,1::int2,date_part('year',NEW.op_fechain),date_part('month',NEW.op_fechain),NEW.op_indirecto);
	END IF;
    END IF;
END IF;

if(int2eq(NEW.op_estado,1::int2) and int2eq(OLD.op_estado,11::int2)) THEN 
    if(int4eq(NEW.op_tipoper,1::int4) or int4eq(NEW.op_tipoper,5::int4))  THEN 
	aux_texto:=substr(nomusu(NEW.op_indirecto),1,25) || ' / ' || substr(traigo_simbtipoper(NEW.op_tipoper),1,3) || '-'|| NEW.op_nrotaldir;
	select cfc1_id into existe from confactur1 where cfc1_idoper=NEW.op_id;
	if not found then
--	    insert into confactur1 (cfc1_usuario,cfc1_fecha,cfc1_idart,cfc1_canti,cfc1_precio,cfc1_importe,cfc1_idoper,cfc1_leyen,cfc1_estado,cfc1_anio,cfc1_mes,cfc1_indirecto) values (NEW.op_directo,NEW.op_fechain,50::int4,1::numeric,20::numeric,20::numeric,NEW.op_id,aux_texto,1::int2,date_part('year',NEW.op_fechain),date_part('month',NEW.op_fechain),NEW.op_indirecto);
	    insert into confactur1 (cfc1_usuario,cfc1_fecha,cfc1_idart,cfc1_canti,cfc1_precio,cfc1_importe,cfc1_idoper,cfc1_leyen,cfc1_estado,cfc1_anio,cfc1_mes,cfc1_indirecto) values (NEW.op_directo,NEW.op_fechain,50::int4,1::numeric,valtari(NEW.op_directo,50,0::numeric,0::int2,NEW.op_fechain),valtari(NEW.op_directo,50,0::numeric,0::int2,NEW.op_fechain),NEW.op_id,aux_texto,1::int2,date_part('year',NEW.op_fechain),date_part('month',NEW.op_fechain),NEW.op_indirecto);
	END IF;
    END IF;
END IF;


if(int2eq(NEW.op_estado,999::int2) and int2lt(OLD.op_estado,100::int2) 
    and int4lt(NEW.op_tipoper,100::int4)) THEN 
    delete from subitem where sitem_idoper=NEW.op_id;
    delete from item where item_idoper=NEW.op_id;
    delete from voling where vol_idoper=NEW.op_id;
end if;

if(int2eq(NEW.op_estado,999::int2) and int2lt(OLD.op_estado,100::int2) 
    and (int4eq(NEW.op_tipoper,101::int4) or int4eq(NEW.op_tipoper,105::int4)) ) THEN 
    delete from retiros where ret_idopera=NEW.op_id;
    delete from volegr where vole_idoper=NEW.op_id;
end if;

if(int2eq(NEW.op_estado,999::int2) and int2lt(OLD.op_estado,100::int2) and int4gt(NEW.op_id,83880) ) THEN
    if(int4eq(NEW.op_tipoper,110::int4) or int4eq(NEW.op_tipoper,120::int4) or int4eq(NEW.op_tipoper,130::int4)) THEN 
    update operaciones set op_estado=999 where op_id=NEW.op_id+1;
    delete from retiros where ret_idopera=NEW.op_id;
    end if;
end if;


if(int2eq(NEW.op_estado,101::int2) and int2eq(OLD.op_estado,1::int2)) THEN 
    if int4lt(NEW.op_tipoper,100::int4)  THEN -- es ingreso
	    trans:=valmer_unifun(NEW.op_id,1::int2,1::int2);
	    update voling set vol_estado=NEW.op_estado where vol_idoper=NEW.op_id;
	else                                  -- es egreso     
	    trans:=valmer_unifun(NEW.op_id,2::int2,1::int2);
	    trans:=cantcomp_cantret(NEW.op_id,1::int2);
	    update volegr set vole_estado=NEW.op_estado,vole_fechaeg=NEW.op_fecha_close where vole_idoper=NEW.op_id;
	END IF;
END IF;

if(int2eq(NEW.op_estado,101::int2) and int2eq(OLD.op_estado,11::int2)) THEN 
    if int4lt(NEW.op_tipoper,100::int4)  THEN -- es ingreso
	    update voling set vol_estado=NEW.op_estado where vol_idoper=NEW.op_id;
	else                                  -- es egreso     
	    update volegr set vole_estado=NEW.op_estado,vole_fechaeg=NEW.op_fecha_close where vole_idoper=NEW.op_id;
	END IF;
END IF;

if(int2eq(NEW.op_estado,1::int2) and int2eq(OLD.op_estado,11::int2)) THEN 
    if int4lt(NEW.op_tipoper,100::int4)  THEN -- es ingreso
	    update voling set vol_estado=NEW.op_estado where vol_idoper=NEW.op_id;
	else                                  -- es egreso     
	    update volegr set vole_estado=NEW.op_estado,vole_fechaeg=NEW.op_fecha_close where vole_idoper=NEW.op_id;
	END IF;
END IF;


if(int2eq(NEW.op_estado,1::int2) and int2eq(OLD.op_estado,101::int2)) THEN 
    if int4lt(NEW.op_tipoper,100::int4)  THEN -- es ingreso
	    trans:=valmer_unifun(NEW.op_id,1::int2,2::int2);
	    update voling set vol_estado=NEW.op_estado where vol_idoper=NEW.op_id;
	else                                  -- es egreso     
	    update volegr set vole_estado=NEW.op_estado,vole_fechaeg=NEW.op_fecha_close where vole_idoper=NEW.op_id;
	    trans:=valmer_unifun(NEW.op_id,2::int2,2::int2);
	    trans:=cantcomp_cantret(NEW.op_id,2::int2);
	END IF;
END IF;


if(int2eq(NEW.op_estado,101::int2) and int2eq(OLD.op_estado,101::int2)) THEN 
	if (int4ne(NEW.op_directo,OLD.op_directo) or
	    int4ne(NEW.op_indirecto,OLD.op_indirecto) or
	    int4ne(NEW.op_tipoper,OLD.op_tipoper) or
	    int4ne(NEW.op_consig,OLD.op_consig) or
	    numeric_ne(NEW.op_importe,OLD.op_importe) or
	    bpcharne(NEW.op_compbte,OLD.op_compbte))  then
		aux_texto:='El usuario autorizado ha modificado la operacion publicada '||NEW.op_id||	' de importe '||OLD.op_importe||' a importe '||NEW.op_importe||' de directo '||OLD.op_directo||' a directo '||NEW.op_directo||' de indirecto '||OLD.op_indirecto||' a indirecto '||NEW.op_indirecto||' de tipoper '||OLD.op_tipoper||' a tipoper '||NEW.op_tipoper||' de compbte '||OLD.op_compbte||' a compbte '||NEW.op_compbte||' de consignatario '||OLD.op_consig||' a consiganatario '||NEW.op_consig||' el dia de hoy';
		insert into noticias(not_tipo,not_numero,not_texto)values(1,NEW.op_id,aux_texto);
		if (int4ne(NEW.op_directo,OLD.op_directo) or int4ne(NEW.op_indirecto,OLD.op_indirecto) or bpcharne(NEW.op_compbte,OLD.op_compbte))   then

		    update voling set vol_compbte=NEW.op_compbte,vol_directo=NEW.op_directo,vol_indirecto=NEW.op_indirecto where vol_idoper=NEW.op_id;
		    update volegr set vole_compbte=NEW.op_compbte,vole_directo=NEW.op_directo,vole_indirecto=NEW.op_indirecto where vole_idoper=NEW.op_id;
		END IF;
	END IF;
END IF;

if(int2ne(NEW.op_moneda,OLD.op_moneda)) THEN 
    update operaciones set op_impdolar=op_importe * ult_cotiz(NEW.op_moneda) where op_id=NEW.op_id;
    update subitem set sitem_imp_dolar=sitem_importe * ult_cotiz(NEW.op_moneda) where sitem_idoper=NEW.op_id;
    update item set item_moneda=NEW.op_moneda where item_idoper=NEW.op_id;
END IF;

if(bpcharne(NEW.op_compbte,OLD.op_compbte)) THEN 
    update subitem set sitem_compbte=NEW.op_compbte where sitem_idoper=NEW.op_id;
    update voling set vol_compbte=NEW.op_compbte where vol_idoper=NEW.op_id;
    update volegr set vole_compbte=NEW.op_compbte,vole_fechaeg=NEW.op_fecha_close where vole_idoper=NEW.op_id;
END IF;




RETURN NEW;
END;$$;


ALTER FUNCTION public.f_au_operaciones() OWNER TO estlm;

--
-- Name: f_au_opervehi(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_opervehi() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
aux_texto 	text;
mal		int2;
trans 		boolean;
notid		int4;
BEGIN



if(int2eq(OLD.opv_est_camion,50::int2) or (int2eq(OLD.opv_est_camion,2::int2) and int2eq(NEW.opv_est_camion,2::int2)) or (int2eq(OLD.opv_est_camion,1::int2) and int2eq(NEW.opv_est_camion,1::int2))) THEN 

    if (int4ne(NEW.opv_idoper,OLD.opv_idoper)) then
	    update contene set cont_idoper=NEW.opv_idoper where cont_idopv=OLD.opv_id;
	    aux_texto:='El usuario autorizado ha modificado el vehiculo '||OLD.opv_id ||' de la operacion publicada '||OLD.opv_idoper||' que tenia un la operacion '||OLD.opv_idoper||' por la operacion '||NEW.opv_idoper||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(81,OLD.opv_idoper,aux_texto);
        end if;

    if (bpcharne(NEW.opv_pat_chasis,OLD.opv_pat_chasis)) then
	    aux_texto:='El usuario autorizado ha modificado el vehiculo '||OLD.opv_id ||' de la operacion publicada '||OLD.opv_idoper||' que tenia como chasis '||OLD.opv_pat_chasis||' por el chasis '||NEW.opv_pat_chasis||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(82,OLD.opv_idoper,aux_texto);
        end if;

    if (bpcharne(NEW.opv_pat_tractor,OLD.opv_pat_tractor)) then
	    aux_texto:='El usuario autorizado ha modificado el vehiculo '||OLD.opv_id ||' de la operacion publicada '||OLD.opv_idoper||' que tenia como tractor '||OLD.opv_pat_tractor||' por el tractor '||NEW.opv_pat_tractor||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(83,OLD.opv_idoper,aux_texto);
        end if;

    if (bpcharne(NEW.opv_chofer,OLD.opv_chofer)) then
	    aux_texto:='El usuario autorizado ha modificado el vehiculo '||OLD.opv_id ||' de la operacion publicada '||OLD.opv_idoper||' que tenia como chofer '||OLD.opv_chofer||' por el chofer '||NEW.opv_chofer||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(84,OLD.opv_idoper,aux_texto);
        end if;

    if (bpcharne(NEW.opv_pat_chasis,OLD.opv_pat_chasis)) then
	    aux_texto:='El usuario autorizado ha modificado el vehiculo '||OLD.opv_id ||' de la operacion publicada '||OLD.opv_idoper||' que tenia como chasis '||OLD.opv_pat_chasis||' por el chasis '||NEW.opv_pat_chasis||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(85,OLD.opv_idoper,aux_texto);
        end if;

    if (bpcharne(NEW.opv_codtd,OLD.opv_codtd)) then
	    aux_texto:='El usuario autorizado ha modificado el vehiculo '||OLD.opv_id ||' de la operacion publicada '||OLD.opv_idoper||' que tenia como tipo de documento '||OLD.opv_codtd||' por el tipo de documento '||NEW.opv_codtd||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(86,OLD.opv_idoper,aux_texto);
        end if;

    if (int2ne(NEW.opv_est_camion,OLD.opv_est_camion)) then
	    aux_texto:='El usuario autorizado ha modificado el vehiculo '||OLD.opv_id ||' de la operacion publicada '||OLD.opv_idoper||' que tenia como estado '||OLD.opv_est_camion||' por el estado '||NEW.opv_est_camion||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(87,OLD.opv_idoper,aux_texto);
        end if;

    if (int4ne(NEW.opv_nro_ticket,OLD.opv_nro_ticket)) then
	    aux_texto:='El usuario autorizado ha modificado el vehiculo '||OLD.opv_id ||' de la operacion publicada '||OLD.opv_idoper||' que tenia como ticket '||OLD.opv_nro_ticket||' por el ticket '||NEW.opv_nro_ticket||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(88,OLD.opv_idoper,aux_texto);
        end if;

    if (bpcharne(NEW.opv_pesa,OLD.opv_pesa)) then
	    aux_texto:='El usuario autorizado ha modificado el vehiculo '||OLD.opv_id ||' de la operacion publicada '||OLD.opv_idoper||' que tenia pesa '||OLD.opv_pesa||' por pesa '||NEW.opv_pesa||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(89,OLD.opv_idoper,aux_texto);
        end if;

    if (numeric_ne(NEW.opv_peso_ing,OLD.opv_peso_ing)) then
	    aux_texto:='El usuario autorizado ha modificado el vehiculo '||OLD.opv_id ||' de la operacion publicada '||OLD.opv_idoper||' que tenia como peso ing '||OLD.opv_peso_ing||' por el peso '||NEW.opv_peso_ing||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(90,OLD.opv_idoper,aux_texto);
        end if;

    if (numeric_ne(NEW.opv_peso_egr,OLD.opv_peso_egr)) then
	    aux_texto:='El usuario autorizado ha modificado el vehiculo '||OLD.opv_id ||' de la operacion publicada '||OLD.opv_idoper||' que tenia como peso egr '||OLD.opv_peso_egr||' por el peso '||NEW.opv_peso_egr||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(91,OLD.opv_idoper,aux_texto);
        end if;

    if (timestamp_ne(NEW.opv_fecha_egr,OLD.opv_fecha_egr)) then
	    aux_texto:='El usuario autorizado ha modificado el vehiculo '||OLD.opv_id ||' de la operacion publicada '||OLD.opv_idoper||' que tenia como fecha egr '||OLD.opv_fecha_egr||' por la fecha '||NEW.opv_fecha_egr||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(92,OLD.opv_idoper,aux_texto);
        end if;

    if (timestamp_ne(NEW.opv_fecha_ing,OLD.opv_fecha_ing)) then
	    aux_texto:='El usuario autorizado ha modificado el vehiculo '||OLD.opv_id ||' de la operacion publicada '||OLD.opv_idoper||' que tenia como fecha ing '||OLD.opv_fecha_ing||' por la fecha '||NEW.opv_fecha_ing||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(93,OLD.opv_idoper,aux_texto);
        end if;


    if (int4ne(NEW.opv_nro_doc,OLD.opv_nro_doc)) then
	    aux_texto:='El usuario autorizado ha modificado el vehiculo '||OLD.opv_id ||' de la operacion publicada '||OLD.opv_idoper||' que tenia como doc '||OLD.opv_nro_doc||' por el doc '||NEW.opv_nro_doc||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(94,OLD.opv_idoper,aux_texto);
        end if;

END IF;


RETURN NEW;
END;$$;


ALTER FUNCTION public.f_au_opervehi() OWNER TO estlm;

--
-- Name: f_au_prove(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_prove() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
BEGIN

    if bpcharne(NEW.prov_nombre,OLD.prov_nombre) THEN 
	update ctes set cte_nombre=NEW.prov_nombre where cte_codigo=OLD.prov_id and cte_codemp=OLD.prov_codemp and cte_tipcta=eval_funcion(valvaramb(NEW.prov_codemp,ptovdefault(NEW.prov_codemp),'TIPCTADXC'));
	END IF;
    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_au_prove() OWNER TO estlm;

--
-- Name: f_au_retiros(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_retiros() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
	aux_texto 	text;
    BEGIN

	if(estadop(NEW.ret_idopera)<100 and numeric_ne(NEW.ret_cantidad,OLD.ret_cantidad)) then
    	    update subitem set sitem_cantcomp=sitem_cantcomp + NEW.ret_cantidad - OLD.ret_cantidad where sitem_id=NEW.ret_idsitem;
	end if;

	if(int2gt(estadop(NEW.ret_idopera),100::int2))then

	    if(numeric_ne(NEW.ret_cantidad,OLD.ret_cantidad)) then
    		update subitem set sitem_cantret=sitem_cantret + NEW.ret_cantidad - OLD.ret_cantidad where sitem_id=NEW.ret_idsitem;
		aux_texto:='El usuario autorizado ha modificado la cantidad del retiro de la operacion publicada '||NEW.ret_idopera||' cambiandola de '||OLD.ret_cantidad ||' a '||NEW.ret_cantidad ||' el dia de hoy';
		insert into noticias(not_tipo,not_numero,not_texto)values(51,NEW.ret_idopera,aux_texto);
	    end if;

	    if(int4ne(NEW.ret_idsitem,OLD.ret_idsitem)) then
    		update subitem set sitem_cantret=sitem_cantret - OLD.ret_cantidad where sitem_id=OLD.ret_idsitem;
    		update subitem set sitem_cantret=sitem_cantret + NEW.ret_cantidad where sitem_id=NEW.ret_idsitem;
		aux_texto:='El usuario autorizado ha modificado el articulo del retiro de la operacion publicada '||NEW.ret_idopera||' cambiandolo del articulo '||OLD.ret_idsitem ||' a '||NEW.ret_idsitem ||' el dia de hoy';
		insert into noticias(not_tipo,not_numero,not_texto)values(52,NEW.ret_idopera,aux_texto);
	    end if;

	end if;

    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_au_retiros() OWNER TO estlm;

--
-- Name: f_au_seguros(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_seguros() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    BEGIN

--cambio el importe pero siempre en estado 1 (vigente)
    if(numeric_ne(OLD.seg_importei,NEW.seg_importei)) then
	if(int2eq(NEW.seg_estado,OLD.seg_estado)) then 
	    update unifun set unif_seguro=unif_seguro - OLD.seg_impmoncte where unif_codigo=OLD.seg_unifun;
	    update unifun set unif_seguro=unif_seguro + NEW.seg_impmoncte where unif_codigo=NEW.seg_unifun;
	END IF;
    END IF;

-- pasa de estado 1 (vigente) a 2 (inactivo o anulado)
    if(int2eq(OLD.seg_estado,1::int2) and int2ne(NEW.seg_estado,1::int2)) then 
	    update unifun set unif_seguro=unif_seguro - OLD.seg_impmoncte where unif_codigo=NEW.seg_unifun;
    END IF;

-- pasa de estado  2 (inactivo o anulado) a 1 (vigente)
    if(int2ne(OLD.seg_estado,1::int2)) then
	if(int2eq(NEW.seg_estado,1::int2)) then 
	    update unifun set unif_seguro=unif_seguro + NEW.seg_impmoncte where unif_codigo=NEW.seg_unifun;
        END IF;
    END IF;

    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_au_seguros() OWNER TO estlm;

--
-- Name: f_au_sucursales(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_sucursales() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
BEGIN

    if bpcharne(NEW.suc_direccl,OLD.suc_direccl) THEN 
	update sucursal set sucu_direccl=NEW.suc_direccl where sucu_cliente=idcli(1,OLD.suc_cliente);
	update sucursal set sucu_direcc=NEW.suc_direccl where sucu_cliente=idcli(1,OLD.suc_cliente);
	END IF;


    if bpcharne(NEW.suc_localil,OLD.suc_localil) THEN 
	update sucursal set sucu_localil=NEW.suc_localil where sucu_cliente=idcli(1,OLD.suc_cliente);
	update sucursal set sucu_locali=NEW.suc_localil where sucu_cliente=idcli(1,OLD.suc_cliente);
	END IF;

    if bpcharne(NEW.suc_codposl,OLD.suc_codposl) THEN 
	update sucursal set sucu_codposl=NEW.suc_codposl where sucu_cliente=idcli(1,OLD.suc_cliente);
	update sucursal set sucu_codpos=NEW.suc_codposl where sucu_cliente=idcli(1,OLD.suc_cliente);
	END IF;

    if int4ne(NEW.suc_codprovl,OLD.suc_codprovl) THEN 
	update sucursal set sucu_codprovl=NEW.suc_codprovl where sucu_cliente=idcli(1,OLD.suc_cliente);
	update sucursal set sucu_provin=NEW.suc_codprovl where sucu_cliente=idcli(1,OLD.suc_cliente);
	END IF;

    if int2ne(NEW.suc_paisl,OLD.suc_paisl) THEN 
	update sucursal set sucu_paisl=NEW.suc_paisl where sucu_cliente=idcli(1,OLD.suc_cliente);
	update sucursal set sucu_pais=NEW.suc_paisl where sucu_cliente=idcli(1,OLD.suc_cliente);
	END IF;


    if bpcharne(NEW.suc_direcc,OLD.suc_direcc) THEN 
	update sucursal set sucu_direcc=NEW.suc_direcc where sucu_cliente=idcli(1,OLD.suc_cliente);
	END IF;

    if bpcharne(NEW.suc_locali,OLD.suc_locali) THEN 
	update sucursal set sucu_locali=NEW.suc_locali where sucu_cliente=idcli(1,OLD.suc_cliente);
	END IF;

    if bpcharne(NEW.suc_codpos,OLD.suc_codpos) THEN 
	update sucursal set sucu_codpos=NEW.suc_codpos where sucu_cliente=idcli(1,OLD.suc_cliente);
	END IF;

    if int4ne(NEW.suc_codprov,OLD.suc_codprov) THEN 
	update sucursal set sucu_provin=NEW.suc_codprov where sucu_cliente=idcli(1,OLD.suc_cliente);
	END IF;

    if int2ne(NEW.suc_pais,OLD.suc_pais) THEN 
	update sucursal set sucu_pais=NEW.suc_pais where sucu_cliente=idcli(1,OLD.suc_cliente);
	END IF;


    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_au_sucursales() OWNER TO estlm;

--
-- Name: f_au_usuarios(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_usuarios() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
BEGIN

    if bpcharne(NEW.usu_nombre,OLD.usu_nombre) THEN 
	update clientes set cli_nombre=NEW.usu_nombre where cli_codigo=OLD.usu_codigo and cli_codemp=1;
	update sucursales set suc_nombre=NEW.usu_nombre where suc_cliente=OLD.usu_codigo;
	END IF;

    if bpcharne(NEW.usu_nrocuit,OLD.usu_nrocuit) THEN 
	update clientes set cli_nrcuit=NEW.usu_nrocuit where cli_codigo=OLD.usu_codigo and cli_codemp=1;
	END IF;

    if bpcharne(NEW.usu_fantasy,OLD.usu_fantasy) THEN 
	update clientes set cli_fantasy=NEW.usu_fantasy where cli_codigo=OLD.usu_codigo and cli_codemp=1;
	END IF;

    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_au_usuarios() OWNER TO estlm;

--
-- Name: f_au_volegr(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_volegr() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE

aux_texto 	text;
mal		int2;
registro	 record;
trans 		boolean;
funcion		text;
importe		numeric;
cantidad	numeric;
precio		numeric;
canting		numeric;
cantret		numeric;
sigo		int4;

BEGIN

if(numeric_ne(NEW.vole_cantret,OLD.vole_cantret)) THEN 

    select vol_canting, vol_cantret into canting,cantret from voling  where vol_idoper=OLD.vole_idoperi;
    cantret:= cantret+NEW.vole_cantret-OLD.vole_cantret;
    if numeric_lt(canting,cantret) then
	RAISE EXCEPTION  'EL VOLUMEN RETIRADO NO PODRA SER NUNCA MAYOR QUE EL INGRESADO';
    end if;

    update voling set vol_cantret=vol_cantret+NEW.vole_cantret-OLD.vole_cantret where vol_idoper=OLD.vole_idoperi;

    for registro in select * from complfac where cfac_codemp=NEW.vole_directo and cfac_estado=1 and cfac_evento=2 
	loop

	sigo:=1;

	if(registro.cfac_fechad) then
	    if date_lt(NEW.vole_fechaeg,registro.cfac_fechad) then
		sigo:=2;  
	    end if;
	end if;

	if(registro.cfac_fechah) then
	    if date_gt(NEW.vole_fechaeg,registro.cfac_fechah) then
		sigo:=2;  
	    end if;
	end if;

        if int4eq(sigo,1) then
	    select fac_estado into mal from facturacion where fac_codemp=NEW.vole_directo and fac_cliente=NEW.vole_cliente and fac_idoper=NEW.vole_idoper and fac_ptov=registro.cfac_ptov and fac_idart=registro.cfac_idart and fac_estado!=1 limit 1;
	    if not found then
		delete from facturacion where fac_codemp=NEW.vole_directo and fac_cliente=NEW.vole_cliente and fac_idoper=NEW.vole_idoper and fac_ptov=registro.cfac_ptov and fac_idart=registro.cfac_idart and fac_estado=1;
		aux_texto:=registro.cfac_leyen || ' ( Operacion:  ' || traigo_simbtipoper(tipoperdeop(NEW.vole_idoper)) || ' - ' ||nrotaldiroper(NEW.vole_idoper)  || ' ) ';
		if(int4eq(registro.cfac_cliente,NEW.vole_cliente) or  registro.cfac_cliente is null) then
		    precio:=calculo_funcion(registro.cfac_id,registro.cfac_idart,NEW.vole_idoper,2);
		    importe:=precio * registro.cfac_dias * registro.cfac_canti;
		    cantidad:=tiene_funcion(registro.cfac_id,registro.cfac_idart,NEW.vole_idoper,2);
		    if cantidad then
			cantidad:=precio / cantidad;
		      else
			cantidad:=1;
		    end if;
		end if;
		insert into facturacion (fac_codemp,fac_cliente,fac_fecha,fac_anio,fac_mes,fac_idoper,fac_leyen,fac_ptov,fac_idart,fac_canti,fac_dias,fac_precio,fac_importe) values (NEW.vole_directo,NEW.vole_cliente,NEW.vole_fechaeg,date_part('year',NEW.vole_fechaeg),date_part('month',NEW.vole_fechaeg),NEW.vole_idoper,aux_texto,registro.cfac_ptov,registro.cfac_idart,cantidad,registro.cfac_dias,precio,importe);
	    end if;
	end if;
    end loop; 
END IF;

RETURN NEW;
END;$$;


ALTER FUNCTION public.f_au_volegr() OWNER TO estlm;

--
-- Name: f_au_voling(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_voling() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE

aux_texto 	text;
mal		int2;
registro	 record;
trans 		boolean;
funcion		text;
importe		numeric;
precio		numeric;
sigo		int4;

BEGIN

if(numeric_ne(NEW.vol_canting,OLD.vol_canting)) THEN 
    for registro in select * from complfac where cfac_codemp=NEW.vol_directo and cfac_estado=1 and cfac_evento=1 
    loop
	sigo:=1;

	if(registro.cfac_fechad) then
	    if date_lt(NEW.vol_fechain,registro.cfac_fechad) then
		sigo:=2;  
	    end if;
	end if;

	if(registro.cfac_fechah) then
	    if date_gt(NEW.vol_fechain,registro.cfac_fechah) then
		sigo:=2;  
	    end if;
	end if;

        if int4eq(sigo,1) then
	    select fac_estado into mal from facturacion where fac_codemp=NEW.vol_directo and fac_cliente=NEW.vol_cliente and fac_idoper=NEW.vol_idoper and fac_ptov=registro.cfac_ptov and fac_idart=registro.cfac_idart and fac_estado!=1 limit 1;
	    if not found then
		delete from facturacion where fac_codemp=NEW.vol_directo and fac_cliente=NEW.vol_cliente and fac_idoper=NEW.vol_idoper and fac_ptov=registro.cfac_ptov and fac_idart=registro.cfac_idart and fac_estado=1;
		aux_texto:=registro.cfac_leyen || ' ( Operacion:  ' || traigo_simbtipoper(tipoperdeop(NEW.vol_idoper)) || ' - ' ||nrotaldiroper(NEW.vol_idoper)  || ' ) ';
		if(int4eq(registro.cfac_cliente,NEW.vol_cliente) or  registro.cfac_cliente is null) then
		    precio:=calculo_funcion(registro.cfac_id,registro.cfac_idart,NEW.vol_idoper,1);
		    importe:=precio * registro.cfac_dias * registro.cfac_canti;
		end if;
		insert into facturacion (fac_codemp,fac_cliente,fac_fecha,fac_anio,fac_mes,fac_idoper,fac_leyen,fac_ptov,fac_idart,fac_canti,fac_dias,fac_precio,fac_importe) values (NEW.vol_directo,NEW.vol_cliente,NEW.vol_fechain,date_part('year',NEW.vol_fechain),date_part('month',NEW.vol_fechain),NEW.vol_idoper,aux_texto,registro.cfac_ptov,registro.cfac_idart,registro.cfac_canti,registro.cfac_dias,precio,importe);
	    end if;
	end if;
    end loop; 
END IF;

RETURN NEW;
END;$$;


ALTER FUNCTION public.f_au_voling() OWNER TO estlm;

--
-- Name: f_au_woperaciones(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_woperaciones() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
aux_texto 	text;
mal		int2;
trans 		boolean;
notid		int4;
BEGIN

if(int2ne(NEW.wop_estado,OLD.wop_estado)) THEN 
    update wret2 set wret2_estado=NEW.wop_estado where wret2_idopera=NEW.wop_id;
end if;

if(int2eq(NEW.wop_estado,999::int2)) THEN 
    delete from wret2 where wret2_idopera=NEW.wop_id;
end if;


RETURN NEW;
END;$$;


ALTER FUNCTION public.f_au_woperaciones() OWNER TO estlm;

--
-- Name: f_au_wret2(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_au_wret2() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
	aux_texto 	text;
    BEGIN

	if(numeric_ne(NEW.wret2_cantidad,OLD.wret2_cantidad)) then
	    update wsubitem set wsitem_cantcompw=wsitem_cantcompw + NEW.wret2_cantidad - OLD.wret2_cantidad where wsitem_id=NEW.wret2_idsitem;
	end if;

	if(int4ne(NEW.wret2_idsitem,OLD.wret2_idsitem)) then
    	    update wsubitem set wsitem_cantcompw=wsitem_cantcompw - OLD.wret2_cantidad where wsitem_id=OLD.wret2_idsitem;
    	    update wsubitem set wsitem_cantcompw=wsitem_cantcompw + NEW.wret2_cantidad where wsitem_id=NEW.wret2_idsitem;
	end if;

    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_au_wret2() OWNER TO estlm;

--
-- Name: f_bd_astoctas(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_bd_astoctas() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    cuantos		int4;
    BEGIN

----------------------------  CHEQUES ---------------------------------------    
	
    select count(*) into cuantos from cheques where int4eq(chq_idastoc,OLD.astc_id);
    if int4ne(cuantos,0) then
	select count(*) into cuantos from cheques where int4eq(chq_idastoc,OLD.astc_id) and chq_idastoce is not null;
	if int4ne(cuantos,0) then
		RAISE EXCEPTION  'NO SE PUEDE BORRAR UN CHEQUE ASIGNADO ANTERIORMENTE';
	    else
		delete from cheques where int4eq(chq_idastoc,OLD.astc_id);
	END IF;
    END IF;


    select count(*) into cuantos from cheques where int4eq(chq_idastoce,OLD.astc_id);
    if found then
	update cheques set chq_estado=2,chq_idastoce=NULL where int4eq(chq_idastoce,OLD.astc_id);
    END IF;

----------------------------  MONEX ---------------------------------------    

    select count(*) into cuantos from monex where int4eq(mne_idastoc,OLD.astc_id);
    if int4ne(cuantos,0) then
	select count(*) into cuantos from monex where int4eq(mne_idastoc,OLD.astc_id) and mne_idastoce is not null;
	if int4ne(cuantos,0) then
		RAISE EXCEPTION  'NO SE PUEDE BORRAR UN BILLETE ASIGNADO ANTERIORMENTE';
	    else
		delete from monex where int4eq(mne_idastoc,OLD.astc_id);
	END IF;
    END IF;

    select count(*) into cuantos from monex where int4eq(mne_idastoce,OLD.astc_id);
    if found then
	update monex set mne_estado=2,mne_idastoce=NULL where int4eq(mne_idastoce,OLD.astc_id);
    END IF;


----------------------------  DOCUM ---------------------------------------    

    select count(*) into cuantos from docum where int4eq(doc_idastoc,OLD.astc_id);
    if int4ne(cuantos,0) then
	select count(*) into cuantos from docum where int4eq(doc_idastoc,OLD.astc_id) and doc_idastoce is not null;
	if int4ne(cuantos,0) then
		RAISE EXCEPTION  'NO SE PUEDE BORRAR UN BILLETE ASIGNADO ANTERIORMENTE';
	    else
		delete from docum where int4eq(doc_idastoc,OLD.astc_id);
	END IF;
    END IF;

    select count(*) into cuantos from docum where int4eq(doc_idastoce,OLD.astc_id);
    if found then
	update docum set doc_estado=2,doc_idastoce=NULL where int4eq(doc_idastoce,OLD.astc_id);
    END IF;

    
    RETURN OLD;
    END;$$;


ALTER FUNCTION public.f_bd_astoctas() OWNER TO estlm;

--
-- Name: f_bd_astoh(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_bd_astoh() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    cuantos		int4;
    BEGIN

    delete from emiti where int4eq(emi_idastoh,OLD.ash_id);
--    delete from compliq where int4eq(cliq_idastoh,OLD.ash_id);
    delete from compra where int4eq(cpra_idastoh,OLD.ash_id);
    delete from astoctas where int4eq(astc_idastoh,OLD.ash_id);
    update astoctas set astc_cierra=1,astc_idashce=NULL where astc_idastoh=OLD.ash_id;
    
    RETURN OLD;
    END;$$;


ALTER FUNCTION public.f_bd_astoh() OWNER TO estlm;

--
-- Name: f_bd_emiti(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_bd_emiti() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    cuantos		int4;
    BEGIN

    delete from movsto where int4eq(movs_idemiti,OLD.emi_id);
    
    RETURN OLD;
    END;$$;


ALTER FUNCTION public.f_bd_emiti() OWNER TO estlm;

--
-- Name: f_bd_empresa(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_bd_empresa() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    cuantos		int4;
    BEGIN

    delete from zona where int4eq(zon_codemp,OLD.emp_codigo);
    delete from vendedor where int4eq(ven_codemp,OLD.emp_codigo);
    delete from varambi where int4eq(vari_codemp,OLD.emp_codigo);
    delete from telefon where int4eq(tel_codemp,OLD.emp_codigo);
    delete from talon where int4eq(tal_codemp,OLD.emp_codigo);
    delete from subd where int4eq(subd_codemp,OLD.emp_codigo);
    delete from prove where int4eq(prov_codemp,OLD.emp_codigo);
    delete from clientes where int4eq(cli_codemp,OLD.emp_codigo);
    delete from ctes where int4eq(cte_codemp,OLD.emp_codigo);
    delete from ctacble where int4eq(cbl_codemp,OLD.emp_codigo);
    delete from cotiza where int4eq(cot_codemp,OLD.emp_codigo);
    delete from conpag where int4eq(cdp_codemp,OLD.emp_codigo);
    delete from interes where int4eq(int_codemp,OLD.emp_codigo);
    delete from listpre where int4eq(ltp_codemp,OLD.emp_codigo);
    delete from articvta where int4eq(art_codemp,OLD.emp_codigo);
    delete from comprob where int4eq(comp_codemp,OLD.emp_codigo);
    delete from centroc where int4eq(cco_codemp,OLD.emp_codigo);
    delete from division where int4eq(div_codemp,OLD.emp_codigo);
    delete from ptovta where int4eq(ptv_codemp,OLD.emp_codigo);

    RETURN OLD;
    END;$$;


ALTER FUNCTION public.f_bd_empresa() OWNER TO estlm;

--
-- Name: f_bd_subitem(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_bd_subitem() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
aux_texto 	text;
salidas		numeric;

BEGIN

-- if int2eq(estadop(OLD.sitem_idoper),101::int2) THEN
--    if booleq(existe_modopub(OLD.sitem_idoper),'f') THEN 
--	    RAISE EXCEPTION  'USTED NO ESTA AUTORIZADO A MODIFICAR UNA OPERACION PUBLICADA';
--	else
--	    update operaciones set op_estado=102 where op_id=OLD.sitem_idoper;
--    end if;
-- end if;

-- if int2eq(estadop(OLD.sitem_idoper),1::int2) THEN
--    aux_texto:='Ha modificado un subitem de la operacion '||OLD.sitem_idoper||'  debera corroborar nuevamente si se puede oficializar';
--    insert into noticias(not_tipo,not_numero,not_texto)values(1,OLD.sitem_idoper,aux_texto);
--    update operaciones set op_estado=11 where op_id=OLD.sitem_idoper;
-- end if;

if int2eq(estadop(OLD.sitem_idoper),101::int2) THEN
    salidas:=OLD.sitem_cantret+OLD.sitem_cantcomp;
    if(numeric_ne(salidas,0::numeric)) then
        RAISE EXCEPTION  'NO SE PUEDE BORRAR ESTE SUBITEM POR EXISTIR RETIROS O REEXPEDICIONES QUE AFECTAN AL MISMO';
    END IF;
END IF;
RETURN OLD;
END;$$;


ALTER FUNCTION public.f_bd_subitem() OWNER TO estlm;

--
-- Name: f_bi_contratos(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_bi_contratos() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    ale 		int2;
    usua 		int4;
    BEGIN
    select unif_codigo into ale from unifun where unif_codigo=NEW.contr_unifun;
    if not found then
	NEW.contr_unifun:=0;
    end if;

    select usu_codigo into usua from usuarios where usu_codigo=NEW.contr_locador;
    if not found then
	NEW.contr_locador:=1;
    end if;

    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_bi_contratos() OWNER TO estlm;

--
-- Name: f_bi_item(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_bi_item() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
	usu1 		int4;
	usu2 		int4;
	aux_texto 	text;
BEGIN

--	NEW.item_item=cantitem(NEW.item_idoper)+1;

RETURN NEW;
END;$$;


ALTER FUNCTION public.f_bi_item() OWNER TO estlm;

--
-- Name: f_bi_lecting(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_bi_lecting() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
    BEGIN
	delete from lecting where let_estado=1 and let_tarje=NEW.let_tarje;

    if(tarjehabilit(NEW.let_tarje) is NULL) then
	    RAISE EXCEPTION  'LA TARJETA NO EXISTE O NO ESTA HABILITADA';
    END IF;

    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_bi_lecting() OWNER TO estlm;

--
-- Name: f_bi_operaciones(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_bi_operaciones() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
aux_texto 	text;
BEGIN
--	if (hay_contrato (NEW.op_directo, NEW.op_indirecto, 1::int2,0,3::int2)!=true )THEN 
--	    aux_texto:='En la Operacion '||traigo_simbtipoper(NEW.op_tipoper)||' '||NEW.op_nrotalzon||' no existe contrato entre el directo '||NEW.op_directo||'  ('||nomusu(NEW.op_directo) ||')     y el indirecto '||NEW.op_indirecto||'  ('||nomusu(NEW.op_indirecto)||')';
--	    insert into noticias(not_tipo,not_numero,not_texto)values(1,NEW.op_id,aux_texto);
--	END IF;

--    if ( NEW.op_tipoper<100 and seg_disponible(NEW.op_deposito, NEW.op_importe,1::int2)!=true) THEN 
--	aux_texto:='En la Operacion '||traigo_simbtipoper(NEW.op_tipoper)||' '||NEW.op_nrotalzon||' el deposito '||NEW.op_deposito||'  ('||traigo_nomunifun(NEW.op_deposito::int2)||') no tiene el seguro necesario';
--	insert into noticias(not_tipo,not_numero,not_texto)values(1,NEW.op_id,aux_texto);
--	END IF;

--    if ( NEW.op_tipoper>100 and ctacte_ok(NEW.op_directo)!=true) THEN 
--	aux_texto:='En la Operacion '||traigo_simbtipoper(NEW.op_tipoper)||' '||NEW.op_nrotalzon||' el usuario directo '||NEW.op_directo||'  ('||nomusu(NEW.op_directo) ||')  esta inhabilitado por falta de pago   ';
--	insert into noticias(not_tipo,not_numero,not_texto)values(1,NEW.op_id,aux_texto);
--	END IF;
    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_bi_operaciones() OWNER TO estlm;

--
-- Name: f_bi_puertos(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_bi_puertos() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    nompais 		varchar;
    BEGIN
    select pai_nombre into nompais from pais where pai_codigo=NEW.pue_pais;
    if not found then
	insert into pais values(NEW.pue_pais,'DATO DESCONOCIDO');
    end if;
    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_bi_puertos() OWNER TO estlm;

--
-- Name: f_bi_retiros(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_bi_retiros() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    BEGIN
    if cantidad_disponible(NEW.ret_idsitem)<NEW.ret_cantidad then
	RAISE EXCEPTION  'LA CANTIDAD A RETIRAR ES MAYOR A LAS DISPONIBILIDADES';
    END IF;
    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_bi_retiros() OWNER TO estlm;

--
-- Name: f_bi_subitem(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_bi_subitem() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
	usu1 		int4;
	usu2 		int4;
	aux_texto 	text;
BEGIN

if numeric_eq(NEW.sitem_imp_dolar,0::numeric) then
    NEW.sitem_imp_dolar:=moncteopera(NEW.sitem_idoper) * NEW.sitem_importe;
end if;

--     if(tipprod_posible(NEW.sitem_deposito,(select item_tipprod from item where item_id=NEW.sitem_iditem)) !=true) then	
--	aux_texto:='El tipo de mercaderia no puede ser almacenada en la unidad funcional '||NEW.sitem_deposito||'  ('||traigo_nomunifun(NEW.sitem_deposito)||')';	 
--	insert into noticias(not_tipo,not_numero,not_texto)values(1,NEW.sitem_idoper,aux_texto);
--	END IF;

--    select unif_usuario into usu1 from unifun where int2eq(unif_codigo,NEW.sitem_deposito);
--    select op_directo into usu2 from operaciones where op_id=NEW.sitem_idoper;
--    if (hay_contrato(usu1, usu2, 1::int2 ,NEW.sitem_idoper, 2::int2)!=true ) THEN 
--	aux_texto:='No Hay CONTRATO DE SERVICIO(2) PARA EL SUBITEM entre  '||usu1||'  ('||nomusu(usu1) ||')  y  '||usu2 ||'  ('||nomusu(usu2)||') ';
--	insert into noticias(not_tipo,not_numero,not_texto)values(1,NEW.sitem_idoper,aux_texto);
--	END IF;

RETURN NEW;
END;$$;


ALTER FUNCTION public.f_bi_subitem() OWNER TO estlm;

--
-- Name: f_bu_astoh(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_bu_astoh() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
saldo	numeric;
BEGIN


if(int4eq(NEW.ash_estado,2) and int4eq(OLD.ash_estado,-1)) THEN 


------------------ PARTIDA DOBLE -----------------------------------

    select sum(astc_importe) into saldo from astoctas where astc_idastoh=NEW.ash_id;
    if numeric_ne(saldo,0) then
	RAISE EXCEPTION  'NO SE PUEDE FINALIZAR EL ASIENTO YA QUE EL SALDO ES DISTINTO DE CERO';
    end if;

------------------ CASO CHEQUES -----------------------------------



END IF;
    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_bu_astoh() OWNER TO estlm;

--
-- Name: f_bu_caratula(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_bu_caratula() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
	aux_texto 	text;
BEGIN

    if(textne(NEW.despacho,OLD.despacho))
    then
	update items set items_despacho=NEW.despacho where items_idcaratula=NEW.car_id;
    END IF;

    if(textne(NEW.transito,OLD.transito))
    then
	update items set items_transito=NEW.transito where items_idcaratula=NEW.car_id;
    END IF;
	
RETURN NEW;
END;$$;


ALTER FUNCTION public.f_bu_caratula() OWNER TO estlm;

--
-- Name: f_bu_cheques(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_bu_cheques() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
saldo	numeric;
BEGIN


if(int4eq(NEW.chq_estado,2) and int4ne(OLD.chq_estado,2)) THEN 


    select astc_importe into saldo from astoctas where astc_id=NEW.chq_idastoce;
    if found then
	RAISE EXCEPTION  'NO SE PUEDE CAMBIAR DE ESTADO UN CHEQUE UTILIZADO';
    end if;

END IF;
    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_bu_cheques() OWNER TO estlm;

--
-- Name: f_bu_operaciones(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_bu_operaciones() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
aux_texto 	text;
mal		int2;
salidas		numeric;
trans 		boolean;
notid		int4;
BEGIN

if(int2eq(NEW.op_estado,1::int2) and int2eq(OLD.op_estado,11::int2)) THEN 
NEW.op_fechain:=date(now());
END IF;

if(int2eq(NEW.op_estado,1::int2)and int2eq(OLD.op_estado,101::int2)) THEN 
    if int4lt(NEW.op_tipoper,100::int4)  THEN -- es ingreso
	select sum(sitem_cantret)+sum(sitem_cantcomp) into salidas 
	    from subitem where sitem_idoper=NEW.op_id;
	if(numeric_ne(salidas,0::numeric)) then
	    RAISE EXCEPTION  'NO SE PUEDE MODIFICAR ESTA OPERACION POR EXISTIR RETIROS O REEXPEDICIONES QUE AFECTAN LA MISMA';
	END IF;
    END IF;
END IF;

RETURN NEW;
END;$$;


ALTER FUNCTION public.f_bu_operaciones() OWNER TO estlm;

--
-- Name: f_bu_retiros(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_bu_retiros() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
	aux_texto 	text;
BEGIN

    if ((cantidad_disponible(NEW.ret_idsitem)+OLD.ret_cantidad)<NEW.ret_cantidad) then
	RAISE EXCEPTION  'LA CANTIDAD A RETIRAR ES MAYOR A LAS DISPONIBILIDADES';
    END IF;
	
RETURN NEW;
END;$$;


ALTER FUNCTION public.f_bu_retiros() OWNER TO estlm;

--
-- Name: f_bu_seguros(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_bu_seguros() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    BEGIN

--    if(date_lt(date(NEW.seg_hasta),date('now()'))) then 
--	RAISE EXCEPTION  'LA FECHA DE EXPIRACION NO PUEDE SER MENOR A LA ACTUAL';
--    END IF;

    if(date_lt(date(NEW.seg_hasta),date(NEW.seg_fechad))) then 
	RAISE EXCEPTION  'LA FECHA DE VIGENCIA NO PUEDE SER MENOR O IGUAL A LA COMIENZO';
    END IF;

--    if(date_lt(date(OLD.seg_hasta),date('now()'))) then 
--	RAISE EXCEPTION  'DEBERA ANULAR ESTE CONTRATO Y CARGARLO NUEVAMENTE';
--    END IF;

    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_bu_seguros() OWNER TO estlm;

--
-- Name: f_bu_subitem(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_bu_subitem() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
	aux_texto 	text;
BEGIN

if int2lt(estadop(NEW.sitem_idoper),100::int2) THEN
    if numeric_ne(NEW.sitem_importe,OLD.sitem_importe) then
	NEW.sitem_imp_dolar:=moncteopera(NEW.sitem_idoper) * NEW.sitem_importe;
    end if;
end if;

if int2gt(estadop(NEW.sitem_idoper),100::int2) THEN
    if numeric_ne(NEW.sitem_importe,OLD.sitem_importe) then
	NEW.sitem_imp_dolar:=moncteopera(NEW.sitem_idoper) * NEW.sitem_importe;
	if (numeric_ne(fobpadre_vs_fobhijos(NEW.sitem_idoper,1::int2),0)) THEN 
	    update operaciones set op_importe=fob_hijos1(NEW.sitem_idoper,1::int2) where op_id=NEW.sitem_idoper;
	    update operaciones set op_impdolar=fob_hijos1(NEW.sitem_idoper,2::int2) where op_id=NEW.sitem_idoper;
	    aux_texto:='El usuario autorizado ha modificado el importe del subitem '||NEW.sitem_id ||' de la operacion publicada '||NEW.sitem_idoper||' que tenia un importe de '||OLD.sitem_importe||' por un importe de '||NEW.sitem_importe||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(41,NEW.sitem_idoper,aux_texto);
        end if;
    end if;

    if (int2ne(NEW.sitem_codigo,OLD.sitem_codigo)) then
	    aux_texto:='El usuario autorizado ha modificado el numero de  subitem '||NEW.sitem_id ||' de la operacion publicada '||NEW.sitem_idoper||' que tenia un codigo '||OLD.sitem_codigo||' por el codigo '||NEW.sitem_codigo||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(42,NEW.sitem_idoper,aux_texto);
        end if;

    if (int4ne(NEW.sitem_artic,OLD.sitem_artic)) then
	    aux_texto:='El usuario autorizado ha modificado el numero de  subitem '||NEW.sitem_id ||' de la operacion publicada '||NEW.sitem_idoper||' que tenia el articulo '||OLD.sitem_artic||' por el articulo '||NEW.sitem_artic||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(43,NEW.sitem_idoper,aux_texto);
        end if;

    if (numeric_ne(NEW.sitem_canting,OLD.sitem_canting)) then
	    aux_texto:='El usuario autorizado ha modificado el numero de  subitem '||NEW.sitem_id ||' de la operacion publicada '||NEW.sitem_idoper||' que tenia la cantidad '||OLD.sitem_canting||' por la cantidad '||NEW.sitem_canting||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(44,NEW.sitem_idoper,aux_texto);
        end if;

    if (int2ne(NEW.sitem_deposito,OLD.sitem_deposito)) then
	    aux_texto:='El usuario autorizado ha modificado el numero de  subitem '||NEW.sitem_id ||' de la operacion publicada '||NEW.sitem_idoper||' que estaba en el deposito '||OLD.sitem_deposito||' por el deposito '||NEW.sitem_deposito||' el dia de hoy';
	    insert into noticias(not_tipo,not_numero,not_texto)values(45,NEW.sitem_idoper,aux_texto);
        end if;
end if;
RETURN NEW;
END;$$;


ALTER FUNCTION public.f_bu_subitem() OWNER TO estlm;

--
-- Name: f_bu_volegr(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_bu_volegr() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
aux_texto 	text;
mal		int2;
salidas		int4;
trans 		boolean;
notid		int4;
BEGIN


if(int2eq(NEW.vole_estado,999::int2)) THEN 
    select fac_id into salidas 
	    from facturacion where fac_idoper=NEW.vole_idoper and fac_estado=50 limit 1;
	if found then
	    RAISE EXCEPTION  'NO SE PUEDE ANULAR ESTA OPERACION POR EXISTIR CONCEPTOS YA FACTURADOS AL CLIENTE';
	END IF;
END IF;

RETURN NEW;
END;$$;


ALTER FUNCTION public.f_bu_volegr() OWNER TO estlm;

--
-- Name: f_bu_voling(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION f_bu_voling() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
aux_texto 	text;
mal		int2;
salidas		int4;
trans 		boolean;
notid		int4;
BEGIN


if(int2eq(NEW.vol_estado,999::int2)) THEN 
    select fac_id into salidas 
	    from facturacion where fac_idoper=NEW.vol_idoper and fac_estado=50 limit 1;
	if found then
	    RAISE EXCEPTION  'NO SE PUEDE ANULAR ESTA OPERACION POR EXISTIR CONCEPTOS YA FACTURADOS AL CLIENTE';
	END IF;
END IF;

RETURN NEW;
END;$$;


ALTER FUNCTION public.f_bu_voling() OWNER TO estlm;

--
-- Name: factu_alm(integer, smallint, smallint, date, date, integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION factu_alm(integer, smallint, smallint, date, date, integer, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	cliente		ALIAS FOR $1; 
	anio		ALIAS FOR $2; 
	mes		ALIAS FOR $3; 
	fecfac		ALIAS FOR $4; 
	fechah		ALIAS FOR $5; 
	opera		ALIAS FOR $6; 
	codemp		ALIAS FOR $7; 
	registro	record;
	regi		record;
	regist		record;
	mal		int2;
	pase		int4;
	aux_texto 	text;
	aux_texto2 	text;
	articulo	integer;
	artsegur	integer;
	sigo		integer;
	retval 		integer;
	valstoc		numeric;
	impreti		numeric;
	retire		numeric;
	retireus	numeric;
	impaseg		numeric;
	volumen		numeric;
	precio		numeric;
	cotiz		numeric;
	precios		numeric;
	importe		numeric;
    BEGIN
    retval:=0;
    impaseg:=0;

    select valvaramb(codemp,0,'ARTALM') into articulo;   
    select valvaramb(codemp,0,'ARTSEG') into artsegur;   
    select ult_cotiz(1) into cotiz;


    if(int4ne(cliente,0) and int4eq(opera,0)) then
	for registro in select * from voling where vol_directo=codemp and vol_cliente=cliente and vol_estado=101 and vol_ultfac<fechah 
	loop
	    impaseg:=0;
	    impreti:=0;
	    retireus:=0;
	    pase:=1;
	    volumen:=registro.vol_canting;
	    impaseg:=fob_a_fecha_oper(registro.vol_idoper,registro.vol_ultfac) * cotiz;
	    select sum(vole_cantret) into retire from volegr where vole_idoperi=registro.vol_idoper and vole_fechaeg<=registro.vol_ultfac and registro.vol_cantret!=0 and vole_estado!=999 ;
	    if (retire is null) then retire:=0; end if;
	    volumen:=volumen - retire;
	    if numeric_ne(retire,0) then
		select sum((s.sitem_imp_dolar/s.sitem_canting) * r.ret_cantidad * cotiz) into retireus from subitem s, retiros r, volegr v where v.vole_idoperi=registro.vol_idoper and v.vole_fechaeg<=registro.vol_ultfac and registro.vol_cantret!=0 and v.vole_estado!=999 and r.ret_idsitem=s.sitem_id and r.ret_idopera=v.vole_idoper and s.sitem_idoper=v.vole_idoperi;
		if (retireus is null) then retireus:=0; end if;
		impaseg:=impaseg - retireus;
	    end if;
	    select elprecioid(codemp,registro.vol_cliente,articulo) into precio;
	    precios:=(calculo_funcion(-1,artsegur,registro.vol_idoper,1)) / 360;
	    for regi in select * from volegr where vole_idoperi=registro.vol_idoper and vole_fechaeg>registro.vol_ultfac and vole_fechaeg<=fecfac and vole_estado=101
		loop
		    volumen:=volumen - regi.vole_cantret;
		    aux_texto:='Almacenaje Operacion  '||compbteoper(regi.vole_idoperi)||' retirada con comprobante  '||compbteoper(regi.vole_idoper)||' (  '||registro.vol_ultfac + 1 ||' - '||regi.vole_fechaeg ||' )';
		    insert into facturacion (fac_fecdes,fac_fechas,fac_codemp,fac_cliente,fac_fecha,fac_anio,fac_mes,fac_idoper,fac_leyen,fac_ptov,fac_idart,fac_canti,fac_dias,fac_precio,fac_importe) values (registro.vol_ultfac,regi.vole_fechaeg,regi.vole_directo,registro.vol_cliente,fecfac,anio,mes,regi.vole_idoperi,aux_texto,ptovdefault(registro.vol_directo),articulo,regi.vole_cantret,(regi.vole_fechaeg - registro.vol_ultfac),precio,((regi.vole_fechaeg - registro.vol_ultfac) * regi.vole_cantret * precio));
		    select sum((s.sitem_imp_dolar/s.sitem_canting)*r.ret_cantidad * cotiz) into impreti from subitem s, retiros r  where r.ret_idsitem=s.sitem_id and r.ret_idopera=regi.vole_idoper and s.sitem_idoper=regi.vole_idoperi;
		    impaseg:=impaseg - impreti;
		    aux_texto:='Seguro Operacion  '||compbteoper(regi.vole_idoperi)||' retirada con comprobante  '||compbteoper(regi.vole_idoper)||' (  '||registro.vol_ultfac + 1 ||' - '||regi.vole_fechaeg ||' )';
		    insert into facturacion (fac_fecdes,fac_fechas,fac_codemp,fac_cliente,fac_fecha,fac_anio,fac_mes,fac_idoper,fac_leyen,fac_ptov,fac_idart,fac_canti,fac_dias,fac_precio,fac_importe) values (registro.vol_ultfac,regi.vole_fechaeg,regi.vole_directo,registro.vol_cliente,fecfac,anio,mes,regi.vole_idoperi,aux_texto,ptovdefault(registro.vol_directo),artsegur,impreti ,(regi.vole_fechaeg - registro.vol_ultfac),precios,((regi.vole_fechaeg - registro.vol_ultfac) * impreti * precios));
		end loop;
	    if numeric_gt(volumen,0) then
		aux_texto:='Almacenaje Operacion  '||compbteoper(registro.vol_idoper)||' Periodo:  '||registro.vol_ultfac + 1 ||' - '||fechah ;
		insert into facturacion (fac_fecdes,fac_fechas,fac_codemp,fac_cliente,fac_fecha,fac_anio,fac_mes,fac_idoper,fac_leyen,fac_ptov,fac_idart,fac_canti,fac_dias,fac_precio,fac_importe) values (registro.vol_ultfac,fechah,codemp,registro.vol_cliente,fecfac,anio,mes,registro.vol_idoper,aux_texto,ptovdefault(registro.vol_directo),articulo,volumen,(fechah - registro.vol_ultfac),precio,((fechah - registro.vol_ultfac) * volumen * precio));
		aux_texto:='Seguro Operacion  '||compbteoper(registro.vol_idoper)||' (  '||registro.vol_ultfac + 1 ||' - '|| fechah ||' )';
		insert into facturacion (fac_fecdes,fac_fechas,fac_codemp,fac_cliente,fac_fecha,fac_anio,fac_mes,fac_idoper,fac_leyen,fac_ptov,fac_idart,fac_canti,fac_dias,fac_precio,fac_importe) values (registro.vol_ultfac,fechah,codemp,registro.vol_cliente,fecfac,anio,mes,registro.vol_idoper,aux_texto,ptovdefault(registro.vol_directo),artsegur,impaseg ,(fechah - registro.vol_ultfac),precios,((fechah - registro.vol_ultfac) * impaseg * precios));
	    end if;
	    for regist in select * from complfac where cfac_codemp=codemp and cfac_estado=1 and cfac_evento=3 
		loop
		    select fac_estado into mal from facturacion where fac_codemp=codemp and fac_cliente=registro.vol_cliente and fac_idoper=registro.vol_idoper and fac_ptov=regist.cfac_ptov and fac_idart=regist.cfac_idart and fac_estado!=1 and fac_anio=anio and fac_mes=mes limit 1;
		    if not found then
			delete from facturacion where fac_codemp=registro.vol_directo and fac_cliente=registro.vol_cliente and fac_idoper=registro.vol_idoper and fac_ptov=regist.cfac_ptov and fac_idart=regist.cfac_idart and fac_estado=1 and fac_anio=anio and fac_mes=mes;
			aux_texto2:=' ( Concepto:  '  || descartic(regist.cfac_idart) || '  -  Operacion:  ' || traigo_simbtipoper(tipoperdeop(registro.vol_idoper)) || ' - ' || nrotaldiroper(registro.vol_idoper) || '   Comprobante:  ' || registro.vol_compbte || ' ) ';
			if(int4eq(regist.cfac_cliente,registro.vol_cliente) or  regist.cfac_cliente is null) then
			    precio:=calculo_funcion(regist.cfac_id,regist.cfac_idart,registro.vol_idoper,1);
			    importe:= precio * regist.cfac_dias * regist.cfac_canti ;
			end if;
			if numeric_gt(importe,0) then 
			    insert into facturacion (fac_codemp,fac_cliente,fac_fecha,fac_anio,fac_mes,fac_idoper,fac_leyen,fac_ptov,fac_idart,fac_canti,fac_dias,fac_precio,fac_importe) values (registro.vol_directo,registro.vol_cliente,registro.vol_fechain,anio,mes,registro.vol_idoper,aux_texto2,regist.cfac_ptov,regist.cfac_idart,regist.cfac_canti * impaseg,regist.cfac_dias,precio,importe);
			end if;
		    end if;
		end loop; 
	end loop;
	update voling set vol_ultfac=fechah where vol_directo=codemp and vol_cliente=cliente and vol_estado=101 and vol_ultfac<fechah;
    end if;


    if(int4eq(cliente,0) and  int4eq(opera,0)) then
	for registro in select * from voling where vol_directo=codemp and vol_estado=101 and climodfac(vol_cliente)=1 and vol_ultfac<fechah
	loop
	    impaseg:=0;
	    impreti:=0;
	    retireus:=0;
	    pase:=1;
	    volumen:=registro.vol_canting;
	    impaseg:=fob_a_fecha_oper(registro.vol_idoper,registro.vol_ultfac) * cotiz;
	    select sum(vole_cantret) into retire from volegr where vole_idoperi=registro.vol_idoper and vole_fechaeg<=registro.vol_ultfac and registro.vol_cantret!=0 and vole_estado!=999 ;
	    if (retire is null) then retire:=0; end if;
	    volumen:=volumen - retire;
	    if numeric_ne(retire,0) then
		select sum((s.sitem_imp_dolar/s.sitem_canting) * r.ret_cantidad * cotiz) into retireus from subitem s, retiros r, volegr v where v.vole_idoperi=registro.vol_idoper and v.vole_fechaeg<=registro.vol_ultfac and registro.vol_cantret!=0 and v.vole_estado!=999 and r.ret_idsitem=s.sitem_id and r.ret_idopera=v.vole_idoper and s.sitem_idoper=v.vole_idoperi;
		if (retireus is null) then retireus:=0; end if;
		impaseg:=impaseg - retireus;
	    end if;
	    select elprecioid(codemp,registro.vol_cliente,articulo) into precio;
	    precios:=(calculo_funcion(-1,artsegur,registro.vol_idoper,1)) / 360;
	    for regi in select * from volegr where vole_idoperi=registro.vol_idoper and vole_fechaeg>registro.vol_ultfac and vole_fechaeg<=fecfac and vole_estado=101
		loop
		    volumen:=volumen - regi.vole_cantret;
		    aux_texto:='Almacenaje Operacion  '||compbteoper(regi.vole_idoperi)||' retirada con comprobante  '||compbteoper(regi.vole_idoper)||' (  '||registro.vol_ultfac + 1 ||' - '||regi.vole_fechaeg ||' )';
		    insert into facturacion (fac_fecdes,fac_fechas,fac_codemp,fac_cliente,fac_fecha,fac_anio,fac_mes,fac_idoper,fac_leyen,fac_ptov,fac_idart,fac_canti,fac_dias,fac_precio,fac_importe) values (registro.vol_ultfac,regi.vole_fechaeg,regi.vole_directo,registro.vol_cliente,fecfac,anio,mes,regi.vole_idoperi,aux_texto,ptovdefault(registro.vol_directo),articulo,regi.vole_cantret,(regi.vole_fechaeg - registro.vol_ultfac),precio,((regi.vole_fechaeg - registro.vol_ultfac) * regi.vole_cantret * precio));
		    select sum((s.sitem_imp_dolar/s.sitem_canting)*r.ret_cantidad * cotiz) into impreti from subitem s, retiros r  where r.ret_idsitem=s.sitem_id and r.ret_idopera=regi.vole_idoper and s.sitem_idoper=regi.vole_idoperi;
		    impaseg:=impaseg - impreti;
		    aux_texto:='Seguro Operacion  '||compbteoper(regi.vole_idoperi)||' retirada con comprobante  '||compbteoper(regi.vole_idoper)||' (  '||registro.vol_ultfac + 1 ||' - '||regi.vole_fechaeg ||' )';
		    insert into facturacion (fac_fecdes,fac_fechas,fac_codemp,fac_cliente,fac_fecha,fac_anio,fac_mes,fac_idoper,fac_leyen,fac_ptov,fac_idart,fac_canti,fac_dias,fac_precio,fac_importe) values (registro.vol_ultfac,regi.vole_fechaeg,regi.vole_directo,registro.vol_cliente,fecfac,anio,mes,regi.vole_idoperi,aux_texto,ptovdefault(registro.vol_directo),artsegur,impreti ,(regi.vole_fechaeg - registro.vol_ultfac),precios,((regi.vole_fechaeg - registro.vol_ultfac) * impreti * precios));
		end loop;
	    if numeric_gt(volumen,0) then
		aux_texto:='Almacenaje Operacion  '||compbteoper(registro.vol_idoper)||' Periodo:  '||registro.vol_ultfac + 1 ||' - '||fechah ;
		insert into facturacion (fac_fecdes,fac_fechas,fac_codemp,fac_cliente,fac_fecha,fac_anio,fac_mes,fac_idoper,fac_leyen,fac_ptov,fac_idart,fac_canti,fac_dias,fac_precio,fac_importe) values (registro.vol_ultfac,fechah,codemp,registro.vol_cliente,fecfac,anio,mes,registro.vol_idoper,aux_texto,ptovdefault(registro.vol_directo),articulo,volumen,(fechah - registro.vol_ultfac),precio,((fechah - registro.vol_ultfac) * volumen * precio));
		aux_texto:='Seguro Operacion  '||compbteoper(registro.vol_idoper)||' (  '||registro.vol_ultfac + 1 ||' - '|| fechah ||' )';
		insert into facturacion (fac_fecdes,fac_fechas,fac_codemp,fac_cliente,fac_fecha,fac_anio,fac_mes,fac_idoper,fac_leyen,fac_ptov,fac_idart,fac_canti,fac_dias,fac_precio,fac_importe) values (registro.vol_ultfac,fechah,codemp,registro.vol_cliente,fecfac,anio,mes,registro.vol_idoper,aux_texto,ptovdefault(registro.vol_directo),artsegur,impaseg ,(fechah - registro.vol_ultfac),precios,((fechah - registro.vol_ultfac) * impaseg * precios));
	    end if;
	    for regist in select * from complfac where cfac_codemp=codemp and cfac_estado=1 and cfac_evento=3 
		loop
		    select fac_estado into mal from facturacion where fac_codemp=codemp and fac_cliente=registro.vol_cliente and fac_idoper=registro.vol_idoper and fac_ptov=regist.cfac_ptov and fac_idart=regist.cfac_idart and fac_estado!=1 and fac_anio=anio and fac_mes=mes limit 1;
		    if not found then
			delete from facturacion where fac_codemp=registro.vol_directo and fac_cliente=registro.vol_cliente and fac_idoper=registro.vol_idoper and fac_ptov=regist.cfac_ptov and fac_idart=regist.cfac_idart and fac_estado=1 and fac_anio=anio and fac_mes=mes;
			aux_texto2:=' ( Concepto:  '  || descartic(regist.cfac_idart) || '  -  Operacion:  ' || traigo_simbtipoper(tipoperdeop(registro.vol_idoper)) || ' - ' || nrotaldiroper(registro.vol_idoper) || '   Comprobante:  ' || registro.vol_compbte || ' ) ';
			if(int4eq(regist.cfac_cliente,registro.vol_cliente) or  regist.cfac_cliente is null) then
			    precio:=calculo_funcion(regist.cfac_id,regist.cfac_idart,registro.vol_idoper,1);
			    importe:= precio * regist.cfac_dias * regist.cfac_canti ;
			end if;
			if numeric_gt(importe,0) then 
			    insert into facturacion (fac_codemp,fac_cliente,fac_fecha,fac_anio,fac_mes,fac_idoper,fac_leyen,fac_ptov,fac_idart,fac_canti,fac_dias,fac_precio,fac_importe) values (registro.vol_directo,registro.vol_cliente,registro.vol_fechain,anio,mes,registro.vol_idoper,aux_texto2,regist.cfac_ptov,regist.cfac_idart,regist.cfac_canti * impaseg,regist.cfac_dias,precio,importe);
			end if;
		    end if;
		end loop; 
	end loop;
	update voling set vol_ultfac=fechah where vol_directo=codemp and vol_estado=101 and climodfac(vol_cliente)=1 and vol_ultfac<fechah;
    end if;


    if(int4ne(opera,0)) then
	for registro in select * from voling where vol_directo=codemp and vol_idoper=opera and vol_estado=101 and vol_ultfac<fechah 
	loop
	    impaseg:=0;
	    impreti:=0;
	    retireus:=0;
	    pase:=1;
	    volumen:=registro.vol_canting;
	    impaseg:=fob_a_fecha_oper(registro.vol_idoper,registro.vol_ultfac) * cotiz;
	    select sum(vole_cantret) into retire from volegr where vole_idoperi=registro.vol_idoper and vole_fechaeg<=registro.vol_ultfac and registro.vol_cantret!=0 and vole_estado!=999 ;
	    if (retire is null) then retire:=0; end if;
	    volumen:=volumen - retire;
	    if numeric_ne(retire,0) then
		select sum((s.sitem_imp_dolar/s.sitem_canting) * r.ret_cantidad * cotiz) into retireus from subitem s, retiros r, volegr v where v.vole_idoperi=registro.vol_idoper and v.vole_fechaeg<=registro.vol_ultfac and registro.vol_cantret!=0 and v.vole_estado!=999 and r.ret_idsitem=s.sitem_id and r.ret_idopera=v.vole_idoper and s.sitem_idoper=v.vole_idoperi;
		if (retireus is null) then retireus:=0; end if;
		impaseg:=impaseg - retireus;
	    end if;
	    select elprecioid(codemp,registro.vol_cliente,articulo) into precio;
	    precios:=(calculo_funcion(-1,artsegur,registro.vol_idoper,1)) / 360;
	    for regi in select * from volegr where vole_idoperi=registro.vol_idoper and vole_fechaeg>registro.vol_ultfac and vole_fechaeg<=fecfac and vole_estado=101
		loop
		    volumen:=volumen - regi.vole_cantret;
		    aux_texto:='Almacenaje Operacion  '||compbteoper(regi.vole_idoperi)||' retirada con comprobante  '||compbteoper(regi.vole_idoper)||' (  '||registro.vol_ultfac + 1 ||' - '||regi.vole_fechaeg ||' )';
		    insert into facturacion (fac_fecdes,fac_fechas,fac_codemp,fac_cliente,fac_fecha,fac_anio,fac_mes,fac_idoper,fac_leyen,fac_ptov,fac_idart,fac_canti,fac_dias,fac_precio,fac_importe) values (registro.vol_ultfac,regi.vole_fechaeg,regi.vole_directo,registro.vol_cliente,fecfac,anio,mes,regi.vole_idoperi,aux_texto,ptovdefault(registro.vol_directo),articulo,regi.vole_cantret,(regi.vole_fechaeg - registro.vol_ultfac),precio,((regi.vole_fechaeg - registro.vol_ultfac) * regi.vole_cantret * precio));
		    select sum((s.sitem_imp_dolar/s.sitem_canting)*r.ret_cantidad * cotiz) into impreti from subitem s, retiros r  where r.ret_idsitem=s.sitem_id and r.ret_idopera=regi.vole_idoper and s.sitem_idoper=regi.vole_idoperi;
		    impaseg:=impaseg - impreti;
		    aux_texto:='Seguro Operacion  '||compbteoper(regi.vole_idoperi)||' retirada con comprobante  '||compbteoper(regi.vole_idoper)||' (  '||registro.vol_ultfac + 1 ||' - '||regi.vole_fechaeg ||' )';
		    insert into facturacion (fac_fecdes,fac_fechas,fac_codemp,fac_cliente,fac_fecha,fac_anio,fac_mes,fac_idoper,fac_leyen,fac_ptov,fac_idart,fac_canti,fac_dias,fac_precio,fac_importe) values (registro.vol_ultfac,regi.vole_fechaeg,regi.vole_directo,registro.vol_cliente,fecfac,anio,mes,regi.vole_idoperi,aux_texto,ptovdefault(registro.vol_directo),artsegur,impreti ,(regi.vole_fechaeg - registro.vol_ultfac),precios,((regi.vole_fechaeg - registro.vol_ultfac) * impreti * precios));
		end loop;
	    if numeric_gt(volumen,0) then
		aux_texto:='Almacenaje Operacion  '||compbteoper(registro.vol_idoper)||' Periodo:  '||registro.vol_ultfac + 1 ||' - '||fechah ;
		insert into facturacion (fac_fecdes,fac_fechas,fac_codemp,fac_cliente,fac_fecha,fac_anio,fac_mes,fac_idoper,fac_leyen,fac_ptov,fac_idart,fac_canti,fac_dias,fac_precio,fac_importe) values (registro.vol_ultfac,fechah,codemp,registro.vol_cliente,fecfac,anio,mes,registro.vol_idoper,aux_texto,ptovdefault(registro.vol_directo),articulo,volumen,(fechah - registro.vol_ultfac),precio,((fechah - registro.vol_ultfac) * volumen * precio));
		aux_texto:='Seguro Operacion  '||compbteoper(registro.vol_idoper)||' (  '||registro.vol_ultfac + 1 ||' - '|| fechah ||' )';
		insert into facturacion (fac_fecdes,fac_fechas,fac_codemp,fac_cliente,fac_fecha,fac_anio,fac_mes,fac_idoper,fac_leyen,fac_ptov,fac_idart,fac_canti,fac_dias,fac_precio,fac_importe) values (registro.vol_ultfac,fechah,codemp,registro.vol_cliente,fecfac,anio,mes,registro.vol_idoper,aux_texto,ptovdefault(registro.vol_directo),artsegur,impaseg ,(fechah - registro.vol_ultfac),precios,((fechah - registro.vol_ultfac) * impaseg * precios));
	    end if;
	    for regist in select * from complfac where cfac_codemp=codemp and cfac_estado=1 and cfac_evento=3 
		loop
		    select fac_estado into mal from facturacion where fac_codemp=codemp and fac_cliente=registro.vol_cliente and fac_idoper=registro.vol_idoper and fac_ptov=regist.cfac_ptov and fac_idart=regist.cfac_idart and fac_estado!=1 and fac_anio=anio and fac_mes=mes limit 1;
		    if not found then
			delete from facturacion where fac_codemp=registro.vol_directo and fac_cliente=registro.vol_cliente and fac_idoper=registro.vol_idoper and fac_ptov=regist.cfac_ptov and fac_idart=regist.cfac_idart and fac_estado=1 and fac_anio=anio and fac_mes=mes;
			aux_texto2:=' ( Concepto:  '  || descartic(regist.cfac_idart) || '  -  Operacion:  ' || traigo_simbtipoper(tipoperdeop(registro.vol_idoper)) || ' - ' || nrotaldiroper(registro.vol_idoper) || '   Comprobante:  ' || registro.vol_compbte || ' ) ';
			if(int4eq(regist.cfac_cliente,registro.vol_cliente) or  regist.cfac_cliente is null) then
			    precio:=calculo_funcion(regist.cfac_id,regist.cfac_idart,registro.vol_idoper,1);
			    importe:= precio * regist.cfac_dias * regist.cfac_canti ;
			end if;
			if numeric_gt(importe,0) then 
			    insert into facturacion (fac_codemp,fac_cliente,fac_fecha,fac_anio,fac_mes,fac_idoper,fac_leyen,fac_ptov,fac_idart,fac_canti,fac_dias,fac_precio,fac_importe) values (registro.vol_directo,registro.vol_cliente,registro.vol_fechain,anio,mes,registro.vol_idoper,aux_texto2,regist.cfac_ptov,regist.cfac_idart,regist.cfac_canti * impaseg,regist.cfac_dias,precio,importe);
			end if;
		    end if;
		end loop; 
	end loop;
	update voling set vol_ultfac=fechah where vol_directo=codemp and vol_idoper=opera and vol_estado=101 and vol_ultfac<fechah;
    end if;


RETURN retval;
END;$_$;


ALTER FUNCTION public.factu_alm(integer, smallint, smallint, date, date, integer, integer) OWNER TO estlm;

--
-- Name: facturo(integer, integer, smallint, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION facturo(integer, integer, smallint, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	codemp		ALIAS FOR $1; 
	cliente		ALIAS FOR $2; 
	estado		ALIAS FOR $3; 
	operador	ALIAS FOR $4; 
	ivaemp 		smallint;
	ivacli 		smallint;
	registro	record;
	regi		record;
	aux_texto 	text;
	idcompro	integer;
	idmovsto	integer;
	idastoh		integer;
	idemiti		integer;
	lineas		integer;
	yvan		integer;
	primera		integer;
	numero		integer;
	ptonew		integer;
	ptoold		integer;
	clinew		integer;
	cliold		integer;
	yapase		integer;
	eliva		numeric;
	elivast		numeric;
	retval 		integer;
    BEGIN
    retval:=0;
    primera:=0;
    ptoold:=0;
    ptonew:=0;
    yapase:=0;
    yvan:=0;


    select valvaramb(codemp,ptovdefault(codemp),'LINFAC') into lineas;
    select emp_coniva into ivaemp from empresa where emp_codigo=codemp;

    if(int4eq(cliente,0)) then
	for registro in select * from facturacion where fac_codemp=codemp and fac_estado=estado 
	loop
	    ptonew:=registro.fac_ptov;
	    clinew:=registro.fac_cliente;

	    if(int4eq(primera,0) or int4ne(ptonew,ptoold) or int4ne(clinew,cliold)) then
		ptoold:=registro.fac_ptov;
		cliold:=registro.fac_cliente;
		select cli_coniva into ivacli from clientes where cli_id=registro.fac_cliente;
		if(int2eq(ivaemp,1::int2)) then
		    if(int2eq(ivacli,1::int2)) then
			select idcomp('FA',ptonew) into idcompro;
		      else		
			select idcomp('FB',ptonew) into idcompro;
		    end if;
	          else
		    select idcomp('FC',ptonew) into idcompro;
		end if;


		select numtalon(ptonew,idcompro,1) into numero;
		select nomcomp(idcompro) into aux_texto;
		insert into astoh (ash_estado,ash_codemp,ash_idptov,ash_anio,ash_mes,ash_fecomp,ash_fecval,ash_operad,ash_comprob,ash_numero,ash_titulo) values (-2,registro.fac_codemp,registro.fac_ptov,registro.fac_anio,registro.fac_mes,registro.fac_fecha,registro.fac_fecfac,operador,idcompro,numero,aux_texto);
		select max(ash_id) into idastoh from astoh;
		insert into emiti (emi_idastoh,emi_codemp,emi_idptov,emi_comprob,emi_numero,emi_fecval,emi_codcli,emi_nomcli,emi_nrocuit,emi_provin,emi_grupo,emi_succli,emi_conivac,emi_conpag,emi_estado) values (idastoh,registro.fac_codemp,registro.fac_ptov,idcompro,numero,registro.fac_fecfac,registro.fac_cliente,nomcli(registro.fac_cliente),cuitcli(registro.fac_cliente),provinclie(registro.fac_cliente,registro.fac_ptov),grupocli(registro.fac_cliente,1),registro.fac_ptov,ivacli,conpagcli(registro.fac_cliente),-2);
		select max(emi_id) into idemiti from emiti;
		update astoh set ash_idemiti=idemiti where ash_id=idastoh;
		insert into movsto (movs_idastoh,movs_idemiti,movs_codemp,movs_idptov,movs_fecval,movs_artic,movs_canti,movs_dias,movs_precio,movs_importe,movs_tasa,movs_estado,movs_codcli,movs_clireal,movs_idoper,movs_leyen) values (idastoh,idemiti,registro.fac_codemp,registro.fac_ptov,registro.fac_fecha,registro.fac_idart,registro.fac_canti,registro.fac_dias,registro.fac_precio,registro.fac_importe,tasaartic(registro.fac_idart),-2,registro.fac_cliente,registro.fac_clireal,registro.fac_idoper,registro.fac_leyen);
		primera:=1;
		yvan:=1;

	      else

		select movs_id into idmovsto from movsto where movs_idastoh=idastoh and movs_idemiti=idemiti and movs_artic=registro.fac_idart and movs_precio=registro.fac_precio;
		if not found then
		    insert into movsto (movs_idastoh,movs_idemiti,movs_codemp,movs_idptov,movs_fecval,movs_artic,movs_canti,movs_dias,movs_precio,movs_importe,movs_tasa,movs_estado,movs_codcli,movs_clireal,movs_idoper,movs_leyen) values (idastoh,idemiti,registro.fac_codemp,registro.fac_ptov,registro.fac_fecfac,registro.fac_idart,registro.fac_canti,registro.fac_dias,registro.fac_precio,registro.fac_importe,tasaartic(registro.fac_idart),-2,registro.fac_cliente,registro.fac_clireal,registro.fac_idoper,registro.fac_leyen);
		    yvan:=yvan + 1; 
		    if int4eq(yvan,lineas)then
		      primera:=0;
		      yvan:=0; 
		    end if;
		  else
		    update movsto set movs_canti=movs_canti+registro.fac_canti,movs_importe=movs_importe+registro.fac_importe,movs_dias=movs_dias+registro.fac_dias where movs_id=idmovsto;
		    update movsto set movs_dias=movs_importe/movs_canti/movs_precio where movs_id=idmovsto;
		end if;

	    end if;
	end loop;
    update facturacion set fac_estado=2 where fac_codemp=codemp and fac_estado=estado;
    end if;


    if(int4ne(cliente,0)) then
	for registro in select * from facturacion where fac_codemp=codemp and fac_cliente=cliente and fac_estado=estado
	loop
	    ptonew:=registro.fac_ptov;
	    if(int4eq(primera,0) or int4ne(ptonew,ptoold)) then
		ptoold:=registro.fac_ptov;
		select cli_coniva into ivacli from clientes where cli_id=cliente;
		if(int2eq(ivaemp,1::int2)) then
		    if(int2eq(ivacli,1::int2)) then
			select idcomp('FA',ptonew) into idcompro;
		      else		
			select idcomp('FB',ptonew) into idcompro;
		    end if;
	          else
		    select idcomp('FC',ptonew) into idcompro;
		end if;
		select numtalon(ptonew,idcompro,1) into numero;
		select nomcomp(idcompro) into aux_texto;
		insert into astoh (ash_estado,ash_codemp,ash_idptov,ash_anio,ash_mes,ash_fecomp,ash_fecval,ash_operad,ash_comprob,ash_numero,ash_titulo) values (-2,registro.fac_codemp,registro.fac_ptov,registro.fac_anio,registro.fac_mes,registro.fac_fecha,registro.fac_fecfac,operador,idcompro,numero,aux_texto);
		select max(ash_id) into idastoh from astoh;
		insert into emiti (emi_idastoh,emi_codemp,emi_idptov,emi_comprob,emi_numero,emi_fecval,emi_codcli,emi_nomcli,emi_nrocuit,emi_provin,emi_grupo,emi_succli,emi_conivac,emi_conpag,emi_estado) values (idastoh,registro.fac_codemp,registro.fac_ptov,idcompro,numero,registro.fac_fecfac,registro.fac_cliente,nomcli(registro.fac_cliente),cuitcli(registro.fac_cliente),provinclie(registro.fac_cliente,registro.fac_ptov),grupocli(registro.fac_cliente,1),registro.fac_ptov,ivacli,conpagcli(registro.fac_cliente),-2);
		select max(emi_id) into idemiti from emiti;
		update astoh set ash_idemiti=idemiti where ash_id=idastoh;
		insert into movsto (movs_idastoh,movs_idemiti,movs_codemp,movs_idptov,movs_fecval,movs_artic,movs_canti,movs_dias,movs_precio,movs_importe,movs_tasa,movs_estado,movs_codcli,movs_clireal,movs_idoper,movs_leyen) values (idastoh,idemiti,registro.fac_codemp,registro.fac_ptov,registro.fac_fecha,registro.fac_idart,registro.fac_canti,registro.fac_dias,registro.fac_precio,registro.fac_importe,tasaartic(registro.fac_idart),-2,registro.fac_cliente,registro.fac_clireal,registro.fac_idoper,registro.fac_leyen);
		primera:=1;
		yvan:=1;

	      else

		select movs_id into idmovsto from movsto where movs_idastoh=idastoh and movs_idemiti=idemiti and movs_artic=registro.fac_idart and movs_precio=registro.fac_precio;
		if not found then
		    insert into movsto (movs_idastoh,movs_idemiti,movs_codemp,movs_idptov,movs_fecval,movs_artic,movs_canti,movs_dias,movs_precio,movs_importe,movs_tasa,movs_estado,movs_codcli,movs_clireal,movs_idoper,movs_leyen) values (idastoh,idemiti,registro.fac_codemp,registro.fac_ptov,registro.fac_fecfac,registro.fac_idart,registro.fac_canti,registro.fac_dias,registro.fac_precio,registro.fac_importe,tasaartic(registro.fac_idart),-2,registro.fac_cliente,registro.fac_clireal,registro.fac_idoper,registro.fac_leyen);
		    yvan:=yvan + 1; 
		    if int4eq(yvan,lineas)then
		      primera:=0;
		      yvan:=0; 
		    end if;
		  else
		    update movsto set movs_canti=movs_canti+registro.fac_canti, movs_importe=movs_importe+registro.fac_importe, movs_dias=movs_dias+registro.fac_dias where movs_id=idmovsto;
		    update movsto set movs_dias=movs_importe/movs_canti/movs_precio where movs_id=idmovsto;
		end if;
	    end if;
	end loop;
    update facturacion set fac_estado=2 where fac_codemp=codemp and fac_cliente=cliente and fac_estado=estado;
    end if;


    eliva:=0;
    elivast:=0;
    for regi in select * from astoh where ash_estado=-2
	loop
	    select sum(movs_importe * movs_tasa / 100) into eliva from movsto where movs_idastoh=regi.ash_id;
	    select graboastocta(regi.ash_id,eliva,elivast,0::numeric) into yapase;
	end loop;
    update astoh set ash_estado=-1 where ash_estado=-2;

    retval:=yapase;

RETURN retval;
END;$_$;


ALTER FUNCTION public.facturo(integer, integer, smallint, integer) OWNER TO estlm;

--
-- Name: fecdechq(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION fecdechq(integer) RETURNS date
    LANGUAGE sql
    AS $_$select chq_fecheq from cheques where chq_id= $1 ;$_$;


ALTER FUNCTION public.fecdechq(integer) OWNER TO estlm;

--
-- Name: fecha_fe(date); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION fecha_fe(date) RETURNS character
    LANGUAGE sql
    AS $_$select date_part('Y',$1)::character varying||lpad(date_part('Month',$1)::text,2,'0'::text)::character varying||lpad(date_part('D',$1)::text,2,'0'::text)::character varying;$_$;


ALTER FUNCTION public.fecha_fe(date) OWNER TO zona;

--
-- Name: fecvalash(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION fecvalash(integer) RETURNS date
    LANGUAGE sql
    AS $_$select ash_fecval from astoh where ash_id= $1;$_$;


ALTER FUNCTION public.fecvalash(integer) OWNER TO estlm;

--
-- Name: fecvalastc(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION fecvalastc(integer) RETURNS date
    LANGUAGE sql
    AS $_$select astc_fecval from astoctas where astc_id= $1 ;$_$;


ALTER FUNCTION public.fecvalastc(integer) OWNER TO estlm;

--
-- Name: fob_a_fecha_compbte(character varying, date); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION fob_a_fecha_compbte(character varying, date) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
DECLARE
compbte		ALIAS FOR $1; 	-- Comprobante
fecha		ALIAS FOR $2;	-- fecha hasta
registro 	RECORD;
registror 	RECORD;
retirado	numeric;
cantret		numeric;
precio		numeric;
retval 		numeric;
BEGIN

retval:=0;

for registro in select op_id as x
    from operaciones where bpchareq(op_compbte,compbte::varchar) and op_estado=101 and int4lt(op_tipoper,100::int4) and date_le(op_fechain,fecha) 
	loop
	for registror in select *
	    from subitem where sitem_idoper=registro.x
		loop

		retval:=retval+registror.sitem_imp_dolar;

		if(registror.sitem_cantret is not null and registror.sitem_cantret!=0) then
		    if(registror.sitem_canting is not null and registror.sitem_canting!=0) then
			precio:=registror.sitem_imp_dolar/registror.sitem_canting;
		    end if;


		select sum(ret_cantidad) into cantret from
    		    retiros where registror.sitem_id=ret_idsitem and date_le(closeop(ret_idopera),fecha) and estadop(ret_idopera)=101;

		    if not found then 
			    retirado:=0;
			else
			    retirado:=cantret*precio;
		    end if;

		    if(retirado is not null and retirado!=0) then   retval:=retval-retirado; end if;

		end if;

		end loop; 

	end loop; 
retval:=retval::numeric(15,2);

RETURN retval;
END;$_$;


ALTER FUNCTION public.fob_a_fecha_compbte(character varying, date) OWNER TO estlm;

--
-- Name: fob_a_fecha_deposito(smallint, date); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION fob_a_fecha_deposito(smallint, date) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
DECLARE
deposito	ALIAS FOR $1; 	-- deposito
fecha		ALIAS FOR $2;	-- fecha hasta
registro 	RECORD;
retirado	numeric;
cantret		numeric;
precio		numeric;
retval 		numeric;
BEGIN

retval:=0;

for registro in select *
    from subitem, operaciones where sitem_deposito=deposito and sitem_idoper=op_id and op_estado=101 and int4lt(op_tipoper,100::int4) and date_le(op_fechain,fecha) 
	loop

	retval:=retval+registro.sitem_imp_dolar;

	if(registro.sitem_cantret is not null and registror.sitem_cantret!=0) then
	    if(registro.sitem_canting is not null and registror.sitem_canting!=0) then
		precio:=registro.sitem_imp_dolar/registro.sitem_canting;
	    end if;


	select sum(ret_cantidad) into cantret from
    	    retiros where registro.sitem_id=ret_idsitem and date_le(closeop(ret_idopera),fecha) and estadop(ret_idopera)=101;

	    if not found then 
		    retirado:=0;
		else
		    retirado:=cantret*precio;
	    end if;

	    if(retirado is not null and retirado!=0) then   retval:=retval-retirado; end if;

	end if;

	end loop; 
retval:=retval::numeric(15,2);

RETURN retval;
END;$_$;


ALTER FUNCTION public.fob_a_fecha_deposito(smallint, date) OWNER TO estlm;

--
-- Name: fob_a_fecha_directo(integer, date); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION fob_a_fecha_directo(integer, date) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
DECLARE
directo		ALIAS FOR $1; 	-- id del directo
fecha		ALIAS FOR $2;	-- fecha hasta
registro 	RECORD;
registror 	RECORD;
retirado	numeric;
cantret		numeric;
precio		numeric;
retval 		numeric;
BEGIN

retval:=0;

for registro in select op_id as x
    from operaciones where op_directo=directo and op_estado=101 and int4lt(op_tipoper,100::int4) and date_le(op_fechain,fecha) 
	loop
	for registror in select *
	    from subitem where sitem_idoper=registro.x
		loop

		retval:=retval+registror.sitem_imp_dolar;

		if(registror.sitem_cantret is not null and registror.sitem_cantret!=0) then
		    if(registror.sitem_canting is not null and registror.sitem_canting!=0) then
			precio:=registror.sitem_imp_dolar/registror.sitem_canting;
		    end if;


		select sum(ret_cantidad) into cantret from
    		    retiros where registror.sitem_id=ret_idsitem and date_le(closeop(ret_idopera),fecha) and estadop(ret_idopera)=101;

		    if not found then 
			    retirado:=0;
			else
			    retirado:=cantret*precio;
		    end if;

		    if(retirado is not null and retirado!=0) then   retval:=retval-retirado; end if;

		end if;

		end loop; 

	end loop; 
retval:=retval::numeric(15,2);

RETURN retval;
END;$_$;


ALTER FUNCTION public.fob_a_fecha_directo(integer, date) OWNER TO estlm;

--
-- Name: fob_a_fecha_directo2(integer, date); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION fob_a_fecha_directo2(integer, date) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
DECLARE
directo		ALIAS FOR $1; 	-- id del directo
fecha		ALIAS FOR $2;	-- fecha hasta
registro 	RECORD;
registror 	RECORD;
retirado	numeric;
cantret		numeric;
precio		numeric;
retval 		numeric;
BEGIN

retval:=0;

for registro in select op_id as x
    from operaciones where op_directo=directo and op_estado=101 and int4lt(op_tipoper,100::int4) and date_le(op_fechain,fecha) 
	loop
	for registror in select *
	    from subitem where sitem_estado=1 and sitem_idoper=registro.x 
		loop
		retval:=retval+((registror.sitem_imp_dolar / registror.sitem_canting)*(registror.sitem_canting - registror.sitem_cantret));
		end loop; 
	end loop; 

retval:=retval::numeric(15,2);

RETURN retval;
END;$_$;


ALTER FUNCTION public.fob_a_fecha_directo2(integer, date) OWNER TO estlm;

--
-- Name: fob_a_fecha_oper(integer, date); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION fob_a_fecha_oper(integer, date) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
DECLARE
compbte		ALIAS FOR $1; 	-- Comprobante
fecha		ALIAS FOR $2;	-- fecha hasta
registror 	RECORD;
retirado	numeric;
cantret		numeric;
precio		numeric;
retval 		numeric;
BEGIN

retval:=0;

	for registror in select *
	    from subitem where sitem_idoper=compbte
		loop

		retval:=retval+registror.sitem_imp_dolar;

		if(registror.sitem_cantret is not null and registror.sitem_cantret!=0) then
		    if(registror.sitem_canting is not null and registror.sitem_canting!=0) then
			precio:=registror.sitem_imp_dolar/registror.sitem_canting;
		    end if;


		select sum(ret_cantidad) into cantret from
    		    retiros where registror.sitem_id=ret_idsitem and date_le(closeop(ret_idopera),fecha) and estadop(ret_idopera)=101;

		    if not found then 
			    retirado:=0;
			else
			    retirado:=cantret*precio;
		    end if;

		    if(retirado is not null and retirado!=0) then   retval:=retval-retirado; end if;

		end if;

		end loop; 

retval:=retval::numeric(15,2);

RETURN retval;
END;$_$;


ALTER FUNCTION public.fob_a_fecha_oper(integer, date) OWNER TO estlm;

--
-- Name: fobpadre_vs_fobhijos(integer, smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION fobpadre_vs_fobhijos(integer, smallint) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	id		ALIAS FOR $1; -- id dela OP.
	modo		ALIAS FOR $2; -- Modalidad de Operacion.
	fobt 		numeric;
	fobs 		numeric;
	retval 		numeric;
	cantidad	numeric;
    BEGIN
    SELECT   op_importe INTO fobt FROM operaciones WHERE op_id=id;
    
    if  int2eq(modo,1::int2) then
	 fobs := fob_hijos1(id,1::int2);
	 else
	 fobs := fob_hijos2(id,2::int2);
    end if;

    if (fobs is not null and fobs!=0) then cantidad=1::numeric; else fobs=0; end if;

    retval := fobt - fobs;
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.fobpadre_vs_fobhijos(integer, smallint) OWNER TO estlm;

--
-- Name: gastoct(integer, integer, integer, numeric); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION gastoct(integer, integer, integer, numeric) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	idastoh		ALIAS FOR $1; 
	cuenta		ALIAS FOR $2; 
	grupo		ALIAS FOR $3; 
	importe		ALIAS FOR $4; 
	retval 		integer;
    BEGIN
    retval:=0;
    if numeric_ne(importe,0::numeric) then

	insert into astoctas (astc_idastoh,astc_ctacble,astc_importe,astc_grupo,astc_codemp,astc_idptov,astc_comprob,astc_numero,astc_fecval,astc_estado) 
	     select idastoh,cuenta,importe,grupo,ash_codemp,ash_idptov,ash_comprob,ash_numero,ash_fecval,-1 
	         from astoh where ash_id=idastoh;

	select astc_id into retval from astoctas order by astc_id desc limit 1;
    end if;
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.gastoct(integer, integer, integer, numeric) OWNER TO estlm;

--
-- Name: gastoct_cta(integer, integer, integer, numeric, integer, integer, integer, date); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION gastoct_cta(integer, integer, integer, numeric, integer, integer, integer, date) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	idastoh		ALIAS FOR $1; 
	cuenta		ALIAS FOR $2; 
	grupo		ALIAS FOR $3; 
	importe		ALIAS FOR $4; 
	tipcta		ALIAS FOR $5; 
	ctacte		ALIAS FOR $6; 
	nucheq		ALIAS FOR $7; 
	fecvto		ALIAS FOR $8; 
	retval 		integer;
    BEGIN
    retval:=0;
    if numeric_ne(importe,0::numeric) then
	insert into astoctas (astc_idastoh,astc_ctacble,astc_importe,astc_grupo,astc_codemp,astc_idptov,astc_comprob,astc_numero,astc_fecval,astc_estado,astc_tipcta,astc_ctacte,astc_nucheq,astc_fecvto) 
	     select idastoh,cuenta,importe,grupo,ash_codemp,ash_idptov,ash_comprob,ash_numero,ash_fecval,-1,tipcta,ctacte,nucheq,fecvto
	         from astoh where ash_id=idastoh;

	select astc_id into retval from astoctas order by astc_id desc limit 1;
    end if;
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.gastoct_cta(integer, integer, integer, numeric, integer, integer, integer, date) OWNER TO estlm;

--
-- Name: genernd(integer, integer, integer, numeric); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION genernd(integer, integer, integer, numeric) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
idastoh		 alias for $1;
elcliente	 alias for $2;
nrogpo		 alias for $3;
totpag		 alias for $4;
ret 		 integer;
registro	 record;
regi		 record;
regi2		 record;
codemp		 integer;
idpto		 integer;
tipct		 integer;
ctadxv		 integer;
ctabco		 integer;
ctachq		 integer;
ctadocu		 integer;
primera		 integer;
salgrup		 numeric;
llevo		 numeric;
interd		 numeric;
prompago	 date;
acum1		 numeric;
acum2		 numeric;
tempor		 numeric;
valmin		 numeric;
begin

ret:=0;
llevo:=0;
acum1:=0;
acum2:=0;
tempor:=0;

select ash_codemp,ash_idptov into codemp,idpto from astoh where ash_id=idastoh;
select idcbl(codemp,valvaramb(codemp,0,'DEUDXV')::integer) into ctadxv;   
select idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer) into ctachq;   
select idcbl(codemp,valvaramb(codemp,0,'BANCO')::integer) into ctabco;   
select idcbl(codemp,valvaramb(codemp,0,'DOCUM')::integer) into ctadocu;   
select sum(astc_importe) into salgrup from astoctas where astc_codemp=codemp and astc_ctacble=ctadxv and astc_ctacte=elcliente and astc_grupo=nrogpo and astc_idastoh!=idastoh;
select (contr_inter * valvaramb(codemp,0,'INTBP')::numeric) into interd from contratos where contr_locatario=codcli(elcliente) and contr_idsubt in (0,1,2,3,4,5,6) and contr_inter is not null order by contr_id desc limit 1;
select valvaramb(codemp,0,'VALMINND') into valmin;   


if interd is null then
interd:= 20000.1;
end if;

for regi in select 
     * from astoctas where astc_idastoh=idastoh
    loop
	if(numeric_gt(regi.astc_importe,0::numeric)) then

	    if(int4eq(regi.astc_ctacble,ctachq)) then
		for regi2 in select * from cheques where chq_idastoc=regi.astc_id
		    loop
			select (regi2.chq_fecheq - '01-01-1900'::date) * regi2.chq_importe into acum1;
			acum2:=acum2 + acum1;
		    end loop; 
		tempor:=acum2;
		acum1:=0;
		acum2:=0;
	      else
		if(int4eq(regi.astc_ctacble,ctadocu)) then
		    for regi2 in select * from docum where doc_idastoc=regi.astc_id
			loop
			    select (regi2.doc_fecdoc - '01-01-1900'::date) * regi2.doc_importe into acum1;
			    acum2:=acum2 + acum1;
			end loop; 
		    tempor:= tempor + acum2;
		    acum1:=0;
		    acum2:=0;
	          else
		    if(int4eq(regi.astc_ctacble,ctabco)) then
			select (regi.astc_fecvto - '01-01-1900'::date) * regi.astc_importe into acum1;
			tempor:= tempor + acum1;
			acum1:=0;
			acum2:=0;
	              else
			select (regi.astc_fecval - '01-01-1900'::date) * regi.astc_importe into acum1;
			tempor:= tempor + acum1;
    		    end if;
    		end if;
    	    end if;
	end if;
    end loop; 

select ('01-01-1900'::date + (tempor / totpag)::integer) into prompago;


primera:=1;
for registro in select 
     * from astoctas where astc_codemp=codemp and astc_ctacble=ctadxv and astc_ctacte=elcliente and astc_grupo=nrogpo order by astc_fecval,astc_idastoh desc
    loop
	if(numeric_le(registro.astc_importe,salgrup) and numeric_gt(registro.astc_importe,0::numeric)) then
	    llevo:= llevo + (registro.astc_importe * (prompago - registro.astc_fecvto) * interd / 100 / 30);
	    salgrup:= salgrup - registro.astc_importe;
	  else 
	    if(numeric_gt(registro.astc_importe,salgrup) and numeric_gt(registro.astc_importe,0::numeric)) then
		llevo:=llevo + (salgrup * (prompago - registro.astc_fecvto) * interd  / 100 / 30);
	    end if;
	end if;
    end loop; 



if numeric_ge(llevo,valmin) then
    insert into notdeb (nd_idasho,nd_codemp,nd_idptov,nd_fecval,nd_grupo,nd_codcli,nd_tpago,nd_tnd,nd_interes) values (idastoh,codemp,idpto,date(now()),nrogpo,elcliente,totpag,llevo,interd);
    select max(nd_id) into ret from notdeb;
end if;


return ret;
end;$_$;


ALTER FUNCTION public.genernd(integer, integer, integer, numeric) OWNER TO estlm;

--
-- Name: genernd1(integer, integer, integer, numeric); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION genernd1(integer, integer, integer, numeric) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
declare
idastoh		 alias for $1;
elcliente	 alias for $2;
nrogpo		 alias for $3;
totpag		 alias for $4;
ret 		 numeric;
registro	 record;
regi		 record;
regi2		 record;
codemp		 integer;
idpto		 integer;
tipct		 integer;
ctadxv		 integer;
ctabco		 integer;
ctachq		 integer;
ctadocu		 integer;
primera		 integer;
salgrup		 numeric;
llevo		 numeric;
interd		 numeric;
prompago	 date;
acum1		 numeric;
acum2		 numeric;
tempor		 numeric;
valmin		 numeric;
begin

ret:=0;
llevo:=0;
acum1:=0;
acum2:=0;
tempor:=0;

select ash_codemp,ash_idptov into codemp,idpto from astoh where ash_id=idastoh;
select idcbl(codemp,valvaramb(codemp,0,'DEUDXV')::integer) into ctadxv;   
select idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer) into ctachq;   
select idcbl(codemp,valvaramb(codemp,0,'BANCO')::integer) into ctabco;   
select idcbl(codemp,valvaramb(codemp,0,'DOCUM')::integer) into ctadocu;   
select sum(astc_importe) into salgrup from astoctas where astc_codemp=codemp and astc_ctacble=ctadxv and astc_ctacte=elcliente and astc_grupo=nrogpo and astc_idastoh!=idastoh;
select (contr_inter * valvaramb(codemp,0,'INTBP')::numeric) into interd from contratos where contr_locatario=codcli(elcliente) and contr_idsubt in (0,1,2,3,4,5,6) and contr_inter is not null order by contr_id desc limit 1;
select valvaramb(codemp,0,'VALMINND') into valmin;   


if interd is null then
interd:= 20000.1;
end if;



for regi in select 
     * from astoctas where astc_idastoh=idastoh
    loop
	if(numeric_gt(regi.astc_importe,0::numeric)) then

	    if(int4eq(regi.astc_ctacble,ctachq)) then
		for regi2 in select * from cheques where chq_idastoc=regi.astc_id
		    loop
			select (regi2.chq_fecheq - '01-01-1900'::date) * regi2.chq_importe into acum1;
			acum2:=acum2 + acum1;
		    end loop; 
		tempor:=acum2;
		acum1:=0;
		acum2:=0;
	      else
		if(int4eq(regi.astc_ctacble,ctadocu)) then
		    for regi2 in select * from docum where doc_idastoc=regi.astc_id
			loop
			    select (regi2.doc_fecdoc - '01-01-1900'::date) * regi2.doc_importe into acum1;
			    acum2:=acum2 + acum1;
			end loop; 
		    tempor:= tempor + acum2;
		    acum1:=0;
		    acum2:=0;
	          else
		    if(int4eq(regi.astc_ctacble,ctabco)) then
			select (regi.astc_fecvto - '01-01-1900'::date) * regi.astc_importe into acum1;
			tempor:= tempor + acum1;
			acum1:=0;
			acum2:=0;
	              else
			select (regi.astc_fecval - '01-01-1900'::date) * regi.astc_importe into acum1;
			tempor:= tempor + acum1;
    		    end if;
    		end if;
    	    end if;
	end if;
    end loop; 


select ('01-01-1900'::date + (tempor / totpag)::integer) into prompago;


primera:=1;
for registro in select 
     * from astoctas where astc_codemp=codemp and astc_ctacble=ctadxv and astc_ctacte=elcliente and astc_grupo=nrogpo order by astc_fecval,astc_idastoh desc
    loop
	if(numeric_le(registro.astc_importe,salgrup) and numeric_gt(registro.astc_importe,0::numeric)) then
	    llevo:= llevo + (registro.astc_importe * (prompago - registro.astc_fecvto) * interd / 100 / 30);
	    salgrup:= salgrup - registro.astc_importe;
	  else 
	    if(numeric_gt(registro.astc_importe,salgrup) and numeric_gt(registro.astc_importe,0::numeric)) then
		llevo:=llevo + (salgrup * (prompago - registro.astc_fecvto) * interd  / 100 / 30);
	    end if;
	end if;
    end loop; 

ret:=salgrup;


return ret;
end;$_$;


ALTER FUNCTION public.genernd1(integer, integer, integer, numeric) OWNER TO estlm;

--
-- Name: get_idopera(integer, integer, smallint, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION get_idopera(integer, integer, smallint, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
directo	 	 alias for $1;
indirecto	 alias for $2;
tipoper		 alias for $3;
nro		 alias for $4;
ret 		 int4;
begin
select op_id into ret from operaciones where
op_directo=directo and op_indirecto=indirecto and
op_tipoper=tipoper and op_nrotaldir=nro ;
return ret;
end;$_$;


ALTER FUNCTION public.get_idopera(integer, integer, smallint, integer) OWNER TO estlm;

--
-- Name: graboastocta(integer, numeric, numeric, numeric); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION graboastocta(integer, numeric, numeric, numeric) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	idastoh		ALIAS FOR $1; 
	iva		ALIAS FOR $2; 
	ivast		ALIAS FOR $3; 
	descto		ALIAS FOR $4; 
	registro	record;
	regis		record;
	codemp		integer;
	idptov		integer;
	comprob 	integer;
	numero		integer;
	fecval		date;
	total		numeric;
	otros		numeric;
	ctadeud		integer;
	tipct		integer;
	tctdepg		integer;
	elcli		integer;
	signo		integer;
	grupo		integer;
	ctaiva		integer;
	ctaivast	integer;
	ctadescto	integer;
	codcompr	character varying;
	retval 		integer;
    BEGIN
select ash_codemp,ash_idptov,ash_comprob,ash_numero,ash_fecval into codemp,idptov,comprob,numero,fecval from astoh where ash_id=idastoh;
select idcbl(codemp, valvaramb(codemp,idptov,'DEUDXV')::smallint) into ctadeud;
select valvaramb(codemp,1,'TIPCTADEPG')::integer into tctdepg;
select tipctacbl(ctadeud) into tipct;
select emi_codcli,emi_grupo into elcli,grupo from emiti where emi_idastoh=idastoh;
select codcompash(idastoh) into codcompr;

if (bpchareq(codcompr,'CA') or bpchareq(codcompr,'CB') or bpchareq(codcompr,'CC')) then
	signo= -1; 
    else
	signo= 1; 
end if;


total:=0;
for registro in select a.art_idcbl as cuenta, b.movs_tasa as latasa, tipctacbl(a.art_idcbl) as cualtipcta, sum(b.movs_importe) as cuanto 
     from movsto b, articvta a where b.movs_idastoh=idastoh 
        and b.movs_artic=a.art_id group by 1,2,3
	loop

	if found then 
	    if(int4eq(registro.cualtipcta, tctdepg)) then
		insert into astoctas (astc_ctacte,astc_tipcta,astc_tasa,astc_ctacble,astc_importe,astc_idastoh,astc_estado,astc_codemp,astc_idptov,astc_comprob,astc_numero,astc_fecval) 
		    values (idctes(tctdepg,codcli(elcli)),tctdepg,registro.latasa,registro.cuenta,(registro.cuanto * -1)::numeric,idastoh,-1::int2,codemp,idptov,comprob,numero,fecval::date);
	      else
		insert into astoctas (astc_tasa,astc_ctacble,astc_importe,astc_idastoh,astc_estado,astc_codemp,astc_idptov,astc_comprob,astc_numero,astc_fecval) 
		    values (registro.latasa,registro.cuenta,(registro.cuanto * -1)::numeric,idastoh,-1::int2,codemp,idptov,comprob,numero,fecval::date);
	    end if;
	    total:=total + registro.cuanto;
	end if;
end loop; 


for regis in select movs_tasa as vlatasa, sum(movs_importe) as vcuanto
     from movsto where movs_idastoh=idastoh group by 1
	loop
	if found then 
	    if numeric_ne(regis.vlatasa,0::numeric) then 
		select idcbl(codemp, valvaramb(codemp,idptov,'CTAIVA')::smallint) into ctaiva;
		insert into astoctas (astc_tasa,astc_ctacble,astc_importe,astc_idastoh,astc_estado,astc_codemp,astc_idptov,astc_comprob,astc_numero,astc_fecval) 
		    values (regis.vlatasa,ctaiva,(regis.vcuanto * -1 * regis.vlatasa / 100)::numeric(15,2),idastoh,-1::int2,codemp,idptov,comprob,numero,fecval::date);
	    end if;
	end if;
end loop; 


if numeric_ne(iva,0::numeric) then
    total:=total + iva;
end if;

if numeric_ne(ivast,0::numeric) then
select idcbl(codemp, valvaramb(codemp,idptov,'CTAIVAST')::smallint) into ctaivast;
    insert into astoctas (astc_ctacble,astc_importe,astc_idastoh,astc_estado,astc_codemp,astc_idptov,astc_comprob,astc_numero,astc_fecval) 
	values (ctaivast,(ivast * -1 * signo)::numeric,idastoh,-1::int2,codemp,idptov,comprob,numero,fecval::date);
total:=total + (ivast * signo);
end if;

if numeric_ne(descto,0::numeric) then
select idcbl(codemp, valvaramb(codemp,idptov,'CTADESCTO')::smallint) into ctadescto;
    insert into astoctas (astc_ctacble,astc_importe,astc_idastoh,astc_estado,astc_codemp,astc_idptov,astc_comprob,astc_numero,astc_fecval) 
	values (ctadescto,(descto * -1 * signo)::numeric,idastoh,-1::int2,codemp,idptov,comprob,numero,fecval::date);
total:=total + (descto * signo);
end if;

insert into astoctas (astc_grupo,astc_ctacte,astc_tipcta,astc_ctacble,astc_importe,astc_idastoh,astc_estado,astc_codemp,astc_idptov,astc_comprob,astc_numero,astc_fecval) 
	values (grupo,elcli,tipct,ctadeud,total::numeric,idastoh,-1::int2,codemp,idptov,comprob,numero,fecval::date);

update emiti set emi_total=total where emi_idastoh=idastoh;

retval:=signo;

RETURN retval;
END;$_$;


ALTER FUNCTION public.graboastocta(integer, numeric, numeric, numeric) OWNER TO estlm;

--
-- Name: graboastoctac(integer, numeric, numeric, numeric, integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION graboastoctac(integer, numeric, numeric, numeric, integer, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	idastoh		ALIAS FOR $1; 
	iva		ALIAS FOR $2; 
	ivast		ALIAS FOR $3; 
	descto		ALIAS FOR $4; 
	tipcta		ALIAS FOR $5; 
	ctact		ALIAS FOR $6; 
	registro	record;
	regis		record;
	codemp		integer;
	idptov		integer;
	comprob 	integer;
	numero		integer;
	fecval		date;
	total		numeric;
	otros		numeric;
	ctadeud		integer;
	tipct		integer;
	tctdepg		integer;
	elcli		integer;
	signo		integer;
	grupo		integer;
	ctaiva		integer;
	ctaivast	integer;
	ctadescto	integer;
	codcompr	character varying;
	retval 		integer;
    BEGIN
select ash_codemp,ash_idptov,ash_comprob,ash_numero,ash_fecval into codemp,idptov,comprob,numero,fecval from astoh where ash_id=idastoh;
select idcbl(codemp, valvaramb(codemp,idptov,'DEUDXV')::smallint) into ctadeud;
select valvaramb(codemp,1,'TIPCTADEPG')::integer into tctdepg;
select tipctacbl(ctadeud) into tipct;
select emi_codcli,emi_grupo into elcli,grupo from emiti where emi_idastoh=idastoh;
select codcompash(idastoh) into codcompr;

if (bpchareq(codcompr,'CA') or bpchareq(codcompr,'CB') or bpchareq(codcompr,'CC')) then
	signo= -1; 
    else
	signo= 1; 
end if;


total:=0;
for registro in select a.art_idcbl as cuenta, b.movs_tasa as latasa, tipctacbl(a.art_idcbl) as cualtipcta, sum(b.movs_importe) as cuanto 
     from movsto b, articvta a where b.movs_idastoh=idastoh 
        and b.movs_artic=a.art_id group by 1,2,3
	loop

	if found then 
	    if(int4eq(registro.cualtipcta, tctdepg)) then
		insert into astoctas (astc_ctacte,astc_tipcta,astc_tasa,astc_ctacble,astc_importe,astc_idastoh,astc_estado,astc_codemp,astc_idptov,astc_comprob,astc_numero,astc_fecval) 
		    values (idctes(tctdepg,codcli(elcli)),tctdepg,registro.latasa,registro.cuenta,(registro.cuanto * -1)::numeric,idastoh,-1::int2,codemp,idptov,comprob,numero,fecval::date);
	      else
	    if(int4eq(registro.cualtipcta, tipcta)) then
		insert into astoctas (astc_ctacte,astc_tipcta,astc_tasa,astc_ctacble,astc_importe,astc_idastoh,astc_estado,astc_codemp,astc_idptov,astc_comprob,astc_numero,astc_fecval) 
		    values (ctact,tipcta,registro.latasa,registro.cuenta,(registro.cuanto * -1)::numeric,idastoh,-1::int2,codemp,idptov,comprob,numero,fecval::date);
	      else
		insert into astoctas (astc_tasa,astc_ctacble,astc_importe,astc_idastoh,astc_estado,astc_codemp,astc_idptov,astc_comprob,astc_numero,astc_fecval) 
		    values (registro.latasa,registro.cuenta,(registro.cuanto * -1)::numeric,idastoh,-1::int2,codemp,idptov,comprob,numero,fecval::date);
	    end if;
	    end if;
	    total:=total + registro.cuanto;
	end if;
end loop; 


for regis in select movs_tasa as vlatasa, sum(movs_importe) as vcuanto
     from movsto where movs_idastoh=idastoh group by 1
	loop
	if found then 
	    if numeric_ne(regis.vlatasa,0::numeric) then 
		select idcbl(codemp, valvaramb(codemp,idptov,'CTAIVA')::smallint) into ctaiva;
		insert into astoctas (astc_tasa,astc_ctacble,astc_importe,astc_idastoh,astc_estado,astc_codemp,astc_idptov,astc_comprob,astc_numero,astc_fecval) 
		    values (regis.vlatasa,ctaiva,(regis.vcuanto * -1 * regis.vlatasa / 100)::numeric(15,2),idastoh,-1::int2,codemp,idptov,comprob,numero,fecval::date);
	    end if;
	end if;
end loop; 


if numeric_ne(iva,0::numeric) then
    total:=total + iva;
end if;

if numeric_ne(ivast,0::numeric) then
select idcbl(codemp, valvaramb(codemp,idptov,'CTAIVAST')::smallint) into ctaivast;
    insert into astoctas (astc_ctacble,astc_importe,astc_idastoh,astc_estado,astc_codemp,astc_idptov,astc_comprob,astc_numero,astc_fecval) 
	values (ctaivast,(ivast * -1 * signo)::numeric,idastoh,-1::int2,codemp,idptov,comprob,numero,fecval::date);
total:=total + (ivast * signo);
end if;

if numeric_ne(descto,0::numeric) then
select idcbl(codemp, valvaramb(codemp,idptov,'CTADESCTO')::smallint) into ctadescto;
    insert into astoctas (astc_ctacble,astc_importe,astc_idastoh,astc_estado,astc_codemp,astc_idptov,astc_comprob,astc_numero,astc_fecval) 
	values (ctadescto,(descto * -1 * signo)::numeric,idastoh,-1::int2,codemp,idptov,comprob,numero,fecval::date);
total:=total + (descto * signo);
end if;

insert into astoctas (astc_grupo,astc_ctacte,astc_tipcta,astc_ctacble,astc_importe,astc_idastoh,astc_estado,astc_codemp,astc_idptov,astc_comprob,astc_numero,astc_fecval) 
	values (grupo,elcli,tipct,ctadeud,total::numeric,idastoh,-1::int2,codemp,idptov,comprob,numero,fecval::date);

update emiti set emi_total=total where emi_idastoh=idastoh;

retval:=signo;

RETURN retval;
END;$_$;


ALTER FUNCTION public.graboastoctac(integer, numeric, numeric, numeric, integer, integer) OWNER TO estlm;

--
-- Name: grabocontrapart(integer, integer, numeric, numeric); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION grabocontrapart(integer, integer, numeric, numeric) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
sitem			alias for $1; -- Id del Subitem retirado
operacion 		alias for $2; -- Operacion de contrapartida
cantidad 		alias for $3; -- Cantidad Retirada a Ingresar
importe 		alias for $4; -- Importe del Subitem a crear (retiro)
registro_op 		RECORD;
registro_artic		RECORD;
registro_item 		RECORD;
registro_sitem 		RECORD;
nuevoiditem		int4;
codarticulo		varchar;
articulo		int4;
iddelitem		int4;
impsitem		numeric;
impdolsitem		numeric;
idsitemcreado		int4;
ret			int4;

begin

for registro_op in select 
    op_directo as directo, 
    op_indirecto as indirecto, 
    op_moneda as monedao, 
    op_deposito as deposito 
     from operaciones where op_id=operacion
	loop
	    ret:=1;		
	end loop; 

    for registro_sitem in select 
	sitem_iditem as iditem, 
	sitem_idoper as operacontrap, 
        sitem_artic as idartic, 
	sitem_tipemb as tipemb, 
	sitem_deposito as sdeposito, 
        sitem_compbte as compbte 
	 from subitem where sitem_id=sitem
	    loop
	    iddelitem:=registro_sitem.iditem;
	    ret:=1;		
	end loop; 

select artic_codigo into codarticulo from articu
where artic_id=registro_sitem.idartic;


select artic_id into articulo from articu
where artic_codigo=codarticulo and artic_indirecto=registro_op.indirecto;
if not found then

for registro_artic in select 
    artic_marca as marca, 
    artic_modelo as modelo, 
    artic_descrip as descrip, 
    artic_present as present, 
    artic_tiprod as arttiprod, 
    artic_posa as artposa, 
    artic_unimed as artunimed 
     from articu where artic_id=registro_sitem.idartic
	loop

if(registro_artic.arttiprod is null) then registro_artic.arttiprod:=1; end if;
if(registro_artic.artunimed is null) then registro_artic.artunimed:=1; end if;
if(registro_artic.artposa is null) then registro_artic.artposa:='DESCONOCIDA'; end if;
if(registro_artic.marca is null) then registro_artic.marca:='DESCONOCIDA'; end if;
if(registro_artic.modelo is null) then registro_artic.modelo:='DESCONOCIDA'; end if;
if(registro_artic.descrip is null) then registro_artic.descrip:='DESCONOCIDA'; end if;
if(registro_artic.present is null) then registro_artic.present:='DESCONOCIDA'; end if;
--begin work; 
--lock item in access exclusive mode;
insert into articu (artic_indirecto,artic_codigo,artic_marca,artic_modelo,artic_descrip,artic_present,artic_tiprod,artic_posa,artic_unimed) 
values (registro_op.indirecto,codarticulo,registro_artic.marca,registro_artic.modelo,registro_artic.descrip,registro_artic.present,registro_artic.arttiprod,registro_artic.artposa,registro_artic.artunimed);

select max(artic_id) into articulo from articu;
--commit;
end loop; 
end if;


	for registro_item in select 
	    item_moneda as moneda, 
	    item_tipprod as tipprod, 
	    item_unimed as unimed, 
	    item_posa as posa 
	     from item where item_id=iddelitem
		loop

	    if(registro_item.moneda is null) then registro_item.moneda:=registro_op.monedao; end if;
	    if(registro_item.tipprod is null) then registro_item.tipprod:=registro_artic.arttiprod; end if;
	    if(registro_item.unimed is null) then registro_item.unimed:=registro_artic.artunimed; end if;
	    if(registro_item.posa is null) then registro_item.posa:=registro_artic.artposa; end if;
	    
--	    begin work; 
--	    lock item in access exclusive mode;
	    insert into item (item_idoper,item_moneda,item_tipprod,item_unimed,item_posa) 
	    values (operacion,registro_item.moneda,registro_item.tipprod,registro_item.unimed,registro_item.posa);
	    select max(item_id) into nuevoiditem from item;
--	    commit;

	    if(registro_op.deposito is null) then registro_op.deposito:=registro_sitem.sdeposito; end if;

	    if (importe>0) then
		    impsitem:=importe;
		    impdolsitem:=importe * moncteopera(operacion);
		else
		    impsitem:=cantidad*precio_unitariod(sitem);
		    impdolsitem:=impsitem;
	    end if;

	    insert into subitem (sitem_iditem,sitem_artic,sitem_tipemb,sitem_compbte,sitem_idoper,sitem_canting,sitem_importe,sitem_deposito,sitem_directo,sitem_indirecto,sitem_imp_dolar) values (nuevoiditem,articulo,registro_sitem.tipemb,registro_sitem.compbte,operacion,cantidad,impsitem,registro_op.deposito,registro_op.directo,registro_op.indirecto,impdolsitem);
	    select max(sitem_id) into idsitemcreado from subitem;
	
	    ret:=idsitemcreado;		
	end loop; 

return ret;
end;$_$;


ALTER FUNCTION public.grabocontrapart(integer, integer, numeric, numeric) OWNER TO estlm;

--
-- Name: grabocontrapart(integer, integer, real, numeric); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION grabocontrapart(integer, integer, real, numeric) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
sitem			alias for $1; -- Id del Subitem retirado
operacion 		alias for $2; -- Operacion de contrapartida
cantidad 		alias for $3; -- Cantidad Retirada a Ingresar
importe 		alias for $4; -- Importe del Subitem a crear (retiro)
registro_op 		RECORD;
registro_artic		RECORD;
registro_item 		RECORD;
registro_sitem 		RECORD;
nuevoiditem		int4;
codarticulo		varchar;
articulo		int4;
iddelitem		int4;
impsitem		numeric;
impdolsitem		numeric;
idsitemcreado		int4;
ret			int4;

begin

for registro_op in select 
    op_directo as directo, 
    op_indirecto as indirecto, 
    op_moneda as monedao, 
    op_deposito as deposito 
     from operaciones where op_id=operacion
	loop
	    ret:=1;		
	end loop; 

    for registro_sitem in select 
	sitem_iditem as iditem, 
	sitem_idoper as operacontrap, 
        sitem_artic as idartic, 
	sitem_tipemb as tipemb, 
	sitem_deposito as sdeposito, 
        sitem_compbte as compbte 
	 from subitem where sitem_id=sitem
	    loop
	    iddelitem:=registro_sitem.iditem;
	    ret:=1;		
	end loop; 

select artic_codigo into codarticulo from articu
where artic_id=registro_sitem.idartic;


select artic_id into articulo from articu
where artic_codigo=codarticulo and artic_indirecto=registro_op.indirecto;
if not found then

for registro_artic in select 
    artic_marca as marca, 
    artic_modelo as modelo, 
    artic_descrip as descrip, 
    artic_present as present, 
    artic_tiprod as arttiprod, 
    artic_posa as artposa, 
    artic_unimed as artunimed 
     from articu where artic_id=registro_sitem.idartic
	loop

if(registro_artic.arttiprod is null) then registro_artic.arttiprod:=1; end if;
if(registro_artic.artunimed is null) then registro_artic.artunimed:=1; end if;
if(registro_artic.artposa is null) then registro_artic.artposa:='DESCONOCIDA'; end if;
if(registro_artic.marca is null) then registro_artic.marca:='DESCONOCIDA'; end if;
if(registro_artic.modelo is null) then registro_artic.modelo:='DESCONOCIDA'; end if;
if(registro_artic.descrip is null) then registro_artic.descrip:='DESCONOCIDA'; end if;
if(registro_artic.present is null) then registro_artic.present:='DESCONOCIDA'; end if;
--begin work; 
--lock item in access exclusive mode;
insert into articu (artic_indirecto,artic_codigo,artic_marca,artic_modelo,artic_descrip,artic_present,artic_tiprod,artic_posa,artic_unimed) 
values (registro_op.indirecto,codarticulo,registro_artic.marca,registro_artic.modelo,registro_artic.descrip,registro_artic.present,registro_artic.arttiprod,registro_artic.artposa,registro_artic.artunimed);

select max(artic_id) into articulo from articu;
--commit;
end loop; 
end if;


	for registro_item in select 
	    item_moneda as moneda, 
	    item_tipprod as tipprod, 
	    item_unimed as unimed, 
	    item_posa as posa 
	     from item where item_id=iddelitem
		loop

	    if(registro_item.moneda is null) then registro_item.moneda:=registro_op.monedao; end if;
	    if(registro_item.tipprod is null) then registro_item.tipprod:=registro_artic.arttiprod; end if;
	    if(registro_item.unimed is null) then registro_item.unimed:=registro_artic.artunimed; end if;
	    if(registro_item.posa is null) then registro_item.posa:=registro_artic.artposa; end if;
	    
--	    begin work; 
--	    lock item in access exclusive mode;
	    insert into item (item_idoper,item_moneda,item_tipprod,item_unimed,item_posa) 
	    values (operacion,registro_item.moneda,registro_item.tipprod,registro_item.unimed,registro_item.posa);
	    select max(item_id) into nuevoiditem from item;
--	    commit;

	    if(registro_op.deposito is null) then registro_op.deposito:=registro_sitem.sdeposito; end if;

	    if (importe>0) then
		    impsitem:=importe;
		    impdolsitem:=importe * moncteopera(operacion);
		else
		    impsitem:=cantidad*precio_unitariod(sitem);
		    impdolsitem:=impsitem;
	    end if;

	    insert into subitem (sitem_iditem,sitem_artic,sitem_tipemb,sitem_compbte,sitem_idoper,sitem_canting,sitem_importe,sitem_deposito,sitem_directo,sitem_indirecto,sitem_imp_dolar) values (nuevoiditem,articulo,registro_sitem.tipemb,registro_sitem.compbte,operacion,cantidad,impsitem,registro_op.deposito,registro_op.directo,registro_op.indirecto,impdolsitem);
	    select max(sitem_id) into idsitemcreado from subitem;
	
	    ret:=idsitemcreado;		
	end loop; 

return ret;
end;$_$;


ALTER FUNCTION public.grabocontrapart(integer, integer, real, numeric) OWNER TO estlm;

--
-- Name: grabonotiweb(integer, integer, integer, character varying, text); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION grabonotiweb(integer, integer, integer, character varying, text) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
DECLARE
directo		ALIAS FOR $1; 	-- id del directo si es cero a todos
operador	ALIAS FOR $2;	-- Operador de carga
prioridad	ALIAS FOR $3;	 
titulo		ALIAS FOR $4;	 
texto		ALIAS FOR $5; 	-- texto
registro 	RECORD;
retval 		boolean;
BEGIN
retval:='t';		

if directo=0 then
	for registro in select usu_codigo as x
	    from usuarios where usu_tipusu=1 and usu_codigo>3
		loop
		    insert into wnoticias (wnot_directo,wnot_operadcar,wnot_prioridad,wnot_titulo,wnot_texto) values (registro.x,operador,prioridad,titulo::varchar,texto::text);
		end loop; 
    else
	insert into wnoticias (wnot_directo,wnot_operadcar,wnot_prioridad,wnot_titulo,wnot_texto) values (directo,operador,prioridad,titulo::varchar,texto::text);

end if;

RETURN retval;
END;$_$;


ALTER FUNCTION public.grabonotiweb(integer, integer, integer, character varying, text) OWNER TO estlm;

--
-- Name: grupocli(integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION grupocli(integer, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	cliente		ALIAS FOR $1; 
	modo		ALIAS FOR $2; -- 1:graba  2:consulta
	otro 		integer;
	retval 		integer;
    BEGIN
    select cli_grupo into retval from
    	 clientes where int4eq(cliente,cli_id);

    if found then
	if int4eq(modo,1) then
	    update clientes set cli_grupo=cli_grupo+1 where int4eq(cliente,cli_id);
	end if;		
    end if;
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.grupocli(integer, integer) OWNER TO estlm;

--
-- Name: grupoprov(integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION grupoprov(integer, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	provd		ALIAS FOR $1; 
	modo		ALIAS FOR $2; -- 1:graba  2:consulta
	otro 		integer;
	retval 		integer;
    BEGIN
    select prov_grupo into retval from
    	 prove where int4eq(provd,prov_id);

    if found then
	if int4eq(modo,1) then
	    update prove set prov_grupo=prov_grupo+1 where int4eq(provd,prov_id);
	end if;		
    end if;
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.grupoprov(integer, integer) OWNER TO estlm;

--
-- Name: gsiessensible(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION gsiessensible(integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
oper		alias for $1;
registro	RECORD;
tipodeop	int4;
essensi		int4;
ret 		int4;
begin
ret:=0;


    select tipoperdeop(oper) into tipodeop;
	if int4lt(tipodeop,6) then

	for registro in select * from item where item_idoper=oper
	    loop
	    select es_sensible('registro.item_posa') into essensi;
		if int4eq(essensi,2) then
		    insert into operest (opr_idoper,opr_compbte) values (oper,compbteoper(oper));
		end if;
	    ret:= 1;
	    end loop; 
	end if;

return ret;
END;$_$;


ALTER FUNCTION public.gsiessensible(integer) OWNER TO estlm;

--
-- Name: gtutti(integer, character varying); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION gtutti(integer, character varying) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
opid		 alias for $1;
compbte	 	 alias for $2;
ret 		 boolean;
registro	 record;
disponible	 numeric;
primera		 int4;
directo		 int4;
haycuantos	 int2;
elmayor		 int2;
indirecto	 int4;
begin
primera:=-1;

select op_directo,op_indirecto into directo,indirecto from operaciones where op_id=opid;

	select count(*) into haycuantos from retiros where ret_idopera=opid;
	if(int2eq(haycuantos,0::int2)) then
	    haycuantos:=0;
	end if;

	select max(ret_item) into elmayor from retiros where ret_idopera=opid;

	if(int2lt(haycuantos,elmayor)) then
	    haycuantos:=elmayor;
	end if;

for registro in select 
     * from subitem where sitem_estado=1 and bpchareq(sitem_compbte,compbte) and sitem_directo=directo and sitem_indirecto=indirecto and estadop(sitem_idoper)=101
	loop
	disponible:=registro.sitem_canting-registro.sitem_cantcomp-registro.sitem_cantret-registro.sitem_cantmala;
	if(disponible>0) then 

	    haycuantos:=haycuantos+1;
	    insert into retiros (ret_item,ret_idopera,ret_idsitem,ret_cantidad) values (haycuantos,opid,registro.sitem_id,disponible);
	end if;
end loop; 

return ret;
end;$_$;


ALTER FUNCTION public.gtutti(integer, character varying) OWNER TO estlm;

--
-- Name: gtuttiopinter(integer, character varying); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION gtuttiopinter(integer, character varying) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
opid		 alias for $1;
compbte	 	 alias for $2;
ret 		 boolean;
registro	 record;
disponible	 numeric;
primera		 int4;
sitemcreado	 int4;
retcreado	 int4;
nopid		 int4;
directo		 int4;
haycuantos	 int2;
elmayor		 int2;
tipoper		 int4;
indirecto	 int4;
begin
primera:=-1;
nopid:=opid+1;

select op_directo,op_indirecto into directo,indirecto from operaciones where op_id=opid;

	select count(*) into haycuantos from retiros where ret_idopera=opid;
	if(int2eq(haycuantos,0::int2)) then
	    haycuantos:=0;
	end if;

	select max(ret_item) into elmayor from retiros where ret_idopera=opid;

	if(int2lt(haycuantos,elmayor)) then
	    haycuantos:=elmayor;
	end if;

	select op_tipoper into tipoper from operaciones where op_id=opid;


for registro in select 
     * from subitem where sitem_estado=1 and bpchareq(sitem_compbte,compbte) and sitem_directo=directo and sitem_indirecto=indirecto and estadop(sitem_idoper)=101
	loop
	disponible:=registro.sitem_canting-registro.sitem_cantcomp-registro.sitem_cantret-registro.sitem_cantmala;
	if(disponible>0) then 
	    haycuantos:=haycuantos+1;
	    insert into retiros (ret_item,ret_idopera,ret_idsitem,ret_cantidad) values (haycuantos,opid,registro.sitem_id,disponible);
	    select max(ret_id) into retcreado from retiros where ret_idopera=opid;
	    select grabocontrapart(registro.sitem_id,nopid,disponible,0::numeric) into sitemcreado;
	    update retiros set ret_idsitemc=sitemcreado where ret_id=retcreado;
	end if;
end loop; 

return ret;
end;$_$;


ALTER FUNCTION public.gtuttiopinter(integer, character varying) OWNER TO estlm;

--
-- Name: gtuttiw(integer, character varying); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION gtuttiw(integer, character varying) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
opid		 alias for $1;
compbte	 	 alias for $2;
ret 		 boolean;
registro	 record;
disponible	 numeric;
primera		 int4;
directo		 int4;
haycuantos	 int2;
elmayor		 int2;
indirecto	 int4;
begin
primera:=-1;

    select wop_directo,wop_indirecto into directo,indirecto from woperaciones where wop_id=opid;

    select count(*) into haycuantos from wret2 where wret2_idopera=opid;
    if(int2eq(haycuantos,0::int2)) then
        haycuantos:=0;
    end if;

    select max(wret2_item) into elmayor from wret2 where wret2_idopera=opid;
    if(int2lt(haycuantos,elmayor)) then
        haycuantos:=elmayor;
    end if;

for registro in select 
     * from wsubitem where wsitem_directo=directo and wsitem_indirecto=indirecto and bpchareq(wsitem_compbte,compbte) 
    loop
	disponible:=registro.wsitem_canting-registro.wsitem_cantcomp-registro.wsitem_cantcompw-registro.wsitem_cantret-registro.wsitem_cantmala;
	if(disponible>0) then 

	    haycuantos:=haycuantos+1;
	    insert into wret2 (wret2_item,wret2_idopera,wret2_idsitem,wret2_cantidad) values (haycuantos,opid,registro.wsitem_id,disponible);
	end if;
    end loop; 

return ret;
end;$_$;


ALTER FUNCTION public.gtuttiw(integer, character varying) OWNER TO estlm;

--
-- Name: habro_ejercicio(character varying, date, integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION habro_ejercicio(character varying, date, integer, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
comprobante	 alias for $1;
fecha		 alias for $2;
codemp		 alias for $3;
idptov		 alias for $4;
ret 		 boolean;
registro	 record;
elcomprob 	 integer;
compcierre 	 integer;
cuentardo 	 integer;
nrocomp 	 integer;
cuenta 	 	 integer;
subcuenta 	 integer;
resultad 	 numeric(15,2);
tituloa	 	 character varying;
idastoh 	 integer;
idashcierre 	 integer;
begin
ret:='f';
    select idcomp(comprobante,idptov) into elcomprob;
    select idcomp('ZZ',idptov) into compcierre;
    select numtalon(idptov,elcomprob,1) into nrocomp;
    select comp_nombre || ' INICIADO EL ' || fecha into tituloa from comprob where comp_id=elcomprob;

    insert into astoh (ash_codemp,ash_idptov,ash_anio,ash_mes,ash_comprob,ash_numero,ash_titulo,ash_fecomp,ash_fecval,ash_leyen,ash_nro2,ash_estado) 
	values (codemp,idptov,date_part('year',fecha)::int2,date_part('month',fecha)::int2,elcomprob,nrocomp,tituloa,fecha,fecha,'Apertura de Cuentas del Ejercicio ',0,-1);

    select ash_id into idastoh from astoh where ash_codemp=codemp and ash_idptov=idptov and ash_comprob=elcomprob and ash_numero=nrocomp;

    select ash_id into idashcierre from astoh where ash_codemp=codemp and ash_idptov=idptov and ash_comprob=compcierre and date_le(ash_fecval,fecha) order by ash_id desc limit 1;

    for registro in select 
	    astc_ctacble, astc_tipcta, astc_ctacte, (astc_importe * -1) as cuanto from astoctas 
	      where astc_idastoh=idashcierre  
	    loop
		if(registro.cuanto != 0) then
		    insert into astoctas (astc_idastoh,astc_ctacble,astc_importe,astc_codemp,astc_idptov,astc_comprob,astc_numero,astc_fecval,astc_estado,astc_tipcta,astc_ctacte) 
    	    	     values (idastoh,registro.astc_ctacble,registro.cuanto,codemp,idptov,elcomprob,nrocomp,fecha,-1,registro.astc_tipcta,registro.astc_ctacte);	
		end if;
	ret:='t';
    end loop; 
    return ret;
end;$_$;


ALTER FUNCTION public.habro_ejercicio(character varying, date, integer, integer) OWNER TO estlm;

--
-- Name: hay_cont_recipro(integer, integer, smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION hay_cont_recipro(integer, integer, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	operacion	ALIAS FOR $1; 	-- id dela operacion
	directo		ALIAS FOR $2; 	-- Usuario Directo
	modo		ALIAS FOR $3; 	-- modo
					--1 valido en publicacion
					--2 valido solo
	indirecto 	int4;
	registro 	RECORD;
	retval 		boolean;
	trans 		boolean;
	aux_texto 	text;
    BEGIN
    retval:='t';		
    for registro in select sitem_deposito as y,count(*) as z
     from subitem where sitem_idoper=operacion  group by y
	loop
	select unif_usuario into indirecto from unifun where unif_codigo=registro.y;
	    if int4ne(directo,indirecto) then
		    trans:=hay_contrato(directo,indirecto,2::int2,operacion,5::int2);
		else
		    trans:='t';		
	    end if;
	end loop; 

    RETURN retval;
    END;$_$;


ALTER FUNCTION public.hay_cont_recipro(integer, integer, smallint) OWNER TO estlm;

--
-- Name: hay_cont_valido(integer, integer, smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION hay_cont_valido(integer, integer, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	usuario		ALIAS FOR $1; 	-- Titular de la unifun 
	directo		ALIAS FOR $2; 	-- Usuario Directo o indirecto
	modo 		alias for $3;  	-- 1  valida que exista contrato
					-- 2 valida que exista y este aprobado
					-- 3 valida que exista contrato y no graba noticias
					-- 4 valida que exista y este aprobado y no graba noticias
					-- 43 valida que exista  tipo contrato 3 y este aprobado y no graba noticias
					-- 443 valida que exista  tipo contrato 4 y este aprobado y no graba noticias
	indirecto 	int4;
	operacion 	int4;
	registro 	RECORD;
	retval 		boolean;
	trans 		boolean;
	aux_texto 	text;
    BEGIN
    retval:='f';		
    operacion=1;

if(usuario!=directo) then
    if usuario is not null then
	if int4ne(directo,usuario) then
	        if int2eq(modo,43::int2) then
	    		trans:=hay_contrato(usuario,directo,modo::int2,operacion,3::int2);
		    else
	    		if int2eq(modo,443::int2) then
	    			trans:=hay_contrato(usuario,directo,modo::int2,operacion,4::int2);
				if booleq(trans,'f')then
				    trans:=hay_contrato(usuario,directo,modo::int2,operacion,3::int2);
				end if;
			    else
				trans:=hay_contrato(usuario,directo,modo::int2,operacion,3::int2);
				if booleq(trans,'f')then
				    trans:=hay_contrato(usuario,directo,modo::int2,operacion,4::int2);
				    if booleq(trans,'f')then
					trans:=hay_contrato(usuario,directo,modo::int2,operacion,5::int2);
					if booleq(trans,'f')then
					    trans:=hay_contrato(usuario,directo,modo::int2,operacion,2::int2);
					end if;
				    end if;
				end if;
			end if;
		end if;
	    else
		trans:='t';		
	end if;
	retval:=trans;
    end if;
else
    retval:='t';		
end if;

    RETURN retval;
    END;$_$;


ALTER FUNCTION public.hay_cont_valido(integer, integer, smallint) OWNER TO estlm;

--
-- Name: hay_cont_valido_new(integer, integer, smallint, integer, smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION hay_cont_valido_new(integer, integer, smallint, integer, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
directo		ALIAS FOR $1; 	-- Titular de la unifun 
indirecto	ALIAS FOR $2; 	-- Usuario Directo o indirecto
deposito	ALIAS FOR $3; 	-- Unifun
operacion	ALIAS FOR $4; 	-- Operacion
modo 		alias for $5;  	-- 1 valida que exista contrato aprobado
				-- 2 valida que exista contrato aprobado y graba noticias
retval 		boolean;
estado		smallint;
aux_texto 	text;
BEGIN

    retval:='f';		
    
    if(indirecto!=directo) then
	select contr_estado into estado from contratos where contr_locador=directo and contr_locatario=indirecto and contr_unifun=deposito and contr_estado=1;
	if not found then
	    if int2eq(modo,2::int2) then
		aux_texto:='No Existe Contrato Aprobado Entre '|| nomusu(directo) ||' y '||nomusu(indirecto)||' Para el Deposito '|| deposito;
		insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
		retval:='f';		
	      else
		retval:='f';		
	    end if;
	  else
	    retval:='t';		
	end if;
      else
	retval:='t';		
    end if;

    RETURN retval;
    END;$_$;


ALTER FUNCTION public.hay_cont_valido_new(integer, integer, smallint, integer, smallint) OWNER TO estlm;

--
-- Name: hay_contrato(integer, integer, smallint, integer, smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION hay_contrato(integer, integer, smallint, integer, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
directo		 alias for $1;
indirecto	 alias for $2;
caso 		 alias for $3;  -- 1 valida que exista contrato
				-- 2 valida que exista y este aprobado
				-- 3 valida que exista contrato y no graba noticias
				-- 4 valida que exista y este aprobado y no graba noticias
				-- 43 valida que exista y este aprobado y no graba noticias
				-- 5 valida que exista y este aprobado y no haya ni reprocidad ni indirecto locador ni
operacion	 alias for $4;
tipo_contrato alias for $5;
aux_texto	 text;
ret 		 boolean;
registro	 RECORD;
estado		 int2;
unifun		 int2;
hayuno	 	 int2;
hayunoaprob	 int2;

begin
ret:='f';
hayuno:=0;
hayunoaprob:=0;

if(int4ne(directo,indirecto)) then
    if caso!=5 then
	for registro in select 
	    * from contratos where contr_locador=directo and contr_locatario=indirecto and tipo_de_contrato(contr_idsubt)=tipo_contrato
	loop
		    hayuno:=1;
    		    if int2eq(registro.contr_estado,1::int2) then
			hayunoaprob:=1;
		    end if;
	end loop;
      else
	for registro in select 
	    * from contratos where contr_locador=directo and contr_locatario=indirecto and tipo_de_contrato(contr_idsubt) in (4::int2,5::int2)
	loop
		    hayuno:=1;
    		    if int2eq(registro.contr_estado,1::int2) then
			hayunoaprob:=1;
		    end if;
	end loop;

    end if;

  else

	hayuno:=1;
	hayunoaprob:=1;
 end if;

if caso=1 and hayuno=1 then
    ret:=true;
end if;

if int2ne(caso,1::int2) and hayunoaprob=1 then     
    ret:=true;
end if;

if caso=2 and hayuno=1  and hayunoaprob=0 then
    aux_texto:='No Existe Contrato Aprobado  tipo  '||nomtipc(tipo_contrato)||' entre '||nomusu(directo) ||' y '||nomusu(indirecto)||' !!!!!!!';
    insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
end if;

if  hayuno=0  and hayunoaprob=0 and int2ne(caso,4::int2) and int4ne(directo,1) then
    aux_texto:='No Existe Contrato Aprobado  de tipo  '||nomtipc(tipo_contrato)||' entre '||nomusu(directo) ||' y '||nomusu(indirecto)||' !!!!!!!';
    insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
end if;
return ret;
END;$_$;


ALTER FUNCTION public.hay_contrato(integer, integer, smallint, integer, smallint) OWNER TO estlm;

--
-- Name: haynovedad(integer, integer, integer, date, date); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION haynovedad(integer, integer, integer, date, date) RETURNS boolean
    LANGUAGE sql
    AS $_$select true from novemple where ne_codemp= $1 and ne_objetivo= $2 and ne_legajo= $3 and date_le(ne_fecha,$5) and date_ge(ne_fecha,$4) limit 1;$_$;


ALTER FUNCTION public.haynovedad(integer, integer, integer, date, date) OWNER TO estlm;

--
-- Name: idarticvta(integer, character varying); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION idarticvta(integer, character varying) RETURNS integer
    LANGUAGE sql
    AS $_$select art_id from articvta where art_codemp= $1 and bpchareq(trim( $2 ),art_codigo);$_$;


ALTER FUNCTION public.idarticvta(integer, character varying) OWNER TO estlm;

--
-- Name: idashdecomp(integer, integer, integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION idashdecomp(integer, integer, integer, integer) RETURNS integer
    LANGUAGE sql
    AS $_$select ash_id from astoh where ash_codemp= $1 and ash_idptov= $2 and ash_comprob= $3 and ash_numero= $4;$_$;


ALTER FUNCTION public.idashdecomp(integer, integer, integer, integer) OWNER TO estlm;

--
-- Name: idcbl(integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION idcbl(integer, integer) RETURNS integer
    LANGUAGE sql
    AS $_$select cbl_id from ctacble where cbl_codemp in ( $1,0) and int4eq(cbl_codigo::integer, $2) order by cbl_codemp desc limit 1;$_$;


ALTER FUNCTION public.idcbl(integer, integer) OWNER TO estlm;

--
-- Name: idcli(integer, character varying); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION idcli(integer, character varying) RETURNS integer
    LANGUAGE sql
    AS $_$select cli_id from clientes where cli_codemp= $1 and bpchareq(cli_codigo, $2);$_$;


ALTER FUNCTION public.idcli(integer, character varying) OWNER TO estlm;

--
-- Name: idcomp(character varying, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION idcomp(character varying, integer) RETURNS integer
    LANGUAGE sql
    AS $_$select comp_id from comprob where bpchareq(trim(comp_codigo),trim( $1 )) and comp_idptov in ( $2 ,0) limit 1;$_$;


ALTER FUNCTION public.idcomp(character varying, integer) OWNER TO estlm;

--
-- Name: idctes(integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION idctes(integer, integer) RETURNS integer
    LANGUAGE sql
    AS $_$select cte_id from ctes where cte_tipcta= $1 and cte_codigo= $2;$_$;


ALTER FUNCTION public.idctes(integer, integer) OWNER TO estlm;

--
-- Name: idprov(integer, character varying); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION idprov(integer, character varying) RETURNS integer
    LANGUAGE sql
    AS $_$select prov_id from prove where prov_codemp= $1 and bpchareq(prov_codigo, $2);$_$;


ALTER FUNCTION public.idprov(integer, character varying) OWNER TO estlm;

--
-- Name: idptov(integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION idptov(integer, integer) RETURNS integer
    LANGUAGE sql
    AS $_$select ptv_id from ptovta where ptv_codemp= $1 and ptv_codigo= $2;$_$;


ALTER FUNCTION public.idptov(integer, integer) OWNER TO estlm;

--
-- Name: importedeleyen(integer, integer, integer, integer, character varying); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION importedeleyen(integer, integer, integer, integer, character varying) RETURNS numeric
    LANGUAGE sql
    AS $_$select sum(astc_importe) from astoctas where astc_estado=2 and astc_idptov=$1 and astc_ctacble=$2 and date_part('month',astc_fecval)=$3 and date_part('year',astc_fecval)=$4 and trim(astc_leyen) like trim($5);$_$;


ALTER FUNCTION public.importedeleyen(integer, integer, integer, integer, character varying) OWNER TO estlm;

--
-- Name: importo_ingreso(integer, integer, integer, integer, integer, smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION importo_ingreso(integer, integer, integer, integer, integer, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	caratul		ALIAS FOR $1; -- id de la Caratula.
	directo		ALIAS FOR $2; -- Directo.
	indirecto	ALIAS FOR $3; -- Indirecto.
	tipoper		ALIAS FOR $4; -- Tipoper.
	consig		ALIAS FOR $5; -- Consignatario.
	deposito	ALIAS FOR $6; -- Deposito.
	operacion	int4;
	elitem		int4;
	articulo	int4;
	monedi		int2;
	moned		int2;
	posafab		varchar;
	despachos	text ;
	retval		boolean;
	registro	record;
    BEGIN
	retval:='f';

	select cual_moneda(divisa_fob) into monedi from caratula where car_id=caratul;

	if(monedi is null) then 
	    select divisa_fob::int2 into monedi from caratula where car_id=caratul;
	end if;

	select mon_codigo into moned from moneda where mon_codigo=monedi;
	if not found then
	    moned=2;
	end if;

	select despacho into despachos from caratula where car_id=caratul;

	insert into operaciones (op_tipoper,op_directo,op_indirecto,op_consig,op_compbte,op_comptrans,op_nrotalzon,op_nrotaldir,op_deposito,op_iddespach,op_peso,op_bultos,op_moneda,op_importe,op_impdolar,op_tipo_cambio,op_embalaje) select tipoper,directo,indirecto,consig,despachos,transito,val_talon(tipoper,1),val_talon(tipoper,directo),deposito,cual_despachante(cuit_despachante),peso_bruto_bultos::numeric,cant_bultos_declar::integer,moned::int2,monto_fob::numeric(15,2),valor_moncte(moned,fecha_oficializ::date,monto_fob::numeric,0::numeric),monto_fob::numeric/valor_moncte(moned,fecha_oficializ::date,monto_fob::numeric,0::numeric),codigo_embalaje::smallint from caratula where car_id=caratul;
	
	select max(op_id) into operacion from operaciones;

	delete from auxoper where auxo_idoper=operacion;
	insert into auxoper(auxo_idoper,auxo_facturas,auxo_fecha_oficial,auxo_monflet,auxo_impflet,auxo_monseg,auxo_impseg,auxo_plazo_suspens,auxo_medio_transpo) select operacion,referencias::varchar(90),fecha_oficializ,cual_moneda(divisa_flete),monto_flete::numeric,cual_moneda(divisa_seguro),monto_seguro::numeric,plazo_suspensiva::int2,medio_transporte::int2 from caratula where car_id=caratul;

	update items set s_monto_fob_dolar=s_monto_fob_divisa where s_monto_fob_dolar='';
	update items set s_monto_fob_dolar='0',s_monto_fob_divisa='0' where s_monto_fob_dolar='';

	for registro in select * from items where items_despacho=despachos
	    loop

	    select posa_codigo into posafab from posaran where bpchareq(posa_codigo,trim(registro.posic_arancelaria)::varchar);
		if not found then
		    insert into posaran (posa_codigo,posa_nombre) values (trim(registro.posic_arancelaria),'NN');
		end if;

	    select item_id into elitem from item where item_idoper=operacion and item_item=registro.nro_item::int2;
		if not found then
		    insert into item (item_idoper,item_item,item_existe_sitem,item_moneda,item_tipprod,item_unimed,item_posa,item_bloqueado,item_paisorigen,item_proced,item_tipitem) values (operacion,registro.nro_item::int2,registro.numero_subitem::int2,moned,1,registro.unidad_declarada::int2,trim(registro.posic_arancelaria),1,registro.pais_origen::int2,registro.pais_procedencia::int2,trim(registro.tipo_item));
		    select max(item_id) into elitem from item;
		end if;


	    select artic_id into articulo from articu where artic_indirecto=indirecto and bpchareq(artic_codigo,trim(registro.codigo_articulo)::varchar);
		if not found then
		    insert into articu (artic_indirecto,artic_codigo,artic_marca,artic_modelo,artic_descrip,artic_present,artic_tiprod,artic_posa,artic_unimed) values (indirecto,trim(registro.codigo_articulo),trim(registro.marca_articulo),trim(registro.modelo_articulo),trim(registro.descrip_articulo),trim(registro.present_articulo),1,trim(registro.posic_arancelaria),registro.unidad_declarada::int2);
		    select artic_id into articulo from articu where artic_indirecto=indirecto and bpchareq(artic_codigo,trim(registro.codigo_articulo));
		end if;

	    insert into subitem (sitem_iditem,sitem_idoper,sitem_codigo,sitem_artic,sitem_canting,sitem_importe,sitem_imp_dolar,sitem_tipemb,sitem_deposito,sitem_directo,sitem_indirecto,sitem_compbte) values (elitem,operacion,registro.numero_subitem::int2,articulo,registro.s_cant_declarada::numeric,registro.s_monto_fob_divisa::numeric,registro.s_monto_fob_dolar::numeric,0::int2,deposito,directo,indirecto,despachos);

	    end loop;

	update operaciones set op_impdolar=opimpdolar(operacion) where op_id=operacion;



	retval:='t';

    RETURN retval;
    END;$_$;


ALTER FUNCTION public.importo_ingreso(integer, integer, integer, integer, integer, smallint) OWNER TO estlm;

--
-- Name: imprim_fact_deta(character varying, integer, smallint, smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION imprim_fact_deta(character varying, integer, smallint, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	impresora	ALIAS FOR $1; 
	reporte		ALIAS FOR $2; 
	mes		ALIAS FOR $3; 
	anio		ALIAS FOR $4; 
	ret 		boolean;
	operacion	int4;
	registro 	RECORD;
    BEGIN
    ret:='f';

    for registro in select cfc_usuario as x, count(*) as y
    	    from confactur where cfc_anio=anio and cfc_mes=mes and cfc_ptov=2 group by cfc_usuario order by 1
		loop
		    operacion:=genimpre(impresora,reporte,registro.x);
		    ret:='t';
		end loop; 
return ret;
	
    END;$_$;


ALTER FUNCTION public.imprim_fact_deta(character varying, integer, smallint, smallint) OWNER TO estlm;

--
-- Name: imprim_fact_deta_alm(character varying, integer, smallint, smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION imprim_fact_deta_alm(character varying, integer, smallint, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	impresora	ALIAS FOR $1; 
	reporte		ALIAS FOR $2; 
	mes		ALIAS FOR $3; 
	anio		ALIAS FOR $4; 
	ret 		boolean;
	operacion	int4;
	registro 	RECORD;
    BEGIN
    ret:='f';

    for registro in select cfc_usuario as x, count(*) as y
    	    from confactur where cfc_anio=anio and cfc_mes=mes and cfc_ptov=2 and cfc_idart in (5,7,11) group by 1 order by 1
		loop
		    operacion:=genimpre(impresora,reporte,registro.x);
		    ret:='t';
		end loop; 
return ret;
	
    END;$_$;


ALTER FUNCTION public.imprim_fact_deta_alm(character varying, integer, smallint, smallint) OWNER TO estlm;

--
-- Name: imprim_fact_deta_almxc(character varying, integer, smallint, smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION imprim_fact_deta_almxc(character varying, integer, smallint, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	impresora	ALIAS FOR $1; 
	reporte		ALIAS FOR $2; 
	mes		ALIAS FOR $3; 
	anio		ALIAS FOR $4; 
	ret 		boolean;
	operacion	int4;
	registro 	RECORD;
    BEGIN
    ret:='f';

    for registro in select cfc_usuario as x, count(*) as y
    	    from confactur where cfc_mes=mes and cfc_anio=anio and cfc_ptov=2 and cfc_idart in (5,7,11) and cfc_usuario in (258,284,325,377,520,522,568,893,983,1004,1365,1757,1823,4069,4116,4117,4344,4862,5140) group by cfc_usuario
		loop
		    operacion:=genimpre(impresora,reporte,registro.x);
		    ret:='t';
		end loop; 
return ret;
	
    END;$_$;


ALTER FUNCTION public.imprim_fact_deta_almxc(character varying, integer, smallint, smallint) OWNER TO estlm;

--
-- Name: imprim_fact_detaxc(character varying, integer, integer, smallint, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION imprim_fact_detaxc(character varying, integer, integer, smallint, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	impresora	ALIAS FOR $1; 
	reporte		ALIAS FOR $2; 
	mes		ALIAS FOR $3; 
	anio		ALIAS FOR $4; 
	usuario		ALIAS FOR $5; 
	ret 		boolean;
	operacion	int4;
	registro 	RECORD;
    BEGIN
    ret:='f';

    for registro in select cfc_usuario as x
    	    from confactur where cfc_mes=11 and cfc_anio=2004 and cfc_ptov=2 and cfc_usuario=usuario group by cfc_usuario
		loop
		    operacion:=genimpre('lexmark',501,registro.x);
		    ret:='t';
		end loop; 
return ret;
	
    END;$_$;


ALTER FUNCTION public.imprim_fact_detaxc(character varying, integer, integer, smallint, integer) OWNER TO estlm;

--
-- Name: imprim_fact_detaxc(character varying, integer, smallint, smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION imprim_fact_detaxc(character varying, integer, smallint, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	impresora	ALIAS FOR $1; 
	reporte		ALIAS FOR $2; 
	mes		ALIAS FOR $3; 
	anio		ALIAS FOR $4; 
	ret 		boolean;
	operacion	int4;
	registro 	RECORD;
    BEGIN
    ret:='f';

    for registro in select cfc_usuario as x, count(*) as y
    	    from confactur where cfc_mes=mes and cfc_anio=anio and cfc_ptov=2 and cfc_usuario in (258,284,325,377,520,522,568,893,983,1004,1365,1757,1823,4069,4116,4117,4344,4862,5140)  group by cfc_usuario
		loop
		    operacion:=genimpre(impresora,reporte,registro.x);
		    ret:='t';
		end loop; 
return ret;
	
    END;$_$;


ALTER FUNCTION public.imprim_fact_detaxc(character varying, integer, smallint, smallint) OWNER TO estlm;

--
-- Name: imprim_fact_detaxc(character varying, integer, smallint, smallint, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION imprim_fact_detaxc(character varying, integer, smallint, smallint, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	impresora	ALIAS FOR $1; 
	reporte		ALIAS FOR $2; 
	mes		ALIAS FOR $3; 
	anio		ALIAS FOR $4; 
	usuario		ALIAS FOR $5; 
	ret 		boolean;
	operacion	int4;
	registro 	RECORD;
    BEGIN
    ret:='f';

    for registro in select cfc_usuario as x, count(*) as y
    	    from confactur where cfc_anio=anio and cfc_mes=mes and cfc_ptov=2 and cfc_usuario=usuario group by cfc_usuario
		loop
		    operacion:=genimpre(impresora,reporte,registro.x);
		    ret:='t';
		end loop; 
return ret;
	
    END;$_$;


ALTER FUNCTION public.imprim_fact_detaxc(character varying, integer, smallint, smallint, integer) OWNER TO estlm;

--
-- Name: indiconcontr(integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION indiconcontr(integer, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
locador		 alias for $1;
locatario	 alias for $2;
temporal	 integer;
ret 		 boolean;
begin
ret:='f';

select contr_locatario into temporal from contratos where contr_locador=locador and contr_locatario =locatario and contr_estado=1 and contr_idsubt in (7,8,9) limit 1;

if found then
    ret:='t';
end if;

return ret;

end;$_$;


ALTER FUNCTION public.indiconcontr(integer, integer) OWNER TO estlm;

--
-- Name: llevastock(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION llevastock(integer) RETURNS boolean
    LANGUAGE sql
    AS $_$select true from varambi where vari_codemp= $1 and vari_codigo='STOCK' and vari_valor='1' limit 1;$_$;


ALTER FUNCTION public.llevastock(integer) OWNER TO estlm;

--
-- Name: marcasitem(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION marcasitem(integer) RETURNS character
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	sitem		ALIAS FOR $1;  
	articulo	int4;
	retval		varchar;
    BEGIN

    SELECT  sitem_artic INTO articulo
	    FROM subitem   WHERE int4eq(sitem_id,sitem);

    SELECT  artic_marca INTO retval
	    FROM articu   WHERE int4eq(artic_id,articulo);

    RETURN retval;
    END;$_$;


ALTER FUNCTION public.marcasitem(integer) OWNER TO estlm;

--
-- Name: marcontdeopv(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION marcontdeopv(integer) RETURNS character
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	idopv		ALIAS FOR $1;  
	codmarcont	int4;
	indi		int4;
	regi		RECORD;
	trans		varchar;
	trans1		varchar;
	retval		varchar;
    BEGIN

    indi=1;
    for regi in select * from contene where cont_idopv= $1 
    loop
    select marc_descrip into trans from marcont where marc_codigo=regi.cont_marcont;
	trans1:= trans||'-'||regi.cont_nrocont;

	if indi>1 then
		retval:= trans1||' / '||trans||'-'||regi.cont_nrocont;
	    else
		retval:= trans1;
	end if;
	indi:=indi+1;
    end loop;
    
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.marcontdeopv(integer) OWNER TO estlm;

--
-- Name: meapeso(smallint, date); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION meapeso(smallint, date) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	moneda		ALIAS FOR $1; 
	fecha		ALIAS FOR $2; 
	cotipes		numeric;
	retval 		numeric;
    BEGIN

    select cotpeso(fecha) into cotipes;
    select (cot_cotiz * cotipes) into retval from cotiza WHERE int2eq(moneda,cot_moneda) and  date_le(cot_fecha,fecha) order by cot_fecha desc limit 1;

    if retval is NULL then
	    retval:=0;
    end if;
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.meapeso(smallint, date) OWNER TO estlm;

--
-- Name: mesastoh(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION mesastoh(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select ash_mes from astoh where ash_id= $1;$_$;


ALTER FUNCTION public.mesastoh(integer) OWNER TO estlm;

--
-- Name: migracion(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION migracion() RETURNS integer
    LANGUAGE plpgsql
    AS $$
declare
regi 		RECORD;
ret		int4;
operid		int4;
itemid		int4;
rowintotal 	int4;
ruflo 	int4;
ruflo1 	int4;
ruflo2 	int4;
begin
ret:=0;

for regi in select * from intotal order by int_directo,int_indirecto,int_tipoper,int_numero,int_articod,int_lotenum
	loop
	rowintotal:=regi.int_id;
	operid:=cidop(regi.int_directo::int4,regi.int_indirecto::int4,regi.int_tipoper::int4,	regi.int_numero::int4);	

	if(regi.int_id<270554) then
		ruflo1:=regi.int_idret::int4;
	    else
		ruflo1:=cidart(regi.int_indirecto::int4,regi.int_articod::varchar);
	end if;


	
	if regi.int_lotenum::int2 < 1  then
		insert into item (
    		item_idoper,item_existe_sitem,item_moneda,item_tipprod,item_unimed) 
		values	(operid,0,regi.int_moneda::int2,trim(regi.int_tiprod)::int4,regi.int_unimed::int2);
		select max(item_id) into ruflo from item; 
	end if;
	

	insert into subitem (sitem_iditem,sitem_idoper,sitem_codigo,
			sitem_artic,sitem_canting,sitem_cantret,
			sitem_cantcomp,sitem_importe,sitem_tipemb,
			sitem_deposito,sitem_directo,sitem_indirecto,sitem_compbte)
		values
(ruflo,operid,regi.int_lotenum,ruflo1,	
    regi.int_canting::numeric,regi.int_cantret::numeric,regi.int_cantcomp::numeric,
    regi.int_valori::numeric,regi.int_embalaje::int2,regi.int_deposito::int2,
    regi.int_directo::int4,regi.int_indirecto::int4,regi.int_compbte);

    end loop; 
return ret;
end;$$;


ALTER FUNCTION public.migracion() OWNER TO estlm;

--
-- Name: migracion1(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION migracion1() RETURNS integer
    LANGUAGE plpgsql
    AS $$
declare
regi 		RECORD;
ret		int4;
operid		int4;
itemid		int4;
rowintotal 	int4;
ruflo 	int4;
ruflo2 	int4;
begin
ret:=0;

for regi in select distinct on (int_directo,int_indirecto,int_tipoper,int_numero) * from intotal
	loop
	insert into operaciones (op_tipoper,op_directo,op_indirecto,op_compbte,op_nrotalzon,op_nrotaldir,op_estado,op_consig,op_fechain,op_deposito,op_conocim,op_peso,op_bultos,op_moneda,op_importe,op_impdolar,op_tipo_cambio,op_embalaje) 
	values
	(regi.int_tipoper::int4,regi.int_directo::int4,regi.int_indirecto::int4,regi.int_compbte::varchar,val_talon(regi.int_tipoper::int4,1),regi.int_numero::int4,regi.int_estado::int2,regi.int_consig::int4,regi.int_fecha::date,regi.int_deposito::int2,regi.int_conocim::varchar,regi.int_peso::numeric,regi.int_bultos::int4,regi.int_moneda::int2,regi.int_fobt::numeric,regi.int_valcte::numeric,regi.int_tipcbo::numeric,regi.int_embalaje::int2);
--	ret:=ret+1;		
        end loop; 

return ret;
end;$$;


ALTER FUNCTION public.migracion1() OWNER TO estlm;

--
-- Name: migracion2(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION migracion2() RETURNS integer
    LANGUAGE plpgsql
    AS $$
declare
regi 		RECORD;
ret		int4;
operid		int4;
itemid		int4;
rowintotal 	int4;
ruflo 	int4;
ruflo2 	int4;
begin
ret:=0;


for regi in select distinct on (int_articod,int_directo,int_indirecto) * from intotal
	loop
	select artic_id into ruflo from articu where artic_indirecto=regi.int_indirecto::int4 and artic_codigo=regi.int_articod::varchar;

	if not found then
	insert into articu (artic_indirecto,artic_codigo,artic_descrip,artic_tiprod,artic_unimed) 
	values
	(regi.int_indirecto::int4,regi.int_articod::varchar,regi.int_artidesc::varchar,trim(regi.int_tiprod)::int4,regi.int_unimed::int2);
ret:=ret+1;
	end if;
        end loop; 

return ret;
end;$$;


ALTER FUNCTION public.migracion2() OWNER TO estlm;

--
-- Name: migracion_e(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION migracion_e() RETURNS integer
    LANGUAGE plpgsql
    AS $$
declare
regi 		RECORD;
ret		int4;
operid		int4;
artic_id		int4;
rowintotal 	int4;
ruflo 	int4;
ruflo2 	int4;
begin
ret:=0;
for regi in select distinct on (egt_directo,egt_indirecto,egt_tipoper,egt_numero) * from egretot
	loop
	insert into operaciones (op_tipoper,op_directo,op_indirecto,op_compbte,
	op_nrotalzon,op_nrotaldir,op_estado,op_consig,op_fechain,
	op_comptrans,op_peso,op_bultos,op_moneda,op_importe,
	op_impdolar,op_embalaje) 
	values
	(regi.egt_tipoper::int4,regi.egt_directo::int4,regi.egt_indirecto::int4,
	regi.egt_compbte,val_talon(regi.egt_tipoper::int4,1),regi.egt_numero::int4,
	101::int2,regi.egt_consig::int4,regi.egt_fecha::date,
	regi.egt_combteeg::char,regi.egt_peso::numeric,regi.egt_bultos::int4,
	regi.egt_moneda::int2,regi.egt_fobt::numeric,regi.egt_valcte::numeric,
	regi.egt_embalaje::int2	);
	ret:=ret+1;		
        end loop; 

for regi in select * from egretot 
	loop
	operid:=cidop(regi.egt_directo::int4,regi.egt_indirecto::int4,regi.egt_tipoper::int4,	regi.egt_numero::int4);	
	artic_id:=cidart(regi.egt_indirecto::int4,regi.egt_articod::varchar);
	
	insert into retiros (ret_idopera,ret_idsitem,ret_item,ret_sitem,ret_cantidad)
		values	(operid,cidsitem(operid,regi.egt_lotenum::int2,regi.egt_compbte::varchar,artic_id),1::int2,0::int2,regi.egt_cantret::numeric);

--	ret:=ret+1;		

    end loop; 

return ret;
end;$$;


ALTER FUNCTION public.migracion_e() OWNER TO estlm;

--
-- Name: migracion_e1(integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION migracion_e1(integer, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
desde	 	alias for $1;
hasta		alias for $2;
regi 		RECORD;
ret		int4;
operid		int4;
operidi		int4;
artic_id		int4;
rowintotal 	int4;
ruflo 	int4;
ruflo2 	int4;
begin
ret:=0;

for regi in select * from egretot where egt_id between desde and hasta
    loop
    operid:=cidop(regi.egt_directo::int4,regi.egt_indirecto::int4,regi.egt_tipoper::int4,regi.egt_numero::int4);
    operidi:=cidop(regi.egt_directo::int4,regi.egt_indirecto::int4,regi.egt_tipoperin::int4,regi.egt_numeroin::int4);
    artic_id:=cidart(regi.egt_indirecto::int4,trim(regi.egt_articod)::varchar);
    ruflo2=cidsitem(operidi::int4,regi.egt_lotenum::int2,trim(regi.egt_compbte)::varchar,artic_id::int4);
    if ruflo2 is null then ruflo2=0; end if;
	insert into retiros (ret_idopera,ret_idsitem,ret_item,ret_sitem,ret_cantidad)
		values	(operid,ruflo2,1::int2,0::int2,regi.egt_cantret::numeric);

ret:=1;
    end loop; 


return ret;
end;$_$;


ALTER FUNCTION public.migracion_e1(integer, integer) OWNER TO estlm;

--
-- Name: migracion_ep(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION migracion_ep() RETURNS integer
    LANGUAGE plpgsql
    AS $$
declare
regi 		RECORD;
ret		int4;
operid		int4;
artic_id		int4;
rowintotal 	int4;
ruflo 	int4;
ruflo2 	int4;
begin
ret:=0;
for regi in select distinct on (trim(egt_directo),trim(egt_indirecto),trim(egt_tipoper),trim(egt_numero)) * from egretot where egt_id>6499
	loop
	insert into operaciones (op_tipoper,op_directo,op_indirecto,op_compbte,
	op_nrotalzon,op_nrotaldir,op_estado,op_consig,op_fechain,
	op_comptrans,op_peso,op_bultos,op_moneda,op_importe,
	op_impdolar,op_embalaje) 
	values
	(trim(regi.egt_tipoper)::int4,trim(regi.egt_directo)::int4,trim(regi.egt_indirecto)::int4,
	trim(regi.egt_compbte)::varchar,val_talon(trim(regi.egt_tipoper)::int4,1),trim(regi.egt_numero)::int4,
	trim(regi.egt_esta)::int2,trim(regi.egt_consig)::int4,trim(regi.egt_fecha)::date,
	trim(regi.egt_combteeg)::varchar,trim(regi.egt_peso)::numeric,trim(regi.egt_bultos)::int4,
	trim(regi.egt_moneda)::int2,trim(regi.egt_fobt)::numeric,trim(regi.egt_valcte)::numeric,
	trim(regi.egt_embalaje)::int2	);
	ret:=ret+1;		
        end loop; 

return ret;
end;$$;


ALTER FUNCTION public.migracion_ep() OWNER TO estlm;

--
-- Name: migracion_ep1(); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION migracion_ep1() RETURNS integer
    LANGUAGE plpgsql
    AS $$
declare
regi 		RECORD;
ret		int4;
operid		int4;
operidi		int4;
artic_id		int4;
rowintotal 	int4;
ruflo 	int4;
ruflo2 	int4;
begin
ret:=0;

for regi in select * from egretot 
    loop
    operid:=cidop(regi.egt_directo::int4,regi.egt_indirecto::int4,regi.egt_tipoper::int4,regi.egt_numero::int4);

    operidi:=cidop(regi.egt_directo::int4,regi.egt_indirecto::int4,regi.egt_tipoperin::int4,regi.egt_numeroin::int4);
    artic_id:=cidart(regi.egt_indirecto::int4,trim(regi.egt_articod)::varchar);
    ruflo2=cidsitem(operidi::int4,regi.egt_lotenum::int2,trim(regi.egt_compbte)::varchar,artic_id::int4);
    if ruflo2 is null then ruflo2=0; end if;
	
	insert into retiros (ret_idopera,ret_idsitem,ret_item,ret_sitem,ret_cantidad)
		values	(operid,ruflo2,1::int2,0::int2,regi.egt_cantret::numeric);
    end loop; 

return ret;
end;$$;


ALTER FUNCTION public.migracion_ep1() OWNER TO estlm;

--
-- Name: mismo_consig(integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION mismo_consig(integer, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	op_ing		ALIAS FOR $1; -- id  Op.ING.
	op_egr		ALIAS FOR $2; -- id  Op.EGR.
	retval 		boolean;
    BEGIN
    retval:='f';
    if  int4eq((select op_consig from operaciones where op_id=op_ing),(select op_consig from operaciones where op_id=op_egr)) 
        then retval:='t';
    end if;		

    RETURN retval;
    END;$_$;


ALTER FUNCTION public.mismo_consig(integer, integer) OWNER TO estlm;

--
-- Name: modoalm(smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION modoalm(smallint) RETURNS character
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	modo		ALIAS FOR $1; 
	retval 		varchar;
    BEGIN

    if int2eq(modo,1::int2) then retval:='VOLUMEN';   end if;
    if int2eq(modo,2::int2) then retval:='CANTIDAD';   end if;
    if int2eq(modo,3::int2) then retval:='PESO';   end if;



    RETURN retval;
    END;$_$;


ALTER FUNCTION public.modoalm(smallint) OWNER TO estlm;

--
-- Name: moncteopera(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION moncteopera(integer) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
declare
operacion	alias for $1; 	--operacion
registro	RECORD;
ret 		numeric;
begin


for registro in select 
    op_impdolar as impdolar, 
    op_importe as importe 
     from operaciones where op_id=operacion
	loop

	if(registro.impdolar is null or numeric_eq(registro.impdolar,0::numeric) or registro.importe is null or numeric_eq(registro.importe,0::numeric)) then   
	    registro.importe=1; registro.impdolar=1;
	end if;

	ret:=registro.impdolar / registro.importe;

	end loop; 

return ret;
END;$_$;


ALTER FUNCTION public.moncteopera(integer) OWNER TO estlm;

--
-- Name: monctesitem(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION monctesitem(integer) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
declare
sitem		alias for $1; 	--Id del Subitem
registro	RECORD;
operacion	int4;
ret 		numeric;
begin

select sitem_idoper into operacion from subitem where sitem_id=sitem;

for registro in select 
    op_impdolar as impdolar, 
    op_importe as importe 
     from operaciones where op_id=operacion
	loop

	if(registro.impdolar is null or numeric_eq(registro.impdolar,0::numeric) or registro.importe is null or numeric_eq(registro.importe,0::numeric)) then   
	    registro.importe=1; registro.impdolar=1;
	end if;

	ret:=registro.impdolar / registro.importe;

	end loop; 

return ret;
END;$_$;


ALTER FUNCTION public.monctesitem(integer) OWNER TO estlm;

--
-- Name: monedacbl(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION monedacbl(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select cbl_moneda from ctacble where cbl_id= $1 ;$_$;


ALTER FUNCTION public.monedacbl(integer) OWNER TO estlm;

--
-- Name: monedeempre(integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION monedeempre(integer, integer) RETURNS boolean
    LANGUAGE sql
    AS $_$select true from monex a, astoctas b where a.mne_id= $2 and a.mne_idastoc=b.astc_id and b.astc_codemp= $1 ;$_$;


ALTER FUNCTION public.monedeempre(integer, integer) OWNER TO estlm;

--
-- Name: nomartic(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION nomartic(integer) RETURNS character
    LANGUAGE sql
    AS $_$select art_nombre from articvta where art_id= $1 ;$_$;


ALTER FUNCTION public.nomartic(integer) OWNER TO estlm;

--
-- Name: nomcble(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION nomcble(integer) RETURNS character
    LANGUAGE sql
    AS $_$select cbl_nombre from ctacble where cbl_id= $1 ;$_$;


ALTER FUNCTION public.nomcble(integer) OWNER TO estlm;

--
-- Name: nomcli(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION nomcli(integer) RETURNS character
    LANGUAGE sql
    AS $_$select cli_nombre from clientes where cli_id= $1 ;$_$;


ALTER FUNCTION public.nomcli(integer) OWNER TO estlm;

--
-- Name: nomcomp(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION nomcomp(integer) RETURNS character
    LANGUAGE sql
    AS $_$select comp_nombre from comprob where comp_id= $1 ;$_$;


ALTER FUNCTION public.nomcomp(integer) OWNER TO estlm;

--
-- Name: nomconpag(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION nomconpag(integer) RETURNS character
    LANGUAGE sql
    AS $_$select cdp_nombre from conpag where cdp_codigo= $1 ;$_$;


ALTER FUNCTION public.nomconpag(integer) OWNER TO estlm;

--
-- Name: nomctes(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION nomctes(integer) RETURNS character
    LANGUAGE sql
    AS $_$select cte_nombre from ctes where cte_id= $1 ;$_$;


ALTER FUNCTION public.nomctes(integer) OWNER TO estlm;

--
-- Name: nomemp(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION nomemp(integer) RETURNS character
    LANGUAGE sql
    AS $_$select emp_nombre from empresa where emp_codigo= $1 ;$_$;


ALTER FUNCTION public.nomemp(integer) OWNER TO estlm;

--
-- Name: nomestlm(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION nomestlm(integer) RETURNS character
    LANGUAGE sql
    AS $_$select zon_nombre from zona where zon_codigo= $1 ;$_$;


ALTER FUNCTION public.nomestlm(integer) OWNER TO estlm;

--
-- Name: nomiva(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION nomiva(integer) RETURNS character
    LANGUAGE sql
    AS $_$select iva_nombre from coniva where iva_codigo= $1 ;$_$;


ALTER FUNCTION public.nomiva(integer) OWNER TO estlm;

--
-- Name: nomivacli(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION nomivacli(integer) RETURNS character
    LANGUAGE sql
    AS $_$select iva_nombre from coniva,clientes where iva_codigo=cli_coniva and cli_id= $1 ;$_$;


ALTER FUNCTION public.nomivacli(integer) OWNER TO estlm;

--
-- Name: nommoneda(smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION nommoneda(smallint) RETURNS character
    LANGUAGE sql
    AS $_$select mon_nombre from moneda where mon_codigo= $1 ;$_$;


ALTER FUNCTION public.nommoneda(smallint) OWNER TO estlm;

--
-- Name: nomopera(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION nomopera(integer) RETURNS character
    LANGUAGE sql
    AS $_$select operad_nombre from operadores where operad_id= $1 ;$_$;


ALTER FUNCTION public.nomopera(integer) OWNER TO estlm;

--
-- Name: nompais(smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION nompais(smallint) RETURNS character
    LANGUAGE sql
    AS $_$select pai_nombre from pais where pai_codigo= $1 ;$_$;


ALTER FUNCTION public.nompais(smallint) OWNER TO estlm;

--
-- Name: nomprov(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION nomprov(integer) RETURNS character
    LANGUAGE sql
    AS $_$select pro_nombre from provin where pro_codigo= $1 ;$_$;


ALTER FUNCTION public.nomprov(integer) OWNER TO estlm;

--
-- Name: nomprove(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION nomprove(integer) RETURNS character
    LANGUAGE sql
    AS $_$select prov_nombre from prove where prov_id= $1 ;$_$;


ALTER FUNCTION public.nomprove(integer) OWNER TO estlm;

--
-- Name: nomptv(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION nomptv(integer) RETURNS character
    LANGUAGE sql
    AS $_$select ptv_nombre from ptovta where ptv_id= $1 ;$_$;


ALTER FUNCTION public.nomptv(integer) OWNER TO estlm;

--
-- Name: nomtipcta(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION nomtipcta(integer) RETURNS character
    LANGUAGE sql
    AS $_$select tct_nombre from tipcta where tct_codigo = $1;$_$;


ALTER FUNCTION public.nomtipcta(integer) OWNER TO estlm;

--
-- Name: nomunifsitem(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION nomunifsitem(integer) RETURNS character
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	sitem		ALIAS FOR $1;  
	deposito	int2;
	retval		varchar;
    BEGIN

    SELECT  sitem_deposito INTO deposito
	    FROM subitem   WHERE int4eq(sitem_id,sitem);

    SELECT  unif_nombre INTO retval
	    FROM unifun   WHERE int2eq(unif_codigo,deposito);

    RETURN retval;
    END;$_$;


ALTER FUNCTION public.nomunifsitem(integer) OWNER TO estlm;

--
-- Name: nomvend(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION nomvend(integer) RETURNS character
    LANGUAGE sql
    AS $_$select ven_nombre from vendedor where ven_id= $1 ;$_$;


ALTER FUNCTION public.nomvend(integer) OWNER TO estlm;

--
-- Name: nroastc(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION nroastc(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select astc_numero from astoctas where astc_id= $1 ;$_$;


ALTER FUNCTION public.nroastc(integer) OWNER TO estlm;

--
-- Name: numash(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION numash(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select ash_numero from astoh where ash_id= $1;$_$;


ALTER FUNCTION public.numash(integer) OWNER TO estlm;

--
-- Name: numero_letras(numeric); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION numero_letras(numeric) RETURNS text
    LANGUAGE plpgsql
    AS $_$
DECLARE
     numero	ALIAS FOR $1;
     lnEntero INTEGER;
     lcRetorno TEXT = '';
     lnTerna INTEGER = 1;
     lcMiles TEXT;
     lcCadena TEXT;
     maxi TEXT;
     lnUnidades INTEGER;
     lnDecenas INTEGER;
     lnCentenas INTEGER;
     lnFraccion INTEGER;
     lnSw INTEGER;
BEGIN
     lnEntero := FLOOR(numero)::INTEGER;--Obtenemos la parte Entera
     lnFraccion := FLOOR(((numero - lnEntero) * 100))::INTEGER;--Obtenemos la Fraccion del Monto
    -- lcRetorno := '';
    -- lnTerna := 1;
     IF lnEntero > 0 THEN
     lnSw := LENGTH(lnEntero::varchar);
     WHILE lnTerna <= lnSw LOOP
        -- Recorro terna por terna
        lcCadena = '';
        lnUnidades = lnEntero % 10;
        lnEntero = CAST(lnEntero/10 AS INTEGER);
        lnDecenas = lnEntero % 10;
        lnEntero = CAST(lnEntero/10 AS INTEGER);
        lnCentenas = lnEntero % 10;
        lnEntero = CAST(lnEntero/10 AS INTEGER);
       SELECT
         CASE /* UNIDADES */
           WHEN lnUnidades = 1 AND lnTerna = 1 THEN 'UNO ' || lcCadena
           WHEN lnUnidades = 1 AND lnTerna <> 1 THEN 'UN ' || lcCadena
           WHEN lnUnidades = 2 THEN 'DOS ' || lcCadena
           WHEN lnUnidades = 3 THEN 'TRES ' || lcCadena
           WHEN lnUnidades = 4 THEN 'CUATRO ' || lcCadena
           WHEN lnUnidades = 5 THEN 'CINCO ' || lcCadena
           WHEN lnUnidades = 6 THEN 'SEIS ' || lcCadena
           WHEN lnUnidades = 7 THEN 'SIETE ' || lcCadena
           WHEN lnUnidades = 8 THEN 'OCHO ' || lcCadena
           WHEN lnUnidades = 9 THEN 'NUEVE ' || lcCadena
           ELSE lcCadena
          END INTO lcCadena;
          /* UNIDADES */
    -- Analizo las decenas
    SELECT
    CASE /* DECENAS */
      WHEN lnDecenas = 1 THEN
        CASE lnUnidades
          WHEN 0 THEN 'DIEZ '
          WHEN 1 THEN 'ONCE '
          WHEN 2 THEN 'DOCE '
          WHEN 3 THEN 'TRECE '
          WHEN 4 THEN 'CATORCE '
          WHEN 5 THEN 'QUINCE '
          ELSE 'DIECI' || lcCadena
        END
      WHEN lnDecenas = 2 AND lnUnidades = 0 THEN 'VEINTE ' || lcCadena
      WHEN lnDecenas = 2 AND lnUnidades <> 0 THEN 'VEINTI' || lcCadena
      WHEN lnDecenas = 3 AND lnUnidades = 0 THEN 'TREINTA ' || lcCadena
      WHEN lnDecenas = 3 AND lnUnidades <> 0 THEN 'TREINTA Y ' || lcCadena
      WHEN lnDecenas = 4 AND lnUnidades = 0 THEN 'CUARENTA ' || lcCadena
      WHEN lnDecenas = 4 AND lnUnidades <> 0 THEN 'CUARENTA Y ' || lcCadena
      WHEN lnDecenas = 5 AND lnUnidades = 0 THEN 'CINCUENTA ' || lcCadena
      WHEN lnDecenas = 5 AND lnUnidades <> 0 THEN 'CINCUENTA Y ' || lcCadena
      WHEN lnDecenas = 6 AND lnUnidades = 0 THEN 'SESENTA ' || lcCadena
      WHEN lnDecenas = 6 AND lnUnidades <> 0 THEN 'SESENTA Y ' || lcCadena
      WHEN lnDecenas = 7 AND lnUnidades = 0 THEN 'SETENTA ' || lcCadena
      WHEN lnDecenas = 7 AND lnUnidades <> 0 THEN 'SETENTA Y ' || lcCadena
      WHEN lnDecenas = 8 AND lnUnidades = 0 THEN 'OCHENTA ' || lcCadena
      WHEN lnDecenas = 8 AND lnUnidades <> 0 THEN 'OCHENTA Y ' || lcCadena
      WHEN lnDecenas = 9 AND lnUnidades = 0 THEN 'NOVENTA ' || lcCadena
      WHEN lnDecenas = 9 AND lnUnidades <> 0 THEN 'NOVENTA Y ' || lcCadena
      ELSE lcCadena
    END INTO lcCadena; /* DECENAS */
    -- Analizo las centenas
    SELECT
    CASE /* CENTENAS */
      WHEN lnCentenas = 1 AND lnUnidades = 0 AND lnDecenas = 0 THEN 'CIEN ' || lcCadena
      WHEN lnCentenas = 1 AND NOT(lnUnidades = 0 AND lnDecenas = 0) THEN 'CIENTO ' || lcCadena
      WHEN lnCentenas = 2 THEN 'DOSCIENTOS ' || lcCadena
      WHEN lnCentenas = 3 THEN 'TRESCIENTOS ' || lcCadena
      WHEN lnCentenas = 4 THEN 'CUATROCIENTOS ' || lcCadena
      WHEN lnCentenas = 5 THEN 'QUINIENTOS ' || lcCadena
      WHEN lnCentenas = 6 THEN 'SEISCIENTOS ' || lcCadena
      WHEN lnCentenas = 7 THEN 'SETECIENTOS ' || lcCadena
      WHEN lnCentenas = 8 THEN 'OCHOCIENTOS ' || lcCadena
      WHEN lnCentenas = 9 THEN 'NOVECIENTOS ' || lcCadena
      ELSE lcCadena
    END INTO lcCadena;/* CENTENAS */
    -- Analizo la terna
    SELECT
    CASE /* TERNA */
      WHEN lnTerna = 1 THEN lcCadena
      WHEN lnTerna = 2 AND (lnUnidades + lnDecenas + lnCentenas <> 0) THEN lcCadena || ' MIL '
      WHEN lnTerna = 3 AND (lnUnidades + lnDecenas + lnCentenas <> 0) AND
        lnUnidades = 1 AND lnDecenas = 0 AND lnCentenas = 0 THEN lcCadena || ' MILLON '
      WHEN lnTerna = 3 AND (lnUnidades + lnDecenas + lnCentenas <> 0) AND
        NOT (lnUnidades = 1 AND lnDecenas = 0 AND lnCentenas = 0) THEN lcCadena || ' MILLONES '
      WHEN lnTerna = 4 AND (lnUnidades + lnDecenas + lnCentenas <> 0) THEN lcCadena || ' MIL MILLONES '
      ELSE ''
    END INTO lcCadena;/* TERNA */
 
    --Retornamos los Valores Obtenidos
    lcRetorno = lcCadena  || lcRetorno;
    lnTerna = lnTerna + 1;
    END LOOP;
  END IF;
  IF lnTerna = 1 THEN
    lcRetorno := 'CERO';
  END IF;

  
  IF lnFraccion!= 0  THEN
	lcRetorno :=' PESOS ' || RTRIM(lcRetorno) || ' CON ' || LTRIM(lnFraccion::varchar) || '/100 CENTAVOS ------';
    else
	lcRetorno :=' PESOS ' || RTRIM(lcRetorno) || ' ------';
  END IF;

RETURN lcRetorno;
end;$_$;


ALTER FUNCTION public.numero_letras(numeric) OWNER TO zona;

--
-- Name: numtalon(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION numtalon(integer, integer, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	ptovta		ALIAS FOR $1; 
	comproba	ALIAS FOR $2; 
	modo		ALIAS FOR $3; -- 1:graba  2:consulta
	otro 		integer;
	talonario	integer;
	retval 		integer;
    BEGIN

    select comp_talon into talonario from
    	 comprob where int4eq(comproba,comp_id);

    select tal_valor into retval from
    	 talon where int4eq(talonario,tal_id);

    if found then
	if int4eq(modo,1) then
	    update talon set tal_valor=tal_valor+1 where int4eq(talonario,tal_id);
	end if;		
    end if;
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.numtalon(integer, integer, integer) OWNER TO estlm;

--
-- Name: numtalonf(integer, integer, date); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION numtalonf(integer, integer, date) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	ptovta		ALIAS FOR $1; 
	comprob		ALIAS FOR $2; 
	fecha		ALIAS FOR $3;
	otro 		integer;
	anter		date;
	retval 		integer;
    BEGIN

    select tal_fecha into anter from
    	 talon where int4eq(ptovta,tal_idptov) and int4eq(comprob,tal_comprob);

    if(date_le(anter,fecha)) then
	select tal_valor into retval from
    	    talon where int4eq(ptovta,tal_idptov) and int4eq(comprob,tal_comprob);
	if not found then
		otro:=0;
		select tal_valor into retval from talon where int4eq(otro,tal_idptov) and int4eq(comprob,tal_comprob);
		update talon set tal_valor=tal_valor+1,tal_fecha=fecha where int4eq(otro,tal_idptov) and int4eq(comprob,tal_comprob);
	     else
		update talon set tal_valor=tal_valor+1,tal_fecha=fecha where int4eq(ptovta,tal_idptov) and int4eq(comprob,tal_comprob);
	end if;
      else
        retval:=-1;
    end if;

    RETURN retval;
    END;$_$;


ALTER FUNCTION public.numtalonf(integer, integer, date) OWNER TO estlm;

--
-- Name: opera_de_dir_ind(integer, integer, integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION opera_de_dir_ind(integer, integer, integer, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	directo		ALIAS FOR $1; 
	indirecto	ALIAS FOR $2; 
	tipoper		ALIAS FOR $3; 
	operacion	ALIAS FOR $4; 
	esta 		int4;
	retval 		boolean;
    BEGIN
    retval:='t';

    select op_id into esta from operaciones where
	op_directo=directo and 
	op_indirecto=indirecto and 
	op_tipoper=tipoper and 
	op_id=operacion ;

    if not found  
        then retval:='f';
    end if;		

    RETURN retval;
    END;$_$;


ALTER FUNCTION public.opera_de_dir_ind(integer, integer, integer, integer) OWNER TO estlm;

--
-- Name: opera_publicada(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION opera_publicada(integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	sitem		ALIAS FOR $1; -- id del SubItem.
	estado		int2;
	operacion	int4;
	retval 		boolean;
    BEGIN

    SELECT  sitem_idoper INTO operacion
	    FROM subitem   WHERE int4eq(sitem_id,sitem);

    SELECT  op_estado INTO estado
	    FROM operaciones   WHERE int4eq(op_id,operacion);

    if int2eq(estado,101::int2) then
    	    retval:='t';
	else
	    retval:='f';
    end if;

    RETURN retval;
    END;$_$;


ALTER FUNCTION public.opera_publicada(integer) OWNER TO estlm;

--
-- Name: orden_tarifa(integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION orden_tarifa(integer, integer) RETURNS smallint
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	usuario		ALIAS FOR $1;  
	articulo	ALIAS FOR $2; 
	orden		int2;
	retval		int2;
    BEGIN

    retval:=1;
    SELECT  max(tari_orden) INTO orden
	    FROM tarifas   WHERE int4eq(tari_idart,articulo) and int4eq(tari_usuario,usuario);

    if int2gt(orden,0::int2) then
	    retval:= orden + 1;
    end if;

    RETURN retval;
    END;$_$;


ALTER FUNCTION public.orden_tarifa(integer, integer) OWNER TO estlm;

--
-- Name: otrconfactur(integer, integer, smallint, smallint, date); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION otrconfactur(integer, integer, smallint, smallint, date) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
usuario		 alias for $1;
articulo	 alias for $2;
anio 		 alias for $3;
mes 		 alias for $4;
fecha		 alias for $5;
ret 		 boolean;
registro	 record;
hay	 	 int4;
importe 	 numeric;
begin

ret:='f';

if(int4eq(usuario,0::int4)) then
	delete from confactur where cfc_idart=articulo and cfc_anio=anio and cfc_mes=mes;
	for registro in select 
	    * from tarifas where tari_idart=articulo
		and estadocontr(tari_idcontr)=1 and date_ge(tari_fhasta,fecha) and date_le(tari_fdesde,fecha)
	loop
	    ret:='t';
--	    insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_estado,cfc_anio,cfc_mes) values (registro.tari_usuario,fecha,articulo::int4,1::numeric,registro.tari_importe::numeric,registro.tari_importe::numeric,1::int2,anio,mes);
	    insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_estado,cfc_anio,cfc_mes) values (registro.tari_usuario,fecha,articulo::int4,1::numeric,valtarico(registro.tari_usuario,articulo,0::numeric,0::int2,fecha::date,registro.tari_idcontr,registro.tari_orden),valtarico(registro.tari_usuario,articulo,0::numeric,0::int2,fecha::date,registro.tari_idcontr,registro.tari_orden),1::int2,anio,mes);
	end loop; 

    else

	delete from confactur where cfc_anio=anio and cfc_mes=mes and cfc_usuario=usuario and cfc_idart=articulo;
--	select tari_importe into importe from tarifas where tari_idart=articulo and tari_usuario=usuario and estadocontr(tari_idcontr)=1 and date_ge(tari_fhasta,fecha) and date_le(tari_fdesde,fecha);
	select valtarico(usuario,articulo,0::numeric,0::int2,fecha::date,tari_idcontr,tari_orden) into importe from tarifas where  estadocontr(tari_idcontr)=1 ;
	insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_estado,cfc_anio,cfc_mes) values (usuario,fecha,articulo::int4,1::numeric,importe::numeric,importe::numeric,1::int2,anio,mes);
end if;

return ret;
end;$_$;


ALTER FUNCTION public.otrconfactur(integer, integer, smallint, smallint, date) OWNER TO estlm;

--
-- Name: pagfac1(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION pagfac1(integer) RETURNS character
    LANGUAGE plpgsql
    AS $_$
declare
idastoh		 alias for $1;
ret 		 varchar;
aux1 		 varchar;
aux2 		 varchar;
codemp	 	 integer;
cuantchq 	 integer;
pago	 	 numeric;
eneft	 	 numeric;
enchq	 	 numeric;
enotr	 	 numeric;
begin
codemp:=1;

    select sum(astc_importe) into pago from astoctas where astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'DEUDXV')::integer) and astc_importe<0 and codcomp(astc_comprob) not in ('CA','CB');

    if pago is not null then
	ret:='Forma de Pago:';
	select sum(astc_importe) into eneft from astoctas where astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'CAJA')::integer) and astc_importe>0;
	select sum(astc_importe) into enchq from astoctas where astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer) and astc_importe>0;
	select sum(astc_importe) into enotr from astoctas where astc_idastoh=idastoh and astc_ctacble not in (idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer),idcbl(codemp,valvaramb(codemp,0,'CAJA')::integer),idcbl(codemp,valvaramb(codemp,0,'DEUDXV')::integer)) and astc_importe>0;
	if eneft is not null then
	    ret:= ret || '  Efectivo                                                      $'|| eneft ;
	  else	    
	    if enchq is not null then
		select count(*) into cuantchq from cheques, astoctas where chq_idastoc=astc_id and astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer) and astc_importe>0;
		if (cuantchq>2) then
		    ret:= ret || '  Cheques segun detalle al dorso                                 $'|| enchq ;
		    end if;
		if (cuantchq<3) then
		    select descchqf(chq_id) into aux1 from cheques, astoctas where chq_idastoc=astc_id and astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer) and astc_importe>0 order by chq_id asc limit 1;
		    ret:= ret ||' Cheque '|| aux1;
		    end if;
	      else	    
		if enotr is not null then
		    select descble(astc_ctacble) into aux2 from astoctas where astc_idastoh=idastoh and astc_ctacble not in (idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer),idcbl(codemp,valvaramb(codemp,0,'CAJA')::integer),idcbl(codemp,valvaramb(codemp,0,'DEUDXV')::integer)) and astc_importe>0;
		    ret:= ret ||'  '|| aux2 ||'                 $'||  enotr;
		    end if;
		end if;
	    end if;
	end if;

if ret is null then 
    ret:='   ';
end if;

return ret;
end;$_$;


ALTER FUNCTION public.pagfac1(integer) OWNER TO estlm;

--
-- Name: pagfac2(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION pagfac2(integer) RETURNS character
    LANGUAGE plpgsql
    AS $_$
declare
idastoh		 alias for $1;
ret 		 varchar;
aux1 		 varchar;
aux2 		 varchar;
codemp	 	 integer;
cuantchq 	 integer;
pago	 	 numeric;
eneft	 	 numeric;
enchq	 	 numeric;
enotr	 	 numeric;
begin
codemp:=1;

    select sum(astc_importe) into pago from astoctas where astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'DEUDXV')::integer) and astc_importe<0 and codcomp(astc_comprob) not in ('CA','CB');

    if pago is not null then
	select sum(astc_importe) into eneft from astoctas where astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'CAJA')::integer) and astc_importe>0;
	select sum(astc_importe) into enchq from astoctas where astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer) and astc_importe>0;
	select sum(astc_importe) into enotr from astoctas where astc_idastoh=idastoh and astc_ctacble not in (idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer),idcbl(codemp,valvaramb(codemp,0,'CAJA')::integer),idcbl(codemp,valvaramb(codemp,0,'DEUDXV')::integer)) and astc_importe>0;
	if eneft is not null then
	    if enchq is not null then
		select descchqf(chq_id) into aux1 from cheques, astoctas where chq_idastoc=astc_id and astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer) and astc_importe>0 limit 1;
		ret:= ret ||' Cheque '|| aux1;
	      else	    
		if enotr is not null then
		    select descble(astc_ctacble) into aux2 from astoctas where astc_idastoh=idastoh and astc_ctacble not in (idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer),idcbl(codemp,valvaramb(codemp,0,'CAJA')::integer),idcbl(codemp,valvaramb(codemp,0,'DEUDXV')::integer)) and astc_importe>0;
		    ret:= ret ||'  '|| aux2 ||'                 $'||  enotr;
		    end if;
		end if;

	  else    

	    if enchq is not null then
		select count(*) into cuantchq from cheques, astoctas where chq_idastoc=astc_id and astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer) and astc_importe>0;
		if int4eq(cuantchq,2) then
		    select descchqf(chq_id) into aux1 from cheques, astoctas where chq_idastoc=astc_id and astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer) and astc_importe>0 order by chq_id desc limit 1;
		    ret:= ret ||' Cheque '|| aux1;
	    	  else	    
		    if enotr is not null then
			select descble(astc_ctacble) into aux2 from astoctas where astc_idastoh=idastoh and astc_ctacble not in (idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer),idcbl(codemp,valvaramb(codemp,0,'CAJA')::integer),idcbl(codemp,valvaramb(codemp,0,'DEUDXV')::integer)) and astc_importe>0;
			ret:= ret ||'  '|| aux2 ||'                 $'||  enotr;
			end if;
		    end if;

	      else	    

		if enotr is not null then
		    select descble(astc_ctacble) into aux2 from astoctas where astc_idastoh=idastoh and astc_ctacble not in (idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer),idcbl(codemp,valvaramb(codemp,0,'CAJA')::integer),idcbl(codemp,valvaramb(codemp,0,'DEUDXV')::integer)) and astc_importe>0;
		    ret:= ret ||'  '|| aux2 ||'                 $'||  enotr;
		    end if;
		end if;
	    end if;
	end if;

if ret is null then 
    ret:='   ';
end if;

return ret;
end;$_$;


ALTER FUNCTION public.pagfac2(integer) OWNER TO estlm;

--
-- Name: patoper(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION patoper(integer) RETURNS character
    LANGUAGE plpgsql
    AS $_$
declare
idoper		 alias for $1;
ret 		 varchar;
auxot		 varchar;
begin

    select opv_pat_tractor into ret from opervehi where opv_idoper = idoper limit 1;

    if ret is null then 
	ret:='A/CARGAR';
    end if;

return ret;
end;$_$;


ALTER FUNCTION public.patoper(integer) OWNER TO estlm;

--
-- Name: precio_unitario(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION precio_unitario(integer) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	item		ALIAS FOR $1; -- id del Sub Item.
	retval 		numeric;
	importe		numeric;
	cantidad	numeric;
    BEGIN
    retval:=0;
    SELECT   sitem_importe,sitem_canting INTO importe,cantidad
	    FROM subitem   WHERE int4eq(sitem_id,item);
    if(importe!=0 and cantidad!=0) then
	retval:= importe / cantidad::numeric;
    end if;	    
	    
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.precio_unitario(integer) OWNER TO estlm;

--
-- Name: precio_unitariod(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION precio_unitariod(integer) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	item		ALIAS FOR $1; -- id del Sub Item.
	retval 		numeric;
	importe		numeric;
	cantidad	numeric;
    BEGIN
    retval:=0;
    SELECT   sitem_imp_dolar,sitem_canting INTO importe,cantidad
	    FROM subitem   WHERE int4eq(sitem_id,item);

    if(importe!=0 and cantidad!=0) then
	retval:= importe / cantidad::numeric;
    end if;	    

    RETURN retval;
    END;$_$;


ALTER FUNCTION public.precio_unitariod(integer) OWNER TO estlm;

--
-- Name: prescble(integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION prescble(integer, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
origen 		 alias for $1;
destino		 alias for $2;
ret 		 boolean;
registro	 record;
auxo		 varchar;
begin
ret:='t';
	for registro in select * from ctacble 
	      where cbl_codemp=destino and cbl_present is null 
	    loop
		select cbl_present into auxo from ctacble where cbl_codemp=origen and bpchareq(cbl_codigo,registro.cbl_codigo);
		if auxo is not null then
		    update ctacble set cbl_present=auxo where cbl_id=registro.cbl_id;
		end if;
	    end loop; 
return ret;
end;$_$;


ALTER FUNCTION public.prescble(integer, integer) OWNER TO estlm;

--
-- Name: presintdeopv(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION presintdeopv(integer) RETURNS character
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	idopv		ALIAS FOR $1;  
	codmarcont	int4;
	indi		int4;
	regi		RECORD;
	trans		varchar;
	trans1		varchar;
	retval		varchar;
    BEGIN

    indi=1;
    for regi in select * from contene where cont_idopv= $1 
    loop
	trans1:= regi.cont_preori||'-'||regi.cont_preana;

	if indi>1 then
		retval:= trans1||' / '||regi.cont_preori||'-'||regi.cont_preana;
	    else
		retval:= trans1;
	end if;
	indi:=indi+1;
    end loop;
    
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.presintdeopv(integer) OWNER TO estlm;

--
-- Name: provinclie(integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION provinclie(integer, integer) RETURNS integer
    LANGUAGE sql
    AS $_$select sucu_provin from sucursalc where sucu_cliente= $1 and sucu_codigo= $2 ;$_$;


ALTER FUNCTION public.provinclie(integer, integer) OWNER TO estlm;

--
-- Name: proxgpocli(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION proxgpocli(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select max(astc_grupo)+1 from astoctas where astc_codemp=1 and astc_ctacble=18 and astc_ctacte= $1 ;$_$;


ALTER FUNCTION public.proxgpocli(integer) OWNER TO estlm;

--
-- Name: proxgpocte(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION proxgpocte(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select max(astc_grupo)+1 from astoctas where astc_ctacte= $1 ;$_$;


ALTER FUNCTION public.proxgpocte(integer) OWNER TO estlm;

--
-- Name: ptovdeastc(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION ptovdeastc(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select astc_idptov from astoctas where astc_id= $1 ;$_$;


ALTER FUNCTION public.ptovdeastc(integer) OWNER TO estlm;

--
-- Name: ptovdeastoc(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION ptovdeastoc(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select astc_idptov from astoctas where astc_id= $1 ;$_$;


ALTER FUNCTION public.ptovdeastoc(integer) OWNER TO estlm;

--
-- Name: ptovdefault(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION ptovdefault(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select ptv_id from ptovta where ptv_codemp= $1 order by ptv_id limit 1;$_$;


ALTER FUNCTION public.ptovdefault(integer) OWNER TO estlm;

--
-- Name: ptovemp(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION ptovemp(integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	empresa		ALIAS FOR $1; 
	retval 		integer;
	cuantos		integer;
    BEGIN
    select count(*) into cuantos from
    	 ptovta where int4eq(empresa,ptv_codemp);

	 if int4eq(cuantos,1) then
		select ptv_id into retval from
    		ptovta where int4eq(empresa,ptv_codemp);
	    else
		retval:=-1;
	 end if;		
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.ptovemp(integer) OWNER TO estlm;

--
-- Name: publico(date); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION publico(date) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	fecha		ALIAS FOR $1; -- fecha
	registro	RECORD;
	regi		RECORD;
	regi2		RECORD;
	primera		int4;
	estado		int2;
	operacion	int4;
	fecsal		date;
	operaciono	int4;
	fecsalo		date;
	trans		boolean;
	retval		int4;

    BEGIN

    primera:=1;
    estado:=0;

    for registro in
	select * from opervehi where opv_est_camion < 50 and opv_fecha_egr is not null order by opv_idoper
	loop
	operacion:=registro.opv_idoper;
	fecsal:=registro.opv_fecha_egr;

	if(int4eq(primera,1) or int4ne(operacion,operaciono)) then
		primera:=0;

		if(int2eq(estado,1::int2)) then
		    insert into auxoperv (avh_idoper,avh_fecha_pub) values (operaciono,fecsalo);
		end if;
		estado:=0;

		if(int2eq(registro.opv_est_camion,2::int2) and int2ne(estado,2::int2) and date_le(date(registro.opv_fecha_egr),fecha)) then
		        estado:=1;
		    else
			estado:=2;
		end if;

	    else

		if(int2ne(estado,2::int2) and int2eq(registro.opv_est_camion,2::int2) and date_le(date(registro.opv_fecha_egr),fecha)) then
		        estado:=1;
		    else
			estado:=2;
		end if;

	end if;

	operaciono:=registro.opv_idoper;
	fecsalo:=registro.opv_fecha_egr;

	end loop;

	if(int2eq(estado,1::int2)) then
	    insert into auxoperv (avh_idoper,avh_fecha_pub) values (operaciono,fecsalo);
	    retval:=operaciono;
	end if;


    for regi2 in
	select * from opervehi where opv_est_camion < 50 and opv_fecha_egr is null order by opv_idoper
	loop
	    delete from auxoperv where avh_idoper=regi2.opv_idoper;
	end loop;


    for regi in
	select * from auxoperv  
	loop
	    if(int2lt(estado_opera(regi.avh_idoper),100::int2)) then
		trans:=cambio_estado(regi.avh_idoper,101::int2,1::int2);
		update opervehi set opv_est_camion=50 where opv_idoper=regi.avh_idoper and opv_est_camion < 50;
		if(int4lt(tipoperdeop(regi.avh_idoper),100)) then
			update operaciones set op_fechain=regi.avh_fecha_pub where op_id=regi.avh_idoper;
		    else
			update operaciones set op_fechain=regi.avh_fecha_pub, op_fecha_close=regi.avh_fecha_pub where op_id=regi.avh_idoper;
		end if;
	    end if;
	end loop;


    delete from auxoperv;


    RETURN retval;
    END;$_$;


ALTER FUNCTION public.publico(date) OWNER TO estlm;

--
-- Name: reparoweb(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION reparoweb(integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
modo		 alias for $1;
ret 		 boolean;
registro	 record;
aux_texto	 text;
indirecto	 integer;
operacion	 integer;

begin


lock wret2 in access exclusive mode;

drop trigger au_wret2 ON wret2;


for registro in select 
     * from temporalweb
loop


    if(registro.wtmp_valor>0) then
	    update wret2 set wret2_cantidad=registro.wtmp_valor where wret2_id=registro.wtmp_idret;
--	    update wsubitem set wsitem_cantcompw=wsitem_cantcompw-registro.wtmp_compweb+registro.wtmp_valor where wsitem_id=idsitemdewret2(registro.wtmp_idret);
	    update wsubitem set wsitem_cantcompw=wsitem_cantcompw+registro.wtmp_valor where wsitem_id=idsitemdewret2(registro.wtmp_idret);
	    aux_texto:='SE LE COMUNICA QUE SE HA MODIFICADO LA REEXPEDICION NUMERO:  <b>'||idwopdewret2(registro.wtmp_idret)||'</b> QUE USTED HA CARGADO EN ESTE SISTEMA OPORTUNAMENTE RELACIONADA AL USUARIO INDIRECTO <b>'||nomusu(indirectodewret2(registro.wtmp_idret)) ||'</b>.  EL MOTIVO DE ESTA MODIFICACION RESPONDE AL PROCESAMIENTO POR PARTE DE OPERADORES DE LA CONCESIONARIA DE REEXPEDICIONES QUE AFECTAN AL ARTICULO:  <b>'||articulodewret2(registro.wtmp_idret)||'</b> QUE TAMBIEN FUERA COMPROMETIDO POR USTED.  VERIQUE LA CANTIDAD A RETIRAR DE ESE ARTICULO Y FINALIZE NUEVAMENTE LA OPERACION !!!!!!!';
	    ret:=grabonotiweb(directodewret2(registro.wtmp_idret),5,10,'ARTICULOS PARCIALMENTE COMPROMETIDOS',aux_texto);
	    update woperaciones set wop_estado=11 where wop_id=idwopdewret2(registro.wtmp_idret);

	else
	    aux_texto:='SE LE COMUNICA QUE SE HA ELIMINADO DE LA REEXPEDICION NUMERO:  <b>'||idwopdewret2(registro.wtmp_idret)||'</b> QUE USTED HA CARGADO EN ESTE SISTEMA OPORTUNAMENTE RELACIONADA AL USUARIO INDIRECTO <b>'||nomusu(indirectodewret2(registro.wtmp_idret)) ||'</b>.   EL ARTICULO:  <b>'||articulodewret2(registro.wtmp_idret)||' </b> QUE TAMBIEN FUERA COMPROMETIDO POR USTED.  EL MOTIVO RESPONDE AL PROCESAMIENTO POR PARTE DE OPERADORES DE LA CONCESIONARIA DE REEXPEDICIONES QUE AFECTAN DICHO ARTICULO VERIFIQUE NUEVAMENTE LA OPERACION !!!!!!!';
	    ret:=grabonotiweb(directodewret2(registro.wtmp_idret),5,10,'ITEMS DE REEXPEDICIONES ELIMINADOS',aux_texto);
--	    update wsubitem set wsitem_cantcompw=wsitem_cantcompw-registro.wtmp_compweb where wsitem_id=idsitemdewret2(registro.wtmp_idret);
	    delete from wret2 where wret2_id=registro.wtmp_idret;
	    update woperaciones set wop_estado=11 where wop_id=idwopdewret2(registro.wtmp_idret);

    end if;
end loop; 

CREATE TRIGGER au_wret2 AFTER UPDATE ON wret2 FOR EACH ROW EXECUTE PROCEDURE f_au_wret2();
			
 delete from temporalweb;
ret:='t';
return ret;
end;$_$;


ALTER FUNCTION public.reparoweb(integer) OWNER TO estlm;

--
-- Name: retenig(integer, numeric, date); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION retenig(integer, numeric, date) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	provd		ALIAS FOR $1; 
	imppago		ALIAS FOR $2;
	fecha		ALIAS FOR $3;
	codemp		integer;
	ptov		integer;
	tipct		integer;
	retsn		integer;
	idastoh		integer;
	deudxc		integer;
	ctaretig	integer;
	compnk		integer;
	registro	record;
	totpagt		numeric;
	totrett		numeric;
	totpag 		numeric;
	totret 		numeric;
	mnoi 		numeric;
	tasa 		numeric;
	retval 		numeric;
    BEGIN
    select prov_codemp into codemp from prove where prov_id=provd;
    select prov_idptov into ptov from prove where prov_id=provd;
    select valvaramb(codemp,ptov,'TIPCTADXC') into tipct;	
    select idcbl(codemp,valvaramb(codemp,ptov,'DEUDXC')::int4) into deudxc;
    select idcbl(codemp,valvaramb(codemp,ptov,'CTARETIG')::int4) into ctaretig;
    select valvaramb(codemp,ptov,'MNIRETIG') into mnoi;
    select valvaramb(codemp,ptov,'TASARIG') into tasa;
    select prov_retig into retsn from prove where prov_id=provd;
    select idcomp('NK',1) into compnk;

    totrett:=0;
    totpagt:=0;
    totret:=0;
    totpag:=0;
    retval:=0;


    if int4eq(retsn,1) then

	for registro in select 
         * from astoctas where astc_estado=2 and astc_ctacble=deudxc and astc_tipcta=tipct and astc_ctacte=provd and date_part('year',astc_fecval)=date_part('year',fecha::date) and date_part('month',astc_fecval)=date_part('month',fecha::date) and astc_importe>0 and astc_comprob!=compnk  
	    loop 
	    select sum(astc_importe*-1) into totrett from astoctas where astc_idastoh=registro.astc_idastoh and astc_ctacble=ctaretig and astc_importe<0; 
	    select sum(astc_importe*-1) into totpagt from astoctas where astc_idastoh=registro.astc_idastoh and astc_importe<0; 
	
	    if totpagt is null then
		totpagt:=0;
	    end if;

	    if totrett is null then
		totrett:=0;
	    end if;

	    totpag:= totpag + totpagt;
	    totret:= totret + totrett;
	    
	    end loop;

	    
	if totpag is null then
	    totpag:=0;
	end if;

	if totret is null then
	    totret:=0;
	end if;

	totpag:= ((totpag + imppago)/1.21) - mnoi;


	if(totpag > 0 ) then
	    retval:= ( totpag * tasa / 100) - totret;
	end if;

	if(retval < 0 ) then
	end if;

    end if;

    RETURN retval;
    END;$_$;


ALTER FUNCTION public.retenig(integer, numeric, date) OWNER TO estlm;

--
-- Name: reti_a_fecha(integer, date); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION reti_a_fecha(integer, date) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
DECLARE
idsitem		ALIAS FOR $1; 	-- id del subitem
fecha		ALIAS FOR $2;	-- fecha hasta
difer1 		numeric;
difer2 		numeric;
retval 		numeric;
BEGIN

retval:=0;

select sum(ret_cantidad) into retval from
    retiros where ret_idsitem=idsitem and date_le(fechainop(ret_idopera),fecha) and estadop(ret_idopera)=101;


if retval is null then
    retval:=0;
end if;


select sum(ret_cantidad) into difer1 from
    retiros where ret_idsitem=idsitem and estadop(ret_idopera)=101;

if difer1 is null then
    difer1:=0;
end if;


select sitem_cantret into difer2 from
    subitem where sitem_id=idsitem;

if difer2 is null then
    difer2:=0;
end if;


if numeric_ne(difer2,difer1) then

retval:=retval + difer2 - difer1;
end if;


RETURN retval;
END;$_$;


ALTER FUNCTION public.reti_a_fecha(integer, date) OWNER TO estlm;

--
-- Name: reti_a_fechap(integer, date); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION reti_a_fechap(integer, date) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
DECLARE
idsitem		ALIAS FOR $1; 	-- id del subitem
fecha		ALIAS FOR $2;	-- fecha hasta
retval 		numeric;
BEGIN

retval:=0;

select sum(ret_cantidad) into retval from
    retiros where ret_idsitem=idsitem and date_le(fechainop(ret_idopera),fecha) and estadop(ret_idopera)=101;


if retval is null then
    retval:=0;
end if;


RETURN retval;
END;$_$;


ALTER FUNCTION public.reti_a_fechap(integer, date) OWNER TO estlm;

--
-- Name: rexpconfactur(date, date, smallint, smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION rexpconfactur(date, date, smallint, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
desde		 alias for $1;
hasta		 alias for $2;
anio 		 alias for $3;
mes 		 alias for $4;
ret 		 boolean;
registro	 record;
directo		 int4;
indirecto	 int4;
tipoper		 int4;
hay	 	 int4;
auxot		 varchar;
begin

ret:='t';
for registro in select 
    * from operaciones where op_estado=101 and date_ge(op_fechain,desde) and date_le(op_fechain,hasta) and op_tipoper in (101,105) 
	loop

	ret:='f';
	select cfc_id into hay from confactur where cfc_idoper=registro.op_id and cfc_idart=35 and cfc_fecha=registro.op_fechain;
	if not found then
	    auxot:=substr(nomusu(registro.op_indirecto),1,25) || ' / ' || substr(traigo_simbtipoper(registro.op_tipoper),1,3) || '-'|| registro.op_nrotaldir;
--	    insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_idoper,cfc_leyen,cfc_estado,cfc_anio,cfc_mes,cfc_indirecto) values (registro.op_directo,registro.op_fechain,35::int4,1::numeric,20::numeric,20::numeric,registro.op_id,auxot,1::int2,anio,mes,registro.op_indirecto);
	    insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_idoper,cfc_leyen,cfc_estado,cfc_anio,cfc_mes,cfc_indirecto) values (registro.op_directo,registro.op_fechain,35::int4,1::numeric,valtari(registro.op_directo,35,0::numeric,0::int2,registro.op_fechain::date),valtari(registro.op_directo,35,0::numeric,0::int2,registro.op_fechain::date),registro.op_id,auxot,1::int2,anio,mes,registro.op_indirecto);
	end if;

end loop; 

return ret;
end;$_$;


ALTER FUNCTION public.rexpconfactur(date, date, smallint, smallint) OWNER TO estlm;

--
-- Name: rexpconfacturd(date, date, smallint, smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION rexpconfacturd(date, date, smallint, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
desde		 alias for $1;
hasta		 alias for $2;
anio 		 alias for $3;
mes 		 alias for $4;
ret 		 boolean;
registro	 record;
directo		 int4;
indirecto	 int4;
tipoper		 int4;
hay	 	 int4;
auxot		 varchar;
begin

ret:='t';
for registro in select 
    * from operaciones where op_estado=101 and date_ge(op_fechain,desde) and date_le(op_fechain,hasta) and op_tipoper in (101,105) 
	loop

	ret:='f';
	select cfc_id into hay from confactur where cfc_idoper=registro.op_id and cfc_idart=35;
	if not found then
	    auxot:=substr(nomusu(registro.op_indirecto),1,25) || ' / ' || substr(traigo_simbtipoper(registro.op_tipoper),1,3) || '-'|| registro.op_nrotaldir;
--	    insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_idoper,cfc_leyen,cfc_estado,cfc_anio,cfc_mes,cfc_indirecto) values (registro.op_directo,registro.op_fechain,35::int4,1::numeric,20::numeric,20::numeric,registro.op_id,auxot,1::int2,anio,mes,registro.op_indirecto);
	    insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_idoper,cfc_leyen,cfc_estado,cfc_anio,cfc_mes,cfc_indirecto) values (registro.op_directo,registro.op_fechain,35::int4,1::numeric,valtari(registro.op_directo,35,0::numeric,0::int2,registro.op_fechain::date),valtari(registro.op_directo,35,0::numeric,0::int2,registro.op_fechain::date),registro.op_id,auxot,1::int2,anio,mes,registro.op_indirecto);
	end if;
end loop; 

return ret;
end;$_$;


ALTER FUNCTION public.rexpconfacturd(date, date, smallint, smallint) OWNER TO estlm;

--
-- Name: sacoauto(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION sacoauto(integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
idiol		alias for $1;
ret 		boolean;
idio 		int4;
existe 		int4;
existeo		int4;
fecout		timestamp without time zone;
begin

    existeo:=2;
    select ogxl_io into idio from outgxl where ogxl_iol=idiol limit 1;

    if not found then
	select igxl_io into idio from ingxl where igxl_iol=idiol limit 1;
	if not found then
	    ret:='f';
	  else
	    existe:=1;
	    ret:='t';
	end if;
      else
	existeo:=1;
	existe:=1;
	ret:='t';
    end if;

    if int4eq(existe,1::int4) then
	select io_fecout into fecout from inout where io_id=idio;
	if found then
	    update inoutliv set iol_estado=101, iol_fecout=fecout where iol_id=idiol;	    
	    if int4eq(existeo,2::int4) then
		insert into outgxl values(idiol,idio,101);
	    end if;
	end if;
    end if;




return ret;
end;$_$;


ALTER FUNCTION public.sacoauto(integer) OWNER TO estlm;

--
-- Name: saldoal(integer, integer, integer, integer, date); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION saldoal(integer, integer, integer, integer, date) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	codemp		ALIAS FOR $1; 
	ptovta		ALIAS FOR $2; 
	tipcta		ALIAS FOR $3; 
	ctacte		ALIAS FOR $4;
	fechad		ALIAS FOR $5;
	salant 		numeric;
	retval 		numeric;
    BEGIN
    select sum(astc_importe) into retval from astoctas 
	where astc_codemp=codemp and astc_idptov=ptovta and astc_tipcta=tipcta 
	and astc_ctacte=ctacte and astc_fecval< fechad and astc_cierra= 1
	and astc_estado=2;

    if retval is NULL then
	    retval:=0;
    end if;
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.saldoal(integer, integer, integer, integer, date) OWNER TO estlm;

--
-- Name: saldocbl(integer, integer, integer, date); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION saldocbl(integer, integer, integer, date) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	codemp		ALIAS FOR $1; 
	ptovta		ALIAS FOR $2; 
	cuenta		ALIAS FOR $3; 
	fechad		ALIAS FOR $4;
	retval 		numeric;
    BEGIN
    if int4eq(codemp,-1) then
	    select sum(astc_importe) into retval from astoctas 
		where astc_ctacble=cuenta and astc_fecval< fechad and astc_estado=2 and codcomp(astc_comprob)!='AR' ;
        else
	    if int4eq(ptovta,0) then
		    select sum(astc_importe) into retval from astoctas 
			where astc_codemp=codemp and astc_ctacble=cuenta 
			    and astc_estado=2 and astc_comprob not in (6,7,147,157) and astc_fecval< fechad;
    		else
		    select sum(astc_importe) into retval from astoctas 
			where astc_codemp=codemp and astc_idptov=ptovta  
			    and astc_ctacble=cuenta and astc_estado=2 and astc_comprob not in (6,7,147,157) 
			    and astc_fecval< fechad ;
	    end if;
    end if;

    if retval is NULL then
	    retval:=0;
    end if;
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.saldocbl(integer, integer, integer, date) OWNER TO estlm;

--
-- Name: salgrup(integer, integer, integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION salgrup(integer, integer, integer, integer) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	codemp		ALIAS FOR $1; 
	tipcta		ALIAS FOR $2;
	ctacte		ALIAS FOR $3;
	grupo		ALIAS FOR $4;
	esisti		integer;
	retval 		numeric;
    BEGIN
    if int4eq(grupo,0) then
	    select sum(astc_importe) into retval from astoctas
		where astc_codemp=codemp and astc_estado=2 and astc_tipcta=tipcta
		    and astc_ctacte=ctacte and astc_grupo is null;
	else
	    select sum(astc_importe) into retval from astoctas
		where astc_codemp=codemp and astc_estado=2 and astc_tipcta=tipcta
		    and astc_ctacte=ctacte and astc_grupo=grupo;
    end if;

    if not found then
	retval:=0;
    end if;
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.salgrup(integer, integer, integer, integer) OWNER TO estlm;

--
-- Name: seg_disponible(smallint, numeric, smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION seg_disponible(smallint, numeric, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	cod_unifun	ALIAS FOR $1; -- id dela unifun
	valorfob	ALIAS FOR $2; -- Valor Fob
	caso		ALIAS FOR $3; -- Caso 
	
		    --  0=compara parametro contra monto UNIFUN
		    --  1=compara contra la oper (INSERTO DE OP FUTURO)
 
	compara 	numeric;
	aux_seg 	varchar;
	retval 		boolean;
    BEGIN
	if caso=0 then
		SELECT  unif_seguro - unif_valormerca INTO compara FROM unifun   
		    WHERE cod_unifun = unif_codigo;
			retval:=numeric_le(valorfob,compara); 
	    elsif	
	    caso=1 then
		 SELECT  var_valor  INTO     aux_seg 	-- Controla seguro??
		    FROM varamb    WHERE var_codigo like 'SEGURO%';
	    
		 if bpchareq(aux_seg,'NO') then
			return true;
	        else
	    	SELECT  unif_seguro - unif_valormerca INTO compara FROM unifun   
			WHERE cod_unifun = unif_codigo;
	    	retval:=numeric_le(valorfob,compara); 
	        end if;	
	    
	    end if;


    RETURN retval;
    END;$_$;


ALTER FUNCTION public.seg_disponible(smallint, numeric, smallint) OWNER TO estlm;

--
-- Name: seg_ok(integer, smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION seg_ok(integer, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	cod_operacion	ALIAS FOR $1; -- id dela operacion
	cod_modo	ALIAS FOR $2; -- modo de operacion
-- modo =	1 valido para notificar y devuelvo true
--		2 valido pulenta (notifico y devuelvo true/false segun)
	compara 	numeric;
	registro 	RECORD;
	retval 		boolean;
	trans 		boolean;
	aux_seg 	varchar;
	aux_texto 	text;
    BEGIN
    retval:='t';		
    SELECT  var_valor  INTO     aux_seg 	-- Controla seguro??
	    FROM varamb    WHERE var_codigo like 'SEGURO%';
	
    if bpchareq(aux_seg,'NO') 
	then return true;
    end if;

    for registro in select sitem_deposito as x,sum(sitem_imp_dolar) as y
     from subitem where sitem_idoper=cod_operacion group by sitem_deposito
	loop
	trans:=seg_disponible(registro.x,registro.y,0::int2);

	if booleq(trans,'f') then 
		retval:=trans;	
		aux_texto:='Con la unifun '||registro.x ||' existen problemas de seguro por '||registro.y ||' !!!!!!!!!!';
		insert into noticias(not_tipo,not_numero,not_texto)values(1,cod_operacion,aux_texto);
	    end if;
	end loop; 

	if  bpchareq(aux_seg,'NI') or (int2eq(cod_modo,1::int2)) then
--	if  bpchareq(aux_seg,'NI') then
--	if   (int2eq(cod_modo,1::int2)) then
	    retval:='t';		
	end if;
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.seg_ok(integer, smallint) OWNER TO estlm;

--
-- Name: sepuedeimportar(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION sepuedeimportar(integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
wopid		 alias for $1;
ret 		 boolean;
registro	 record;
begin

ret:='t';

for registro in select 
    cantidisponib(wret2_idsitem) as x, wret2_cantidad as y
    from wret2 where wret2_idopera=wopid 
    loop
	if(booleq(ret,'t')) then
	    if(registro.x < registro.y) then
		ret:='f';
	    end if;
	end if;
    end loop; 

return ret;
end;$_$;


ALTER FUNCTION public.sepuedeimportar(integer) OWNER TO estlm;

--
-- Name: simbmoneda(smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION simbmoneda(smallint) RETURNS character
    LANGUAGE sql
    AS $_$select mon_simbol from moneda where mon_codigo= $1 ;$_$;


ALTER FUNCTION public.simbmoneda(smallint) OWNER TO estlm;

--
-- Name: simbunimeditem(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION simbunimeditem(integer) RETURNS character
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	sitem		ALIAS FOR $1;  
	deposito	int2;
	retval		varchar;
    BEGIN

    SELECT  item_unimed INTO deposito
	    FROM item   WHERE int4eq(item_id,sitem);

    SELECT  uni_simbolo INTO retval
	    FROM unimed   WHERE int2eq(uni_codigo,deposito);

    RETURN retval;
    END;$_$;


ALTER FUNCTION public.simbunimeditem(integer) OWNER TO estlm;

--
-- Name: simbunimedwsitem(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION simbunimedwsitem(integer) RETURNS character
    LANGUAGE sql
    AS $_$select uni_simbolo from unimed where uni_codigo= $1 ;$_$;


ALTER FUNCTION public.simbunimedwsitem(integer) OWNER TO estlm;

--
-- Name: stasaconiva(smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION stasaconiva(smallint) RETURNS numeric
    LANGUAGE sql
    AS $_$select iva_stasa from coniva where iva_codigo= $1;$_$;


ALTER FUNCTION public.stasaconiva(smallint) OWNER TO estlm;

--
-- Name: stivacli(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION stivacli(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select stasaconiva(cli_coniva) from clientes where cli_id= $1;$_$;


ALTER FUNCTION public.stivacli(integer) OWNER TO estlm;

--
-- Name: subtotf(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION subtotf(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sum(movs_importe) from movsto where movs_idastoh= $1 ;$_$;


ALTER FUNCTION public.subtotf(integer) OWNER TO estlm;

--
-- Name: taldecomp(integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION taldecomp(integer, integer) RETURNS integer
    LANGUAGE sql
    AS $_$select tal_id from talon where tal_codemp = $1 and tal_comprob= $2;$_$;


ALTER FUNCTION public.taldecomp(integer, integer) OWNER TO estlm;

--
-- Name: tasaartic(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION tasaartic(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select art_tasa from articvta where art_id= $1 ;$_$;


ALTER FUNCTION public.tasaartic(integer) OWNER TO estlm;

--
-- Name: tasaconiva(smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION tasaconiva(smallint) RETURNS numeric
    LANGUAGE sql
    AS $_$select iva_tasa from coniva where iva_codigo= $1;$_$;


ALTER FUNCTION public.tasaconiva(smallint) OWNER TO estlm;

--
-- Name: tiene_funcion(integer, integer, integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION tiene_funcion(integer, integer, integer, integer) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	idreg		ALIAS FOR $1;  -- id del registro
	idartic		ALIAS FOR $2;  -- id del articulo 
	idoper		ALIAS FOR $3; 
	tabla		ALIAS FOR $4;  -- 1=voling   y   2=volegr 
	modo		int4;
	pase		int4;
	sinfun		int4;
	registro	record;
	valorfob	text;
	funcion		text;
	funcion2	text;
	funcion3	text;
	cotiz		text;
	peso		text;
	volumen		numeric;
	cantidad	numeric;
	preciopul	numeric;
	precio		numeric;
	retval		numeric;
    BEGIN
    retval:=0;
    pase:=0;
    sinfun:=1;

	select cfac_funcion into funcion from complfac where cfac_id=idreg;
	if not found then
	    select art_funcion into funcion from articvta where art_id=idartic;
	    if not found then
		sinfun:=0;
	    end if;
	end if;


	select cfac_precio into preciopul from complfac where cfac_id=idreg;
	if not found then
	    select art_precio into precio from articvta where art_id=idartic;
	end if;

if sinfun then
	if funcion then
	    if numeric_gt(preciopul,0) then
		    retval:=preciopul; 
		else
		    if(precio) then
			retval:=precio; 
		    end if;
	    end if;
	end if;
end if;


RETURN retval;
END;$_$;


ALTER FUNCTION public.tiene_funcion(integer, integer, integer, integer) OWNER TO estlm;

--
-- Name: tipctacbl(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION tipctacbl(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select cbl_tipcta from ctacble where cbl_id= $1 ;$_$;


ALTER FUNCTION public.tipctacbl(integer) OWNER TO estlm;

--
-- Name: tipprod_item(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION tipprod_item(integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	itemc	ALIAS FOR $1; -- id del Item
	tipo	int4;
    BEGIN
    SELECT item_tipprod into tipo
	FROM item WHERE item_id = itemc;
    RETURN tipo;
    END;$_$;


ALTER FUNCTION public.tipprod_item(integer) OWNER TO estlm;

--
-- Name: tipprod_ok(integer, smallint, smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION tipprod_ok(integer, smallint, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	operacion	ALIAS FOR $1; -- id dela operacion
	unifun		ALIAS FOR $2; -- id unifun
	modo		ALIAS FOR $3; -- modo
-- modo =	1 valido para notificar y devuelvo true
--		2 valido pulenta (notifico y devuelvo true/false segun)
	compara 	numeric;
	registro 	RECORD;
	retval 		boolean;
	trans 		boolean;
	aux_seg 	varchar;
	aux_texto 	text;
    BEGIN
    retval:='t';		
    SELECT  var_valor  INTO     aux_seg 	-- Controla tipo de merca?
	    FROM varamb    WHERE var_codigo like 'VALID_TIPMERC%';
	
    if bpchareq(aux_seg,'NO') 
	then return true;
    end if;

    for registro in select sitem_iditem as x,sitem_deposito as y,count(*) as z
     from subitem where sitem_idoper=operacion  group by x,y
	loop
	trans:=tipprod_posible(registro.y::int2,tipprod_item(registro.x));

	if booleq(trans,'f') then 
		retval:=trans;	
		aux_texto:='La unidad funcional '||registro.y||'  ('||traigo_nomunifun(registro.y) ||')  no tolera el ingreso de mercaderia del tipo '||tipprod_item(registro.x) ||' debera cambiar de ubicacion la misma. Notifique al usuario ';
		insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
	    end if;
	end loop; 

	if  bpchareq(aux_seg,'NI') or (int2eq(modo,1::int2)) then
	    retval:='t';		
	end if;

    RETURN retval;
    END;$_$;


ALTER FUNCTION public.tipprod_ok(integer, smallint, smallint) OWNER TO estlm;

--
-- Name: tipprod_posible(smallint, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION tipprod_posible(smallint, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	unifun		ALIAS FOR $1; -- id de Unifun.
	tipmerc		ALIAS FOR $2; -- tipo de Mercaderia
	compara 	numeric;
	registro 	RECORD;
	kk 		int2;
	retval 		boolean;
	trans 		boolean;
	aux_seg 	varchar;
    BEGIN
    retval:='t';		
    SELECT  var_valor  INTO     aux_seg 	-- Controla Tipo de Merca??
	    FROM varamb    WHERE var_codigo like 'VALID_TIPMERC%';
	
    if bpchareq(aux_seg,'NO') 
	then return true;
    end if;


    select txu_codtipp into kk from tippxunif where 
	    int4eq(txu_codtipp,tipmerc) and 
		int2eq(txu_codunif,unifun);
    if not found then 
	return false;
    end if;


    if bpchareq(aux_seg,'NI')  then
	    retval:='t';		
	end if;
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.tipprod_posible(smallint, integer) OWNER TO estlm;

--
-- Name: tipprodsitem(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION tipprodsitem(integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	sitem		ALIAS FOR $1;  
	iditem		int4;
	retval		int4;
    BEGIN

    select sitem_iditem into iditem from subitem where sitem_id= $1 ;

    select item_tipprod into retval from item where item_id=iditem;
    
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.tipprodsitem(integer) OWNER TO estlm;

--
-- Name: tipprove(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION tipprove(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select prov_tipo from prove where prov_id= $1 ;$_$;


ALTER FUNCTION public.tipprove(integer) OWNER TO estlm;

--
-- Name: titastoh(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION titastoh(integer) RETURNS character
    LANGUAGE sql
    AS $_$select ash_titulo from astoh where ash_id= $1 ;$_$;


ALTER FUNCTION public.titastoh(integer) OWNER TO estlm;

--
-- Name: tivacli(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION tivacli(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select tasaconiva(cli_coniva) from clientes where cli_id= $1;$_$;


ALTER FUNCTION public.tivacli(integer) OWNER TO estlm;

--
-- Name: totfactu(integer, smallint, smallint, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION totfactu(integer, smallint, smallint, integer) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
declare
usuario		 alias for $1;
anio		 alias for $2;
mes		 alias for $3;
articulo	 alias for $4;
ret 		 numeric;

begin

if int4eq(articulo,0) then 
    select sum(cfc_importe) into ret from confactur where cfc_usuario=usuario and cfc_anio=anio and cfc_mes=mes;
  else
    select sum(cfc_importe) into ret from confactur where cfc_usuario=usuario and cfc_anio=anio and cfc_mes=mes and cfc_idart=articulo;
end if;

return ret;
end;$_$;


ALTER FUNCTION public.totfactu(integer, smallint, smallint, integer) OWNER TO estlm;

--
-- Name: totimpastc(integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION totimpastc(integer, integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select astc_importe from astoctas where astc_ctacble= $1 and astc_idastoh= $2 ;$_$;


ALTER FUNCTION public.totimpastc(integer, integer) OWNER TO estlm;

--
-- Name: tposastc(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION tposastc(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sum(astc_importe) from astoctas where astc_idastoh= $1 and astc_importe>0 ;$_$;


ALTER FUNCTION public.tposastc(integer) OWNER TO estlm;

--
-- Name: trae_cotiza(smallint, date); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION trae_cotiza(smallint, date) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
declare
moneda		 alias for $1;
fecha		 alias for $2;
ret 		 numeric;
begin
     SELECT  cot_cotiz  INTO     ret 
	    FROM cotiza    
		WHERE int2eq(moneda,cot_moneda) and  
		    date_le(cot_fecha,fecha) 
	    order by cot_fecha desc limit 1;
return ret;
END;$_$;


ALTER FUNCTION public.trae_cotiza(smallint, date) OWNER TO estlm;

--
-- Name: traigo_codarticu(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION traigo_codarticu(integer) RETURNS character
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	sitem		ALIAS FOR $1;  
	idart		int4;
	retval		varchar;
    BEGIN

    select sitem_artic into idart from subitem where sitem_id= $1 ;

    select artic_codigo into retval from articu where artic_id=idart;
    
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.traigo_codarticu(integer) OWNER TO estlm;

--
-- Name: transfieroweb(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION transfieroweb(integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
wopid		 alias for $1;
ret 		 boolean;
registro	 record;
regist		 record;
registleye	 record;
registwr	 record;
registw2	 record;
disponible	 numeric;
dispon		 numeric;
compromweb	 numeric;
llevo		 numeric;
elultimo	 numeric;
idop		 integer;
primera		 integer;
elestado	 smallint;
begin

ret:='t';
idop:=0;

select wop_estado into elestado from woperaciones where wop_id=wopid;

if found then
    if int2eq(elestado,1::int2) then

	for registro in select 
	    cantidisponib(wret2_idsitem) as x, wret2_cantidad as y
	    from wret2 where wret2_idopera=wopid 
	    loop
		if(booleq(ret,'t')) then
		    if(registro.x < registro.y) then
			ret:='f';
		    end if;
		end if;
	    end loop; 


	if(booleq(ret,'t')) then

		insert into operaciones(op_directo,op_indirecto,op_tipoper,op_idopw,op_operador,op_nrotalzon,op_nrotaldir) select wop_directo,wop_indirecto,wop_tipoper,wop_id,wop_operador,val_talon(wop_tipoper,1),val_talon(wop_tipoper,wop_directo) from woperaciones where wop_id = wopid;

		select op_id into idop from operaciones where op_idopw=wopid;

		for regist in select 
		    * from wret2 where wret2_idopera=wopid
		loop
		    insert into retiros (ret_idopera,ret_idsitem,ret_item,ret_sitem,ret_cantidad) values (idop,regist.wret2_idsitem,regist.wret2_item,regist.wret2_sitem,regist.wret2_cantidad);
		    update wsubitem set wsitem_cantcomp=wsitem_cantcomp+regist.wret2_cantidad, wsitem_cantcompw=wsitem_cantcompw-regist.wret2_cantidad where wsitem_id=regist.wret2_idsitem;
		end loop; 

		for registleye in select 
		    * from wleyenrexp where wleyr_idoper=wopid
		loop
		    insert into leyenrexp (leyr_idoper,leyr_nro,leyr_leyenda) values (idop,registleye.wleyr_nro,registleye.wleyr_leyenda);
		end loop; 

		update woperaciones set wop_estado=50 where wop_id=wopid;

		for registwr in select 
		    * from retiros where ret_idopera=idop
		loop
		    insert into wretiros (wret_id,wret_idopera,wret_idsitem,wret_item,wret_sitem,wret_cantidad,wret_idsitemc,wret_compbte,wret_tipoper,wret_nrotaldir,wret_estado) 
			values (registwr.ret_id,registwr.ret_idopera,registwr.ret_idsitem,registwr.ret_item,registwr.ret_sitem,registwr.ret_cantidad,registwr.ret_idsitemc,compbteoper(registwr.ret_idopera),tipoperdeop(registwr.ret_idopera),nrotaldiroper(registwr.ret_idopera),1::int2);
		end loop; 


	    else


		for registw2 in select 
		    * from wret2 where wret2_idopera=wopid 
	        loop

		primera:=0;
		elultimo:=0;
		dispon:=0;
		dispon:=cantidisponib(registw2.wret2_idsitem);
		elultimo:=registw2.wret2_cantidad;

		if(elultimo<=dispon) then
			if(int4eq(primera,0)) then
			    insert into operaciones(op_directo,op_indirecto,op_tipoper,op_idopw,op_operador,op_nrotalzon,op_nrotaldir) select wop_directo,wop_indirecto,wop_tipoper,wop_id,wop_operador,val_talon(wop_tipoper,1),val_talon(wop_tipoper,wop_directo) from woperaciones where wop_id = wopid;
			    select op_id into idop from operaciones where op_idopw=wopid;
			    for registleye in select 
				* from wleyenrexp where wleyr_idoper=wopid
			    loop
				insert into leyenrexp (leyr_idoper,leyr_nro,leyr_leyenda) values (idop,registleye.wleyr_nro,registleye.wleyr_leyenda);
			    end loop; 
			    primera:=1;
			end if;

			update wsubitem set wsitem_cantcompw=wsitem_cantcompw + registw2.wret2_cantidad where wsitem_id=registw2.wret2_idsitem;

		    else
			if(dispon <= 0) then
				insert into temporalweb (wtmp_idsitem,wtmp_disponib,wtmp_compweb,wtmp_idret,wtmp_valor) values (registw2.wret2_idsitem,dispon,elultimo,registw2.wret2_id,-1);
    			    else
				insert into temporalweb (wtmp_idsitem,wtmp_disponib,wtmp_compweb,wtmp_idret,wtmp_valor) values (registw2.wret2_idsitem,dispon,elultimo,registw2.wret2_id,dispon);
			end if;
		end if;
		end loop; 

		ret:=reparoweb(1);
	end if;
    end if;
end if;
return idop;
end;$_$;


ALTER FUNCTION public.transfieroweb(integer) OWNER TO estlm;

--
-- Name: transfreexpdeweb(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION transfreexpdeweb(integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
wopid		 alias for $1;
ret 		 boolean;
registro	 record;
regist		 record;
registleye	 record;
registwr	 record;
registw2	 record;
disponible	 numeric;
dispon		 numeric;
compromweb	 numeric;
llevo		 numeric;
elultimo	 numeric;
idop		 integer;
primera		 integer;
entre		 integer;
elestado	 smallint;
aux_texto	 text;
aux_texto1	 text;
aux_texto2	 text;
aux_texto3	 text;
begin

ret:='t';
entre:=0;
idop:=0;

select wop_estado into elestado from woperaciones where wop_id=wopid;

if found then
    if int2eq(elestado,1::int2) then
	for registro in select 
	    cantidisponib(wret2_idsitem) as x, wret2_cantidad as y
	    from wret2 where wret2_idopera=wopid 
	    loop
		entre:=1;
		if(booleq(ret,'t')) then
		    if(registro.x < registro.y) then
			ret:='f';
		    end if;
		end if;
	    end loop; 


    if int4eq(entre,0) then
	ret:='f';
    end if;


	if(booleq(ret,'t')) then

		insert into operaciones(op_directo,op_indirecto,op_tipoper,op_idopw,op_operador,op_nrotalzon,op_nrotaldir,op_consig) select wop_directo,wop_indirecto,wop_tipoper,wop_id,wop_operador,val_talon(wop_tipoper,1),val_talon(wop_tipoper,wop_directo),wop_consig from woperaciones where wop_id = wopid;

		select op_id into idop from operaciones where op_idopw=wopid;

		for regist in select 
		    * from wret2 where wret2_idopera=wopid
		loop
		    insert into retiros (ret_idopera,ret_idsitem,ret_item,ret_sitem,ret_cantidad) values (idop,regist.wret2_idsitem,regist.wret2_item,regist.wret2_sitem,regist.wret2_cantidad);
		    update wsubitem set wsitem_cantcomp=wsitem_cantcomp+regist.wret2_cantidad, wsitem_cantcompw=wsitem_cantcompw-regist.wret2_cantidad where wsitem_id=regist.wret2_idsitem;
		end loop; 

		for registleye in select 
		    * from wleyenrexp where wleyr_idoper=wopid
		loop
		    insert into leyenrexp (leyr_idoper,leyr_nro,leyr_leyenda) values (idop,registleye.wleyr_nro,registleye.wleyr_leyenda);
		end loop; 

		update woperaciones set wop_estado=50 where wop_id=wopid;

		for registwr in select 
		    * from retiros where ret_idopera=idop
		loop
		    insert into wretiros (wret_id,wret_idopera,wret_idsitem,wret_item,wret_sitem,wret_cantidad,wret_idsitemc,wret_compbte,wret_tipoper,wret_nrotaldir,wret_estado) 
			values (registwr.ret_id,registwr.ret_idopera,registwr.ret_idsitem,registwr.ret_item,registwr.ret_sitem,registwr.ret_cantidad,registwr.ret_idsitemc,compbteoper(registwr.ret_idopera),tipoperdeop(registwr.ret_idopera),nrotaldiroper(registwr.ret_idopera),1::int2);
		end loop; 


	    else


		for registro in select 
		    * from wret2 where wret2_idopera=wopid 
		loop

		    delete from wretiros where wret_idsitem=registro.wret2_idsitem; 

		    for regist in select 
			* from retiros where ret_idsitem=registro.wret2_idsitem
			loop
			    insert into wretiros (wret_id,wret_idopera,wret_idsitem,wret_item,wret_sitem,wret_cantidad,wret_idsitemc,wret_compbte,wret_tipoper,wret_nrotaldir) 
				values (regist.ret_id,regist.ret_idopera,regist.ret_idsitem,regist.ret_item,regist.ret_sitem,regist.ret_cantidad,regist.ret_idsitemc,compbteoper(regist.ret_idopera),tipoperdeop(regist.ret_idopera),nrotaldiroper(regist.ret_idopera));
			end loop; 


		    if(registro.wret2_cantidad<=cantidisponib(registro.wret2_idsitem)) then

			    update wsubitem set wsitem_cantcompw=cantcompwdeidwsitem(registro.wret2_idsitem),wsitem_canting=cantingdeidsitem(registro.wret2_idsitem),wsitem_cantcomp=cantcompdeidsitem(registro.wret2_idsitem),wsitem_cantret=cantretdeidsitem(registro.wret2_idsitem),wsitem_cantmala=cantmaladeidsitem(registro.wret2_idsitem) where wsitem_id=registro.wret2_idsitem;

			else

			    aux_texto2:='<br> SE HA ELIMINADO EL ARTICULO  <B> '||codartdewret2(registro.wret2_id)||'</B> EL CUAL USTED HABIA COMPROMETIDO POR UNA CANTIDAD DE : <B>'||registro.wret2_cantidad||'</B> ';
			    insert into temporalweb (wtmp_idwop,wtmp_idsitem,wtmp_disponib,wtmp_compweb,wtmp_idret,wtmp_valor) values (wopid,registro.wret2_idsitem,cantidisponib(registro.wret2_idsitem),registro.wret2_cantidad,registro.wret2_id,-1);

		    end if;

		end loop; 

		aux_texto:='SE LE COMUNICA QUE NO SE HA PODIDO PROCESAR LA REEXPEDICION NUMERO:  <b>'||wopid||' </b>QUE USTED HA CARGADO EN ESTE SISTEMA OPORTUNAMENTE RELACIONADA AL USUARIO INDIRECTO  <b>'||nomusu(indirectodewop(wopid))||' </b>.  EL MOTIVO DE ESTA MODIFICACION RESPONDE AL PROCESAMIENTO POR PARTE DE OPERADORES DE LA CONCESIONARIA DE REEXPEDICIONES QUE AFECTAN AL/LOS SIGUIENTES ARTICULOS POR USTED COMPROMETIDOS '||aux_texto2||'<BR>   VERIQUE NUEVAMENTE LA OPERACION Y FINALICELA !!!!!!! ';
		ret:=grabonotiweb(directodewop(wopid),5,10,'ERROR EN LA IMPORTACION DE REEXPEDICIONES',aux_texto);
		update woperaciones set wop_estado=11 where wop_id=wopid;



		for registro in select 
    		    * from temporalweb where wtmp_idwop=wopid
		    loop
			update wsubitem set wsitem_canting=cantingdeidsitem(registro.wtmp_idsitem),wsitem_cantcomp=cantcompdeidsitem(registro.wtmp_idsitem),wsitem_cantret=cantretdeidsitem(registro.wtmp_idsitem),wsitem_cantmala=cantmaladeidsitem(registro.wtmp_idsitem) where wsitem_id=registro.wtmp_idsitem;
			delete from wret2 where wret2_id=registro.wtmp_idret;
		    end loop; 
			
		delete from temporalweb where wtmp_idwop=wopid;

	end if;
    end if;
end if;
return idop;
end;$_$;


ALTER FUNCTION public.transfreexpdeweb(integer) OWNER TO estlm;

--
-- Name: ult_cotiz(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION ult_cotiz(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select cot_cotiz  from cotiza where cot_moneda = $1  order by cot_fecha desc limit 1;$_$;


ALTER FUNCTION public.ult_cotiz(integer) OWNER TO estlm;

--
-- Name: ulticont(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION ulticont(integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
opid		 alias for $1;
ret 		 int4;
begin
select max(contr_id) into ret from contratos;
return ret;
end;$_$;


ALTER FUNCTION public.ulticont(integer) OWNER TO estlm;

--
-- Name: unifunes(integer, integer, integer, smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION unifunes(integer, integer, integer, smallint) RETURNS character varying
    LANGUAGE plpgsql
    AS $_$
declare
locador		 alias for $1;
locatario	 alias for $2;
idsubt		 alias for $3;
estado		 alias for $4;
ret		 character varying;
registro	 record;

begin

	ret='';
	for registro in select * from contratos
	      where contr_locador=locador and contr_locatario=locatario and contr_idsubt=idsubt
		and contr_estado=estado order by contr_unifun
	    loop
		if(char_length(ret)<1) then
		    ret:=registro.contr_unifun;
		  else
		    ret:=ret ||' -  '||registro.contr_unifun;
		end if;
	    end loop;


return ret;
end;$_$;


ALTER FUNCTION public.unifunes(integer, integer, integer, smallint) OWNER TO estlm;

--
-- Name: unifunesxd(integer, integer, integer, smallint, character varying); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION unifunesxd(integer, integer, integer, smallint, character varying) RETURNS character varying
    LANGUAGE plpgsql
    AS $_$
declare
locador		 alias for $1;
locatario	 alias for $2;
idsubt		 alias for $3;
estado		 alias for $4;
dispos		 alias for $5;
ret		 character varying;
registro	 record;
begin

	ret='';
	if dispos is not null then
	    for registro in select * from contratos
	      where contr_locador=locador and contr_locatario=locatario and contr_idsubt=idsubt
		and contr_estado=estado and bpchareq(trim(dispos),trim(contr_dispos)) order by contr_unifun
		loop
		    if(char_length(ret)<1) then
			ret:=registro.contr_unifun;
		      else
			ret:=ret ||' -  '||registro.contr_unifun;
		    end if;
		end loop;
	  else
	    for registro in select * from contratos
	      where contr_locador=locador and contr_locatario=locatario and contr_idsubt=idsubt
		and contr_estado=estado order by contr_unifun
		loop
		    if(char_length(ret)<1) then
			ret:=registro.contr_unifun;
		      else
			ret:=ret ||' -  '||registro.contr_unifun;
		    end if;
		end loop;
	end if;


return ret;
end;$_$;


ALTER FUNCTION public.unifunesxd(integer, integer, integer, smallint, character varying) OWNER TO estlm;

--
-- Name: usuario_inout(integer, date); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION usuario_inout(integer, date) RETURNS character
    LANGUAGE plpgsql
    AS $_$
declare
    idio		 alias for $1;
    fecha		 alias for $2;
    retval		varchar;

    begin
    retval:='TRAMITES';

    select nomusu(vt_usuario) into retval from visita where date(vt_fecin)=fecha and vt_inout=idio;
    if not found then
	select usudegte(io_gente) into retval from inout where io_id=idio;
    end if;

return retval;
END;$_$;


ALTER FUNCTION public.usuario_inout(integer, date) OWNER TO estlm;

--
-- Name: usucontrapart(integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION usucontrapart(integer, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
operacion	 alias for $1;
modo		 alias for $2;
directo		 int4;
indirecto	 int4;
deposito	 int4;
ret 		 int4;
begin

 SELECT  op_directo,op_indirecto,op_deposito  INTO  directo,indirecto,deposito    
    FROM operaciones   WHERE op_id= operacion+1;

if int4eq(modo,1) then ret:=directo; end if;
if int4eq(modo,2) then ret:=indirecto; end if;
if int4eq(modo,3) then ret:=deposito; end if;

return ret;
END;$_$;


ALTER FUNCTION public.usucontrapart(integer, integer) OWNER TO estlm;

--
-- Name: usureal_confactur(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION usureal_confactur(integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
cfcid		 alias for $1;
ret 		 int4;
auxreal		 int4;
auxusu 		 int4;

begin
    select cfc_usuario,cfc_usureal into auxusu,auxreal  
     from confactur where cfc_id=cfcid;

	if auxreal is null then 
		ret:=auxusu;
	    else
		ret:= auxreal;
	end if;

return ret;
end;$_$;


ALTER FUNCTION public.usureal_confactur(integer) OWNER TO estlm;

--
-- Name: val_talon(integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION val_talon(integer, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
tipoper		 alias for $1;
usuario		 alias for $2;
ret 		 int4;
begin

 SELECT  talop_numero  INTO     ret 
    FROM talonop   WHERE talop_usuario=usuario and talop_tipoper=tipoper;

return ret;
END;$_$;


ALTER FUNCTION public.val_talon(integer, integer) OWNER TO estlm;

--
-- Name: valmer_unifun(integer, smallint, smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION valmer_unifun(integer, smallint, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
DECLARE
operacion	ALIAS FOR $1; 	-- id de la operacion
caso		ALIAS FOR $2; 	-- Caso 
				--  1=arregla valormerca de unifun por ingreso
				--  2=arregla valormerca de unifun por egreso
modalidad	ALIAS FOR $3; 	-- Modalidad sumo o resto 
				--  1=actualizo normal
				--  2=Me arrepiento y corrijo lo ya hecho
compara 	numeric;
deposito 	int2;
registro 	RECORD;
retval 		boolean;
trans 		boolean;
aux_texto 	text;
BEGIN
retval:='t';		

if modalidad=1 then
	if caso=1 then
		for registro in select sitem_deposito as x,sum(sitem_imp_dolar) as y
    		    from subitem where sitem_idoper=operacion group by sitem_deposito
			loop
			    update unifun set unif_valormerca=unif_valormerca+registro.y
				where unif_codigo=registro.x;
			end loop; 
	    else
		for registro in select ret_idsitem as x,sum(ret_cantidad*precio_unitariod(ret_idsitem)) as y
    		    from retiros where ret_idopera=operacion group by x
			loop
			    select sitem_deposito into deposito from subitem where sitem_id=registro.x;
			    update unifun set unif_valormerca=unif_valormerca-registro.y
				where unif_codigo=deposito;
			end loop; 
	end if;

    else
	if caso=1 then
		for registro in select sitem_deposito as x,sum(sitem_imp_dolar) as y
    		    from subitem where sitem_idoper=operacion group by sitem_deposito
			loop
			    update unifun set unif_valormerca=unif_valormerca-registro.y
				where unif_codigo=registro.x;
			end loop; 
	    else
		for registro in select ret_idsitem as x,sum(ret_cantidad*precio_unitariod(ret_idsitem)) as y
    		    from retiros where ret_idopera=operacion group by x
			loop
			    select sitem_deposito into deposito from subitem where sitem_id=registro.x;
			    update unifun set unif_valormerca=unif_valormerca+registro.y
				where unif_codigo=deposito;
			end loop; 
	end if;
end if;


RETURN retval;
END;$_$;


ALTER FUNCTION public.valmer_unifun(integer, smallint, smallint) OWNER TO estlm;

--
-- Name: valmerxunif(smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION valmerxunif(smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
deposito	 alias for $1;
ret 		 boolean;
total 		 numeric;
depo 		 int2;
registro	 record;
begin

ret:='f';

if(int2eq(deposito,0::int2)) then
    for registro in select 
	sitem_deposito as depos, sum((sitem_canting-sitem_cantret)*(sitem_imp_dolar/sitem_canting)) as totals from subitem where sitem_estado=1 and estadop(sitem_idoper)=101 group by sitem_deposito
	loop
	    ret:='t';
	    update unifun set unif_valormerca=registro.totals where unif_codigo=registro.depos;
	end loop; 

else

    select sum((sitem_canting-sitem_cantret)*(sitem_imp_dolar/sitem_canting)) into total from subitem where sitem_estado=1 and sitem_deposito=deposito and estadop(sitem_idoper)=10;
    ret:='t';
    update unifun set unif_valormerca=total where unif_codigo=deposito;

end if;

return ret;
end;$_$;


ALTER FUNCTION public.valmerxunif(smallint) OWNER TO estlm;

--
-- Name: valor_moncte(smallint, date, numeric, numeric); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION valor_moncte(smallint, date, numeric, numeric) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
declare
moneda		 alias for $1;
fecha		 alias for $2;
cuanto		 alias for $3;
tipo_de_cambio	 alias for $4;
aux_mon		 int2;
cotiz		 numeric;
ret 		 numeric;
begin

 SELECT  var_valor 
 INTO     aux_mon -- Codigo Moneda Homogenea
    FROM varamb    WHERE var_codigo like 'MONH%';

if int2eq(aux_mon,moneda) then
	    ret:= cuanto;
   else
     if numeric_eq(tipo_de_cambio,0::numeric) then -- busco la cotizacion
	    cotiz:=trae_cotiza(moneda,fecha)::numeric;
	    if (cotiz is not null) then 
		    if (cotiz!=0) then 
			ret:=cuanto / cotiz;
		    end if;
		else
		    ret:=0;
	    end if;
	else

	    ret:= cuanto / tipo_de_cambio;

--	    cotiz:=trae_cotiza(1::int2,fecha)::numeric;
--	    if(cotiz) then 
--		    ret:= cuanto * (tipo_de_cambio / cotiz);
--		else
--		    ret:=0;
--	    end if;
    end if;

end if;

return ret;
END;$_$;


ALTER FUNCTION public.valor_moncte(smallint, date, numeric, numeric) OWNER TO estlm;

--
-- Name: valstock(integer, integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION valstock(integer, integer) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
DECLARE
    operacioni	ALIAS FOR $1; 	-- Operacion de ingreso
    operacione	ALIAS FOR $2; 	-- Operacion de egreso
    registro 	RECORD;
    registror 	RECORD;
    retirado	numeric;
    cantret		numeric;
    precio		numeric;
    retval 		numeric;
BEGIN

    retval:=0;
    for registror in select *
        from subitem where sitem_idoper=operacioni
	    loop
		retval:=retval+registror.sitem_imp_dolar;

		if(numeric_ne(registror.sitem_canting,0) and numeric_ne(registror.sitem_imp_dolar,0)) then
			precio:=registror.sitem_imp_dolar/registror.sitem_canting;
		    end if;

		if(registror.sitem_cantret is not null and registror.sitem_cantret!=0) then

		    select sum(ret_cantidad) into cantret from retiros where registror.sitem_id=ret_idsitem and ret_idopera=operacione;
		    if not found then 
			    retirado:=0;
			else
			    retirado:=cantret*precio;
		    end if;
		    if(retirado is not null and retirado!=0) then   retval:=retval-retirado; end if;
		end if;
	    end loop; 
retval:=retval::numeric(15,2);

RETURN retval;
END;$_$;


ALTER FUNCTION public.valstock(integer, integer) OWNER TO estlm;

--
-- Name: valtari(integer, integer, numeric, smallint, date); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION valtari(integer, integer, numeric, smallint, date) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
declare
usuario		 alias for $1;
articulo	 alias for $2;
canti		 alias for $3;
dias		 alias for $4;
fecha		 alias for $5;
ret 		 numeric;
paso 		 numeric;
paso5 		 numeric;
registro	 record;
regi		 record;
hay	 	 int4;
articulo5 	 int4;
coti 	 	 numeric;
importe 	 numeric;
begin

    for registro in select 
	    * from tarifas where tari_imp_dolar!=0 and tari_usuario=usuario and tari_idart=articulo and 
	    date_ge(tari_fhasta,fecha) and date_le(tari_fdesde,fecha) limit 1
	loop
	    if numeric_ne(canti,0::numeric) then
		if (registro.tari_cdesde is not null and registro.tari_chasta is not null and numeric_ge(registro.tari_chasta,canti) and numeric_le(registro.tari_cdesde,canti)) then
			paso=1;
		    else
			paso=0;
		end if;
	    end if; 

	    if int2ne(dias,0::int2) then
		if (registro.tari_ddesde is not null and registro.tari_dhasta is not null and int2ge(registro.tari_dhasta,dias) and int2le(registro.tari_ddesde,dias)) then
			paso=1;
		    else
			paso=0;
		end if;
	    end if; 

	    if paso is null then 
		paso=1; 
	    end if;

	    importe=registro.tari_imp_dolar;
	    select cot_cotiz into coti from cotiza where cot_moneda=1 order by cot_fecha desc limit 1;

	    if numeric_ge(coti,registro.tari_cot_dolar) then
		    ret= importe * coti * paso;
		else
		    ret= importe * registro.tari_cot_dolar * paso;
	    end if;
	end loop; 


    if ret is null then
    if int4ge(articulo,27) then
    if int4le(articulo,31) then
	articulo5=articulo - 5;
	for regi in select 
	    * from tarifas where tari_imp_dolar!=0 and tari_usuario=usuario and tari_idart=articulo5 and 
	    date_ge(tari_fhasta,fecha) and date_le(tari_fdesde,fecha) limit 1
	    loop
		if numeric_ne(canti,0::numeric) then
		    if (regi.tari_cdesde is not null and regi.tari_chasta is not null and numeric_ge(regi.tari_chasta,canti) and numeric_le(regi.tari_cdesde,canti)) then
			paso5=1;
		      else
			paso5=0;
		    end if;
		end if; 

		if int2ne(dias,0::int2) then
		    if (regi.tari_ddesde is not null and regi.tari_dhasta is not null and int2ge(regi.tari_dhasta,dias) and int2le(regi.tari_ddesde,dias)) then
			paso5=1;
		      else
			paso5=0;
		    end if;
		end if; 

		if paso5 is null then 
		    paso5=1; 
		end if;

		importe=regi.tari_imp_dolar;
		select cot_cotiz into coti from cotiza where cot_moneda=1 order by cot_fecha desc limit 1;

		if numeric_ge(coti,regi.tari_cot_dolar) then
		    ret= importe * coti * paso5;
		  else
		    ret= importe * regi.tari_cot_dolar * paso5;
		end if;
	    end loop; 
    end if;
    end if;
    end if;




	if ret is null then
	    select tari_importe into ret from tarifas where tari_usuario=usuario and tari_idart=articulo and 
	    date_ge(tari_fhasta,fecha) and date_le(tari_fdesde,fecha) limit 1;
	end if;

    if ret is null then
    if int4ge(articulo,27) then
    if int4le(articulo,31) then
	articulo5=articulo - 5;
	    select tari_importe into ret from tarifas where tari_usuario=usuario and tari_idart=articulo5 and 
	    date_ge(tari_fhasta,fecha) and date_le(tari_fdesde,fecha) limit 1;
    end if;
    end if;
    end if;


	if ret is null then
	    if int4eq(articulo,50) then ret=20; 
		else
		    if int4eq(articulo,35) then ret=38.20; 
			else
			    if int4eq(articulo,40) then ret=28.65; 
				else
				    ret=0; 
			    end if;
		    end if;
	    end if;
	end if;


return ret;
end;$_$;


ALTER FUNCTION public.valtari(integer, integer, numeric, smallint, date) OWNER TO estlm;

--
-- Name: valtarico(integer, integer, numeric, smallint, date, integer, smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION valtarico(integer, integer, numeric, smallint, date, integer, smallint) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
declare
usuario		 alias for $1;
articulo	 alias for $2;
canti		 alias for $3;
dias		 alias for $4;
fecha		 alias for $5;
contrato	 alias for $6;
orden		 alias for $7;
ret 		 numeric;
paso 		 numeric;
paso5 		 numeric;
registro	 record;
regi		 record;
hay	 	 int4;
articulo5 	 int4;
coti 	 	 numeric;
importe 	 numeric;
begin

    for registro in select 
	    * from tarifas where tari_imp_dolar!=0 and tari_usuario=usuario and tari_idart=articulo and 
	    date_ge(tari_fhasta,fecha) and date_le(tari_fdesde,fecha) and tari_idcontr=contrato and tari_orden=orden limit 1
	loop
	    if numeric_ne(canti,0::numeric) then
		if (registro.tari_cdesde is not null and registro.tari_chasta is not null and numeric_ge(registro.tari_chasta,canti) and numeric_le(registro.tari_cdesde,canti)) then
			paso=1;
		    else
			paso=0;
		end if;
	    end if; 

	    if int2ne(dias,0::int2) then
		if (registro.tari_ddesde is not null and registro.tari_dhasta is not null and int2ge(registro.tari_dhasta,dias) and int2le(registro.tari_ddesde,dias)) then
			paso=1;
		    else
			paso=0;
		end if;
	    end if; 

	    if paso is null then 
		paso=1; 
	    end if;

	    importe=registro.tari_imp_dolar;
	    select cot_cotiz into coti from cotiza where cot_moneda=1 order by cot_fecha desc limit 1;

	    if numeric_ge(coti,registro.tari_cot_dolar) then
		    ret= importe * coti * paso;
		else
		    ret= importe * registro.tari_cot_dolar * paso;
	    end if;
	end loop; 


    if ret is null then
    if int4ge(articulo,27) then
    if int4le(articulo,31) then
	articulo5=articulo - 5;
	for regi in select 
	    * from tarifas where tari_imp_dolar!=0 and tari_usuario=usuario and tari_idart=articulo5 and 
	    date_ge(tari_fhasta,fecha) and date_le(tari_fdesde,fecha) and tari_idcontr=contrato and tari_orden=orden limit 1
	    loop
		if numeric_ne(canti,0::numeric) then
		    if (regi.tari_cdesde is not null and regi.tari_chasta is not null and numeric_ge(regi.tari_chasta,canti) and numeric_le(regi.tari_cdesde,canti)) then
			paso5=1;
		      else
			paso5=0;
		    end if;
		end if; 

		if int2ne(dias,0::int2) then
		    if (regi.tari_ddesde is not null and regi.tari_dhasta is not null and int2ge(regi.tari_dhasta,dias) and int2le(regi.tari_ddesde,dias)) then
			paso5=1;
		      else
			paso5=0;
		    end if;
		end if; 

		if paso5 is null then 
		    paso5=1; 
		end if;

		importe=regi.tari_imp_dolar;
		select cot_cotiz into coti from cotiza where cot_moneda=1 order by cot_fecha desc limit 1;

		if numeric_ge(coti,regi.tari_cot_dolar) then
		    ret= importe * coti * paso5;
		  else
		    ret= importe * regi.tari_cot_dolar * paso5;
		end if;
	    end loop; 
    end if;
    end if;
    end if;




	if ret is null then
	    select tari_importe into ret from tarifas where tari_usuario=usuario and tari_idart=articulo and 
	    date_ge(tari_fhasta,fecha) and date_le(tari_fdesde,fecha) and tari_idcontr=contrato and tari_orden=orden limit 1;
	end if;

    if ret is null then
    if int4ge(articulo,27) then
    if int4le(articulo,31) then
	articulo5=articulo - 5;
	    select tari_importe into ret from tarifas where tari_usuario=usuario and tari_idart=articulo5 and 
	    date_ge(tari_fhasta,fecha) and date_le(tari_fdesde,fecha) and tari_idcontr=contrato and tari_orden=orden limit 1;
    end if;
    end if;
    end if;


	if ret is null then
	    if int4eq(articulo,50) then ret=20; 
		else
		    if int4eq(articulo,35) then ret=38.20; 
			else
			    if int4eq(articulo,40) then ret=28.65; 
				else
				    ret=0; 
			    end if;
		    end if;
	    end if;
	end if;


return ret;
end;$_$;


ALTER FUNCTION public.valtarico(integer, integer, numeric, smallint, date, integer, smallint) OWNER TO estlm;

--
-- Name: valvaramb(integer, integer, character varying); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION valvaramb(integer, integer, character varying) RETURNS character
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	codemp		ALIAS FOR $1; 
	ptovta		ALIAS FOR $2; 
	codigo		ALIAS FOR $3; 
	otro 		integer;
	retval 		varchar;
    BEGIN

    select vari_valor into retval from
    	 varambi where int4eq(ptovta,vari_idptov) and int4eq(codemp,vari_codemp) and bpchareq(codigo,vari_codigo);

    if not found then
	select vari_valor into retval from
    	    varambi where int4eq(0,vari_idptov) and int4eq(codemp,vari_codemp) and bpchareq(codigo,vari_codigo);
	if not found then
	    select vari_valor into retval from
    		varambi where int4eq(0,vari_idptov) and int4eq(0,vari_codemp) and bpchareq(codigo,vari_codigo);
	end if;
    end if;
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.valvaramb(integer, integer, character varying) OWNER TO estlm;

--
-- Name: veo_seg_disponible(integer); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION veo_seg_disponible(integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	operacion	ALIAS FOR $1; -- Operacion
 
	compara 	numeric;
	totals		numeric;
	aux_seg 	varchar;
	importe 	numeric;
	deposito	int2;
	retval 		boolean;

    BEGIN

	SELECT  var_valor  INTO     aux_seg 	
		    FROM varamb    WHERE var_codigo like 'SEGURO%';
	retval:='f';
	    
	if bpchareq(aux_seg,'NO') then
	    select op_deposito,op_impdolar into deposito,importe from operaciones where op_id=operacion;
	    select sum((sitem_canting-sitem_cantret-sitem_cantmala)*(sitem_imp_dolar/sitem_canting)) into totals from subitem where sitem_estado=1 and sitem_deposito=deposito and estadop(sitem_idoper)=101;
	    SELECT  unif_seguro - totals INTO compara FROM unifun WHERE unif_codigo = deposito;
	    if numeric_le(importe,compara) then
		retval:='t';
	      else
		retval:='f';
	    end if;

	  else
	    retval='t';

	end if;

    RETURN retval;
    END;$_$;


ALTER FUNCTION public.veo_seg_disponible(integer) OWNER TO estlm;

--
-- Name: verif_estado(integer, smallint, smallint); Type: FUNCTION; Schema: public; Owner: estlm
--

CREATE FUNCTION verif_estado(integer, smallint, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	operacion	ALIAS FOR $1; 	-- operacion
	estado		ALIAS FOR $2; 	-- estado
	modo		ALIAS FOR $3; 	-- 1 cambia estado
					-- Solo verifica sin cambiar estado 
	viejo_estado	int2;
	directo		int4;
	tipoper		int4;
	indirecto	int4;
	consig		int4;
	duedepo		int4;
	nrotalzon	int4;
	nrotaldir	int4;
	deposito	int2;
	importe		numeric;
	aux_texto 	text;
	mal		int2;
	trans 		boolean;
	trans1 		boolean;
	notid		int4;
	fobopera	numeric;
	foboperai	numeric;
	ret		boolean;
	registro	RECORD;
    BEGIN

select 	op_estado,op_tipoper,op_directo,op_indirecto,op_nrotalzon,op_nrotaldir,op_deposito,op_importe,op_consig
into viejo_estado,tipoper,directo,indirecto,nrotalzon,nrotaldir,deposito,importe,consig
	    from operaciones where op_id=operacion;

select unif_usuario into duedepo from unifun where unif_codigo=deposito;

if consig is null then
    consig:=-1;
end if;

------------------- I N G R E S O S


if(int4lt(tipoper,100::int2))  THEN 



------------------- PUBLICACION 
--falta ver los contratos por unidad funcional que salen de subitem

    if(( int2eq(estado,101::int2)and int2eq(viejo_estado,1::int2) )
	or 
	(int2eq(estado,102::int2)and int2eq(viejo_estado,101::int2) )
	or 
	(int2eq(estado,1::int2)and int2eq(viejo_estado,11::int2) )
		or
	(int2eq(estado,101::int2)and int2eq(viejo_estado,11::int2) )
		or
	(int2eq(estado,1::int2) and int2eq(viejo_estado,1::int2))) THEN 

	    delete from noticias where not_tipo=1 and not_numero=operacion;

	    if(int4eq(tipoper,10::int2) or int4eq(tipoper,30::int2))  THEN 
		foboperai:=fob_hijos1(operacion,2::int2);
		update operaciones set op_importe=foboperai,op_impdolar=foboperai WHERE op_id = operacion;
	    END IF;

	    if (hay_cont_valido(directo,indirecto,4::int2)!=true )THEN 
	    aux_texto:='En la Operacion '||traigo_simbtipoper(tipoper)||' '||nrotaldir||' no existe contrato entre el directo '||directo||'  ('||nomusu(directo) ||')     y el indirecto '||indirecto||'  ('||nomusu(indirecto)||')';
	    insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
	    END IF;

	    if (numeric_ne(fobpadre_vs_fobhijos(operacion,1::int2),0)) THEN 
		aux_texto:='En la Operacion '||traigo_simbtipoper(tipoper)||' '||nrotaldir||' el valor FOB de los SUBITEMS es distinto al FOB de la operacion, debera modificar este error antes de oficializar';
		insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
	    END IF;

	    if (seg_disponible(deposito, importe,1::int2)!=true) THEN 
		aux_texto:='En la Operacion '||traigo_simbtipoper(tipoper)||' '||nrotaldir||' el deposito '||deposito||'  ('||traigo_nomunifun(deposito::int2)||') no tiene el seguro necesario';
		insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
	    END IF;

	    trans1:=tipprod_ok(operacion,1::int2,2::int2);

	    if (int4ne(duedepo,directo)) THEN
		trans1:=hay_contrato(duedepo,directo,5::int2,operacion,5::int2);
	    END IF;
	    
	    if(tipoper=5 and consig=-1) then
		aux_texto:='En la Operacion '||traigo_simbtipoper(tipoper)||' '||nrotaldir||' no se ha definifo el consignatario';
		insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
	    END IF;


	    for registro in select itemdeitem(sitem_iditem) as item, sitem_codigo  from subitem where sitem_idoper=operacion and estadunif(sitem_deposito)=999 
		loop
		    aux_texto:='En la Operacion '||traigo_simbtipoper(tipoper)||' '||nrotaldir||' el Item '||registro.item ||' Subitem '||registro.sitem_codigo||' Se encuentra en un deposito INHABILITADO ';
		    insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
		end loop; 

	END IF;
	
    else

------------------- E G R E S O S
------------------- PUBLICACION 
        if ((int2eq(estado,101::int2) and int2eq(viejo_estado,1::int2)) 
		or 
    	    (int2eq(estado,102::int2) and int2eq(viejo_estado,101::int2))
		or 
	    (int2eq(estado,1::int2) and int2eq(viejo_estado,11::int2))
		or
	    (int2eq(estado,101::int2)and int2eq(viejo_estado,11::int2))
		or
	    (int2eq(estado,1::int2) and int2eq(viejo_estado,1::int2))) THEN 

	    delete from noticias where not_tipo=1 and not_numero=operacion;

	    if (hay_cont_valido(directo,indirecto,4::int2)!=true )THEN 
		aux_texto:='En la Operacion '||traigo_simbtipoper(tipoper)||' '||nrotaldir||' no existe contrato entre el directo '||directo||'  ('||nomusu(directo) ||')     y el indirecto '||indirecto||'  ('||nomusu(indirecto)||')';
		insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
	    END IF;

	    if ctacte_ok(directo)!=true THEN 
		aux_texto:='En la Operacion '||traigo_simbtipoper(tipoper)||' '||nrotaldir||' el usuario directo '||directo||'  ('||nomusu(directo) ||')  esta inhabilitado por falta de pago   ';
		insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
	    END IF;
	    
	    if(tipoper=105 and consig=-1) then
		aux_texto:='En la Operacion '||traigo_simbtipoper(tipoper)||' '||nrotaldir||' no se ha definifo el consignatario';
		insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
	    END IF;

	    fobopera:=fob_hijos2(operacion,2::int2);

	    for registro in select itemitemdesitem(ret_idsitem) as item, sitemcodigo(ret_idsitem) as sitem_codigo from retiros where ret_idopera=operacion and estadunif(depositem(ret_idsitem))=999 
		loop
		    aux_texto:='En la Operacion '||traigo_simbtipoper(tipoper)||' '||nrotaldir||' el Item '||registro.item ||' Subitem '||registro.sitem_codigo||' Se encuentra en un deposito INHABILITADO ';
		    insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
		end loop; 

	END IF;
END IF;

select not_id into notid from noticias where not_tipo=1 and not_numero=operacion;

if found then 
    	    ret:='f';
	    if(int2eq(estado,1::int2) and int2eq(viejo_estado,1::int2)) THEN 
		    update operaciones set op_estado=11::int2 WHERE op_id = operacion;
	    end if;

	else

	    ret:='t';

    	    if (int2eq(estado,101::int2) and int2eq(viejo_estado,1::int2) and (fobopera>0)) then
		update operaciones set op_impdolar=fobopera WHERE op_id = operacion;
	    end if;
	
	    if(int2eq(modo,1::int2)) then	
	    update operaciones set op_estado=estado WHERE op_id = operacion;
	    end if;

end if;

if int2eq(estado,999::int2) then
    update operaciones set op_estado=estado WHERE op_id = operacion;
end if;


RETURN ret;
END;$_$;


ALTER FUNCTION public.verif_estado(integer, smallint, smallint) OWNER TO estlm;

SET default_tablespace = '';

SET default_with_oids = true;

--
-- Name: aduanas; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE aduanas (
    adu_codigo smallint NOT NULL,
    adu_nombre character varying(160) NOT NULL
);


ALTER TABLE public.aduanas OWNER TO estlm;

--
-- Name: articvta; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE articvta (
    art_id integer NOT NULL,
    art_codemp integer NOT NULL,
    art_idptov integer,
    art_codigo character varying(160),
    art_tasa numeric(20,5) DEFAULT 0.21,
    art_stock numeric(20,5) DEFAULT 0,
    art_nivrep numeric(20,5) DEFAULT 0,
    art_unimed smallint,
    art_present numeric(20,5) DEFAULT 0,
    art_peso numeric(20,5) DEFAULT 0,
    art_estado smallint DEFAULT 1,
    art_codrub smallint,
    art_automatoper character varying(100),
    art_tipoper integer,
    art_precio_unique numeric(20,5) DEFAULT 0,
    art_nombre character varying(160),
    art_leyen text,
    art_siste smallint DEFAULT 1,
    art_tipo smallint DEFAULT 1,
    art_codsrb integer,
    art_codcbl integer,
    art_funcion text,
    art_precio numeric(20,5) DEFAULT 0,
    art_idcbl integer
);


ALTER TABLE public.articvta OWNER TO estlm;

--
-- Name: articvta_art_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE articvta_art_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.articvta_art_id_seq OWNER TO estlm;

--
-- Name: articvta_art_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE articvta_art_id_seq OWNED BY articvta.art_id;


--
-- Name: astoctas; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE astoctas (
    astc_id integer NOT NULL,
    astc_idastoh integer NOT NULL,
    astc_codemp integer NOT NULL,
    astc_idptov integer,
    astc_iddiv integer,
    astc_idcco integer,
    astc_comprob integer NOT NULL,
    astc_numero integer NOT NULL,
    astc_fecval date NOT NULL,
    astc_ctacble integer NOT NULL,
    astc_moneda smallint DEFAULT 1 NOT NULL,
    astc_valor numeric(20,2) DEFAULT 0,
    astc_cotiza numeric(20,5) DEFAULT 0,
    astc_importe numeric(20,2) DEFAULT 0 NOT NULL,
    astc_tipcta integer,
    astc_ctacte integer,
    astc_nucheq integer DEFAULT 0,
    astc_fecvto date,
    astc_estado smallint DEFAULT 1 NOT NULL,
    astc_cierra smallint DEFAULT 1 NOT NULL,
    astc_grupo integer DEFAULT 1 NOT NULL,
    astc_tasa numeric(20,5),
    astc_leyen character varying(160),
    astc_idashce integer
);


ALTER TABLE public.astoctas OWNER TO estlm;

--
-- Name: astoctas_astc_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE astoctas_astc_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.astoctas_astc_id_seq OWNER TO estlm;

--
-- Name: astoctas_astc_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE astoctas_astc_id_seq OWNED BY astoctas.astc_id;


--
-- Name: astoh; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE astoh (
    ash_id integer NOT NULL,
    ash_codemp integer NOT NULL,
    ash_idptov integer,
    ash_anio smallint NOT NULL,
    ash_mes smallint NOT NULL,
    ash_comprob integer NOT NULL,
    ash_numero integer NOT NULL,
    ash_fecomp date NOT NULL,
    ash_fecval date,
    ash_fecreg timestamp without time zone DEFAULT now() NOT NULL,
    ash_estado smallint DEFAULT 1,
    ash_idcpra integer,
    ash_idemiti integer,
    ash_nro2 integer,
    ash_leyen text,
    ash_operad integer,
    ash_date date,
    ash_titulo character varying(200)
);


ALTER TABLE public.astoh OWNER TO estlm;

--
-- Name: astoh_ash_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE astoh_ash_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.astoh_ash_id_seq OWNER TO estlm;

--
-- Name: astoh_ash_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE astoh_ash_id_seq OWNED BY astoh.ash_id;


--
-- Name: auxfe; Type: TABLE; Schema: public; Owner: zona; Tablespace: 
--

CREATE TABLE auxfe (
    fe_id integer NOT NULL,
    fe_idcli integer NOT NULL,
    fe_cuit character varying(11) NOT NULL,
    fe_cbte smallint DEFAULT 1 NOT NULL,
    fe_ptovta smallint DEFAULT 1 NOT NULL,
    fe_nograv numeric(15,2),
    fe_grav numeric(15,2),
    fe_ivatot numeric(15,2),
    fe_total numeric(15,2),
    fe_tributo numeric(15,2),
    fe_ivaex numeric(15,2),
    fe_iva21 numeric(15,2),
    fe_iva105 numeric(15,2),
    fe_fechaf character varying(8),
    fe_iniserv character varying(8),
    fe_finserv character varying(8),
    fe_fechavp character varying(8),
    fe_cae character varying(14),
    fe_fechavtocae character varying(8),
    fe_numero integer,
    fe_estado integer DEFAULT 1 NOT NULL,
    fe_errores text
);


ALTER TABLE public.auxfe OWNER TO zona;

--
-- Name: auxfe_fe_id_seq; Type: SEQUENCE; Schema: public; Owner: zona
--

CREATE SEQUENCE auxfe_fe_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.auxfe_fe_id_seq OWNER TO zona;

--
-- Name: auxfe_fe_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: zona
--

ALTER SEQUENCE auxfe_fe_id_seq OWNED BY auxfe.fe_id;


--
-- Name: bancos; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE bancos (
    bco_codigo smallint NOT NULL,
    bco_nombre character varying(160) NOT NULL,
    bco_estado smallint DEFAULT 1
);


ALTER TABLE public.bancos OWNER TO estlm;

--
-- Name: catego; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE catego (
    cat_codigo integer NOT NULL,
    cat_nombre character varying(160) NOT NULL
);


ALTER TABLE public.catego OWNER TO estlm;

--
-- Name: catego_cat_codigo_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE catego_cat_codigo_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.catego_cat_codigo_seq OWNER TO estlm;

--
-- Name: catego_cat_codigo_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE catego_cat_codigo_seq OWNED BY catego.cat_codigo;


SET default_with_oids = false;

--
-- Name: catemple; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE catemple (
    ce_codigo smallint NOT NULL,
    ce_nombre character varying(160) NOT NULL
);


ALTER TABLE public.catemple OWNER TO estlm;

--
-- Name: cblexasi; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE cblexasi (
    cxa_codemp integer NOT NULL,
    cxa_tipasi integer NOT NULL,
    cxa_cble integer NOT NULL
);


ALTER TABLE public.cblexasi OWNER TO estlm;

SET default_with_oids = true;

--
-- Name: centroc; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE centroc (
    cco_id integer NOT NULL,
    cco_codemp integer NOT NULL,
    cco_idptov integer NOT NULL,
    cco_iddiv integer NOT NULL,
    cco_codigo smallint NOT NULL,
    cco_nombre character varying(160)
);


ALTER TABLE public.centroc OWNER TO estlm;

--
-- Name: centroc_cco_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE centroc_cco_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.centroc_cco_id_seq OWNER TO estlm;

--
-- Name: centroc_cco_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE centroc_cco_id_seq OWNED BY centroc.cco_id;


--
-- Name: cheques; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE cheques (
    chq_id integer NOT NULL,
    chq_codbco smallint NOT NULL,
    chq_nucheq integer NOT NULL,
    chq_codemp integer NOT NULL,
    chq_idptov integer,
    chq_idastoc integer NOT NULL,
    chq_fechaem date,
    chq_fecheq date NOT NULL,
    chq_moneda smallint DEFAULT 1 NOT NULL,
    chq_importe numeric(20,2) DEFAULT 0 NOT NULL,
    chq_estado smallint DEFAULT 1 NOT NULL,
    chq_nrcuit character varying(20),
    chq_ctacte integer,
    chq_idastoce integer,
    chq_observ text
);


ALTER TABLE public.cheques OWNER TO estlm;

--
-- Name: cheques_chq_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE cheques_chq_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.cheques_chq_id_seq OWNER TO estlm;

--
-- Name: cheques_chq_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE cheques_chq_id_seq OWNED BY cheques.chq_id;


--
-- Name: clientes; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE clientes (
    cli_id integer NOT NULL,
    cli_codemp integer NOT NULL,
    cli_idptov integer,
    cli_codigo character varying(40) NOT NULL,
    cli_nrcuit character varying(20) NOT NULL,
    cli_tipcli smallint,
    cli_nombre character varying(160),
    cli_fantasy character varying(160),
    cli_nomabre character varying(40),
    cli_coniva smallint NOT NULL,
    cli_descto numeric(20,5) DEFAULT 0,
    cli_conpag integer,
    cli_catego integer,
    cli_limcred numeric(20,2) DEFAULT 0,
    cli_interes numeric(20,5) DEFAULT 0,
    cli_grupo integer,
    cli_saldo numeric(20,2),
    cli_estado smallint DEFAULT 1 NOT NULL,
    cli_modfac smallint DEFAULT 1
);


ALTER TABLE public.clientes OWNER TO estlm;

--
-- Name: clientes_cli_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE clientes_cli_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.clientes_cli_id_seq OWNER TO estlm;

--
-- Name: clientes_cli_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE clientes_cli_id_seq OWNED BY clientes.cli_id;


--
-- Name: compra; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE compra (
    cpra_id integer NOT NULL,
    cpra_idastoh integer NOT NULL,
    cpra_codemp integer NOT NULL,
    cpra_idptov integer,
    cpra_comprob integer NOT NULL,
    cpra_numero integer NOT NULL,
    cpra_prove integer,
    cpra_lecomp character varying(2),
    cpra_sucomp smallint,
    cpra_nucomp integer,
    cpra_fecori date,
    cpra_fecval date,
    cpra_fecvto date,
    cpra_estado smallint DEFAULT 1 NOT NULL,
    cpra_nomprov character varying(160),
    cpra_nrcuit character varying(20),
    cpra_coniva smallint,
    cpra_total numeric(20,2) DEFAULT 0
);


ALTER TABLE public.compra OWNER TO estlm;

--
-- Name: compra_cpra_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE compra_cpra_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.compra_cpra_id_seq OWNER TO estlm;

--
-- Name: compra_cpra_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE compra_cpra_id_seq OWNED BY compra.cpra_id;


--
-- Name: comprob; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE comprob (
    comp_id integer NOT NULL,
    comp_codemp integer NOT NULL,
    comp_idptov integer,
    comp_codigo character(10) NOT NULL,
    comp_nombre character varying(160) NOT NULL,
    comp_sistem smallint DEFAULT 1,
    comp_siste smallint DEFAULT 4,
    comp_credeb smallint DEFAULT 1,
    comp_stcksn smallint DEFAULT 1,
    comp_tipo smallint DEFAULT 1,
    comp_intext smallint DEFAULT 1,
    comp_cuenta integer,
    comp_talon integer,
    comp_copias integer,
    comp_letra character varying(3),
    comp_leyen text
);


ALTER TABLE public.comprob OWNER TO estlm;

--
-- Name: comprob_comp_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE comprob_comp_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.comprob_comp_id_seq OWNER TO estlm;

--
-- Name: comprob_comp_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE comprob_comp_id_seq OWNED BY comprob.comp_id;


--
-- Name: coniva; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE coniva (
    iva_codigo smallint NOT NULL,
    iva_nombre character varying(160) NOT NULL,
    iva_tasa numeric(20,5) DEFAULT 0,
    iva_stasa numeric(20,5) DEFAULT 0,
    iva_discrim smallint DEFAULT 1,
    iva_estado integer DEFAULT 1
);


ALTER TABLE public.coniva OWNER TO estlm;

--
-- Name: conpag; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE conpag (
    cdp_codigo integer NOT NULL,
    cdp_codemp integer NOT NULL,
    cdp_nombre character varying(160) NOT NULL,
    cdp_dias smallint
);


ALTER TABLE public.conpag OWNER TO estlm;

--
-- Name: conpag_cdp_codigo_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE conpag_cdp_codigo_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.conpag_cdp_codigo_seq OWNER TO estlm;

--
-- Name: conpag_cdp_codigo_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE conpag_cdp_codigo_seq OWNED BY conpag.cdp_codigo;


SET default_with_oids = false;

--
-- Name: convmult; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE convmult (
    cmt_codemp integer NOT NULL,
    cmt_provin integer NOT NULL,
    cmt_tasa numeric(15,5) DEFAULT 0 NOT NULL,
    cmt_coef numeric(15,5) DEFAULT 0
);


ALTER TABLE public.convmult OWNER TO estlm;

SET default_with_oids = true;

--
-- Name: cotiza; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE cotiza (
    cot_codemp integer DEFAULT (-1) NOT NULL,
    cot_moneda smallint NOT NULL,
    cot_fecha date NOT NULL,
    cot_cotiz numeric(20,6) DEFAULT 1 NOT NULL
);


ALTER TABLE public.cotiza OWNER TO estlm;

--
-- Name: ctacble; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE ctacble (
    cbl_id integer NOT NULL,
    cbl_codemp integer,
    cbl_codigo character varying(60) NOT NULL,
    cbl_nombre character varying(160) NOT NULL,
    cbl_identi integer,
    cbl_nivel integer,
    cbl_posic integer,
    cbl_asigna integer DEFAULT 1,
    cbl_moneda smallint DEFAULT 1 NOT NULL,
    cbl_tipcta integer,
    cbl_monetaria smallint DEFAULT 1,
    cbl_ajuste smallint DEFAULT 1,
    cbl_indice smallint DEFAULT 1,
    cbl_ctarei integer,
    cbl_ctaaju integer,
    cbl_leyed character varying(160),
    cbl_leyeh character varying(160),
    cbl_present character varying(60)
);


ALTER TABLE public.ctacble OWNER TO estlm;

--
-- Name: ctacble_cbl_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE ctacble_cbl_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.ctacble_cbl_id_seq OWNER TO estlm;

--
-- Name: ctacble_cbl_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE ctacble_cbl_id_seq OWNED BY ctacble.cbl_id;


--
-- Name: ctes; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE ctes (
    cte_id integer NOT NULL,
    cte_codemp integer NOT NULL,
    cte_tipcta integer NOT NULL,
    cte_tipct smallint,
    cte_codigo integer NOT NULL,
    cte_nombre character varying(160),
    cte_idtal integer,
    cte_estado smallint DEFAULT 1
);


ALTER TABLE public.ctes OWNER TO estlm;

--
-- Name: ctes_cte_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE ctes_cte_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.ctes_cte_id_seq OWNER TO estlm;

--
-- Name: ctes_cte_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE ctes_cte_id_seq OWNED BY ctes.cte_id;


--
-- Name: division; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE division (
    div_id integer NOT NULL,
    div_codemp integer NOT NULL,
    div_idptov integer NOT NULL,
    div_codigo smallint NOT NULL,
    div_nombre character varying(160)
);


ALTER TABLE public.division OWNER TO estlm;

--
-- Name: division_div_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE division_div_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.division_div_id_seq OWNER TO estlm;

--
-- Name: division_div_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE division_div_id_seq OWNED BY division.div_id;


--
-- Name: docum; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE docum (
    doc_id integer NOT NULL,
    doc_codemp integer NOT NULL,
    doc_idptov integer,
    doc_idastoc integer NOT NULL,
    doc_numero integer NOT NULL,
    doc_fechaem date,
    doc_fecdoc date NOT NULL,
    doc_moneda smallint DEFAULT 1 NOT NULL,
    doc_importe numeric(20,2) DEFAULT 0 NOT NULL,
    doc_estado smallint DEFAULT 1 NOT NULL,
    doc_nrcuit character varying(20),
    doc_ctacte integer,
    doc_idastoce integer,
    doc_observ text
);


ALTER TABLE public.docum OWNER TO estlm;

--
-- Name: docum_doc_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE docum_doc_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.docum_doc_id_seq OWNER TO estlm;

--
-- Name: docum_doc_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE docum_doc_id_seq OWNED BY docum.doc_id;


--
-- Name: emiti; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE emiti (
    emi_id integer NOT NULL,
    emi_idastoh integer NOT NULL,
    emi_codemp integer NOT NULL,
    emi_idptov integer,
    emi_comprob integer NOT NULL,
    emi_numero integer NOT NULL,
    emi_fecval date,
    emi_grupo integer,
    emi_conpag integer,
    emi_codcli integer,
    emi_succli integer,
    emi_nomcli character varying(160),
    emi_conivac smallint,
    emi_nrcuit character varying(20),
    emi_vended integer,
    emi_provin integer,
    emi_estlm integer,
    emi_desre numeric(20,2) DEFAULT 0,
    emi_total numeric(20,2) DEFAULT 0,
    emi_retiro integer,
    emi_estado smallint DEFAULT 1,
    emi_leyen text,
    emi_idfe integer,
    emi_cae character varying(14)
);


ALTER TABLE public.emiti OWNER TO estlm;

--
-- Name: emiti_emi_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE emiti_emi_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.emiti_emi_id_seq OWNER TO estlm;

--
-- Name: emiti_emi_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE emiti_emi_id_seq OWNED BY emiti.emi_id;


SET default_with_oids = false;

--
-- Name: empleados; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE empleados (
    e_id integer NOT NULL,
    e_codemp integer NOT NULL,
    e_legajo integer NOT NULL,
    e_nombre character varying(160),
    e_sexo integer DEFAULT 1,
    e_fecnac date,
    e_estciv integer DEFAULT 1,
    e_tipdoc character varying(10),
    e_nrodoc integer,
    e_nacion integer DEFAULT 200,
    e_cuil numeric(14,0),
    e_catego integer DEFAULT 1,
    e_fecing date,
    e_estado integer DEFAULT 1,
    e_turno integer DEFAULT 1,
    e_objetivo integer,
    e_horaing time without time zone,
    e_horaegr time without time zone
);


ALTER TABLE public.empleados OWNER TO estlm;

--
-- Name: empleados_e_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE empleados_e_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.empleados_e_id_seq OWNER TO estlm;

--
-- Name: empleados_e_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE empleados_e_id_seq OWNED BY empleados.e_id;


SET default_with_oids = true;

--
-- Name: empresa; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE empresa (
    emp_codigo integer NOT NULL,
    emp_nombre character varying(160),
    emp_direcc character varying(160),
    emp_locali character varying(160),
    emp_codpos character varying(10),
    emp_provin integer DEFAULT 1,
    emp_pais smallint DEFAULT 200,
    emp_nrcuit character varying(20) NOT NULL,
    emp_estado smallint DEFAULT 1,
    emp_codact character varying(60),
    emp_descact character varying(160),
    emp_respons character varying(160),
    emp_respcargo character varying(160),
    emp_nroanses character varying(60),
    emp_nroigj character varying(60),
    emp_fecigj date,
    emp_vtocont date DEFAULT '2028-12-31'::date,
    emp_tipo smallint DEFAULT 1,
    emp_coniva smallint DEFAULT 1,
    emp_anti date DEFAULT date(now()),
    emp_fecint date,
    emp_grupo integer DEFAULT 1,
    emp_redond smallint DEFAULT 0,
    emp_nomabr character varying(10),
    emp_codcli integer DEFAULT 1,
    emp_codprov integer DEFAULT 1
);


ALTER TABLE public.empresa OWNER TO estlm;

SET default_with_oids = false;

--
-- Name: estcivil; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE estcivil (
    ec_codigo smallint NOT NULL,
    ec_nombre character varying(160) NOT NULL
);


ALTER TABLE public.estcivil OWNER TO estlm;

SET default_with_oids = true;

--
-- Name: evindi; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE evindi (
    evi_indice smallint NOT NULL,
    evi_fecha date NOT NULL,
    evi_valor numeric(20,5) DEFAULT 1
);


ALTER TABLE public.evindi OWNER TO estlm;

--
-- Name: firman; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE firman (
    fir_id integer NOT NULL,
    fir_codemp integer NOT NULL,
    fir_nrcuit character varying(20) NOT NULL,
    fir_nombre character varying(160) NOT NULL,
    fir_direcc character varying(160),
    fir_locali character varying(160),
    fir_codpos character varying(10),
    fir_provin integer,
    fir_pais smallint,
    fir_estado smallint DEFAULT 1,
    fir_observ text
);


ALTER TABLE public.firman OWNER TO estlm;

--
-- Name: firman_fir_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE firman_fir_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.firman_fir_id_seq OWNER TO estlm;

--
-- Name: firman_fir_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE firman_fir_id_seq OWNED BY firman.fir_id;


--
-- Name: grupos; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE grupos (
    gpo_id integer NOT NULL,
    gpo_nombre character varying(160) NOT NULL
);


ALTER TABLE public.grupos OWNER TO estlm;

--
-- Name: grupos_gpo_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE grupos_gpo_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.grupos_gpo_id_seq OWNER TO estlm;

--
-- Name: grupos_gpo_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE grupos_gpo_id_seq OWNED BY grupos.gpo_id;


--
-- Name: impresiones; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE impresiones (
    imp_codigo smallint NOT NULL,
    imp_name text,
    imp_query text,
    imp_enscript text,
    imp_filter text,
    imp_shell text
);


ALTER TABLE public.impresiones OWNER TO estlm;

--
-- Name: indices; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE indices (
    ind_codigo smallint NOT NULL,
    ind_nombre character varying(160) NOT NULL
);


ALTER TABLE public.indices OWNER TO estlm;

--
-- Name: interes; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE interes (
    int_codemp integer NOT NULL,
    int_fecha date DEFAULT date(now()) NOT NULL,
    int_valor numeric(20,5) DEFAULT 0
);


ALTER TABLE public.interes OWNER TO estlm;

--
-- Name: listpre; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE listpre (
    ltp_id integer NOT NULL,
    ltp_codemp integer NOT NULL,
    ltp_idcli integer,
    ltp_nrolista integer,
    ltp_idart integer NOT NULL,
    ltp_orden integer,
    ltp_precio numeric(20,5) DEFAULT 0
);


ALTER TABLE public.listpre OWNER TO estlm;

--
-- Name: listpre_ltp_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE listpre_ltp_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.listpre_ltp_id_seq OWNER TO estlm;

--
-- Name: listpre_ltp_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE listpre_ltp_id_seq OWNED BY listpre.ltp_id;


--
-- Name: moneda; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE moneda (
    mon_codigo smallint NOT NULL,
    mon_nombre character varying(160) NOT NULL,
    mon_simbol character varying(5)
);


ALTER TABLE public.moneda OWNER TO estlm;

--
-- Name: monex; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE monex (
    mne_id integer NOT NULL,
    mne_codemp integer NOT NULL,
    mne_idastoc integer NOT NULL,
    mne_moneda smallint NOT NULL,
    mne_numero character varying(30),
    mne_valor numeric(20,2),
    mne_estado smallint DEFAULT 1,
    mne_idastoce integer
);


ALTER TABLE public.monex OWNER TO estlm;

--
-- Name: monex_mne_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE monex_mne_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.monex_mne_id_seq OWNER TO estlm;

--
-- Name: monex_mne_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE monex_mne_id_seq OWNED BY monex.mne_id;


--
-- Name: movsto; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE movsto (
    movs_id integer NOT NULL,
    movs_codemp integer NOT NULL,
    movs_idptov integer,
    movs_idastoh integer NOT NULL,
    movs_idemiti integer NOT NULL,
    movs_fecval date,
    movs_artic integer NOT NULL,
    movs_canti numeric(20,5) DEFAULT 0,
    movs_dias numeric(20,2) DEFAULT 0,
    movs_precio numeric(20,2) DEFAULT 0,
    movs_importe numeric(20,2) DEFAULT 0,
    movs_tasa numeric(20,5) DEFAULT 0,
    movs_peso numeric(20,2) DEFAULT 0,
    movs_volum numeric(20,2) DEFAULT 0,
    movs_entreg numeric(20,2) DEFAULT 0,
    movs_fecrep date,
    movs_estado smallint DEFAULT 1,
    movs_codcli integer,
    movs_indir integer,
    movs_clireal integer,
    movs_idoper integer,
    movs_ticket integer,
    movs_leyen text,
    movs_origen integer,
    movs_destino integer,
    movs_compbte character varying(16)
);


ALTER TABLE public.movsto OWNER TO estlm;

--
-- Name: movsto_movs_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE movsto_movs_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.movsto_movs_id_seq OWNER TO estlm;

--
-- Name: movsto_movs_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE movsto_movs_id_seq OWNED BY movsto.movs_id;


--
-- Name: movstoc; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE movstoc (
    movc_id integer NOT NULL,
    movc_codemp integer NOT NULL,
    movc_idptov integer,
    movc_idastoh integer NOT NULL,
    movc_idcompra integer NOT NULL,
    movc_fecval date,
    movc_artic integer,
    movc_canti numeric(20,5) DEFAULT 0,
    movc_precio numeric(20,2) DEFAULT 0,
    movc_importe numeric(20,2) DEFAULT 0,
    movc_tasa numeric(20,5) DEFAULT 0,
    movc_peso numeric(20,2) DEFAULT 0,
    movc_volum numeric(20,2) DEFAULT 0,
    movc_entreg numeric(20,2) DEFAULT 0,
    movc_fecrep date,
    movc_estado smallint DEFAULT 1,
    movc_codpro integer,
    movc_leyen text
);


ALTER TABLE public.movstoc OWNER TO estlm;

--
-- Name: movstoc_movc_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE movstoc_movc_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.movstoc_movc_id_seq OWNER TO estlm;

--
-- Name: movstoc_movc_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE movstoc_movc_id_seq OWNED BY movstoc.movc_id;


--
-- Name: notdeb; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE notdeb (
    nd_id integer NOT NULL,
    nd_codemp integer NOT NULL,
    nd_idptov integer,
    nd_idastoh integer NOT NULL,
    nd_fecval date,
    nd_grupo integer,
    nd_codcli integer,
    nd_estado integer DEFAULT 1,
    nd_tpago numeric(20,2) DEFAULT 0,
    nd_tnd numeric(20,2) DEFAULT 0,
    nd_interes numeric(20,2) DEFAULT 0,
    nd_operadb integer
);


ALTER TABLE public.notdeb OWNER TO estlm;

--
-- Name: notdeb_nd_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE notdeb_nd_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.notdeb_nd_id_seq OWNER TO estlm;

--
-- Name: notdeb_nd_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE notdeb_nd_id_seq OWNED BY notdeb.nd_id;


SET default_with_oids = false;

--
-- Name: novemple; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE novemple (
    ne_id integer NOT NULL,
    ne_codemp integer NOT NULL,
    ne_idemple integer NOT NULL,
    ne_legajo integer,
    ne_fecha date,
    ne_objetivo integer,
    ne_mes integer,
    ne_anio integer,
    ne_horasd numeric(15,2),
    ne_horash numeric(15,2),
    ne_vales numeric(15,2),
    ne_estado integer DEFAULT 1
);


ALTER TABLE public.novemple OWNER TO estlm;

--
-- Name: novemple_ne_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE novemple_ne_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.novemple_ne_id_seq OWNER TO estlm;

--
-- Name: novemple_ne_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE novemple_ne_id_seq OWNED BY novemple.ne_id;


SET default_with_oids = true;

--
-- Name: operadores; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE operadores (
    operad_id integer NOT NULL,
    operad_nombre character varying(160) NOT NULL,
    operad_pass character varying(40) NOT NULL,
    operad_sector character varying(160),
    operad_estado smallint DEFAULT 1 NOT NULL,
    operad_nivaut1 character(2) DEFAULT 'NO'::bpchar NOT NULL,
    operad_nivaut2 character(2) DEFAULT 'NO'::bpchar NOT NULL,
    operad_count smallint DEFAULT 1 NOT NULL,
    operad_grupo smallint,
    operad_cliente smallint,
    operad_login character varying(40) NOT NULL,
    operad_last date DEFAULT date(now()),
    operad_contacto character varying(190),
    operad_telefono character varying(190),
    operad_codemp integer,
    operad_ptovta integer
);


ALTER TABLE public.operadores OWNER TO estlm;

--
-- Name: operadores_operad_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE operadores_operad_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.operadores_operad_id_seq OWNER TO estlm;

--
-- Name: operadores_operad_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE operadores_operad_id_seq OWNED BY operadores.operad_id;


--
-- Name: pais; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE pais (
    pai_codigo smallint NOT NULL,
    pai_nombre character varying(160) NOT NULL
);


ALTER TABLE public.pais OWNER TO estlm;

--
-- Name: posaran; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE posaran (
    posa_codigo character varying(15) NOT NULL,
    posa_nombre character varying(160) NOT NULL
);


ALTER TABLE public.posaran OWNER TO estlm;

--
-- Name: prove; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE prove (
    prov_id integer NOT NULL,
    prov_codemp integer,
    prov_idptov integer,
    prov_nrcuit character varying(20),
    prov_codigo character varying(40),
    prov_nombre character varying(160),
    prov_direcc character varying(160),
    prov_locali character varying(160),
    prov_provin integer DEFAULT 1 NOT NULL,
    prov_pais smallint DEFAULT 200 NOT NULL,
    prov_estado smallint DEFAULT 1 NOT NULL,
    prov_direce character varying(160),
    prov_observ text,
    prov_grupo integer DEFAULT 1,
    prov_tipo integer DEFAULT 1,
    prov_coniva integer DEFAULT 1,
    prov_retig integer DEFAULT 1,
    prov_codpos character varying
);


ALTER TABLE public.prove OWNER TO estlm;

--
-- Name: prove_prov_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE prove_prov_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.prove_prov_id_seq OWNER TO estlm;

--
-- Name: prove_prov_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE prove_prov_id_seq OWNED BY prove.prov_id;


--
-- Name: provin; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE provin (
    pro_codigo integer NOT NULL,
    pro_nombre character varying(160) NOT NULL,
    pro_tasa numeric(20,5) DEFAULT 0,
    pro_coef numeric(20,5) DEFAULT 0,
    pro_valor numeric(20,2) DEFAULT 0
);


ALTER TABLE public.provin OWNER TO estlm;

--
-- Name: provin_pro_codigo_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE provin_pro_codigo_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.provin_pro_codigo_seq OWNER TO estlm;

--
-- Name: provin_pro_codigo_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE provin_pro_codigo_seq OWNED BY provin.pro_codigo;


--
-- Name: ptovta; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE ptovta (
    ptv_id integer NOT NULL,
    ptv_codemp integer,
    ptv_codigo integer NOT NULL,
    ptv_nombre character varying(160),
    ptv_direcc character varying(160),
    ptv_locali character varying(160),
    ptv_codpos character varying(10),
    ptv_provin integer,
    ptv_pais smallint,
    ptv_estado smallint DEFAULT 1,
    ptv_codact character varying(60),
    ptv_descact character varying(160),
    ptv_porcib numeric(15,5)
);


ALTER TABLE public.ptovta OWNER TO estlm;

--
-- Name: ptovta_ptv_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE ptovta_ptv_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.ptovta_ptv_id_seq OWNER TO estlm;

--
-- Name: ptovta_ptv_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE ptovta_ptv_id_seq OWNED BY ptovta.ptv_id;


--
-- Name: seccion; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE seccion (
    sec_codigo smallint NOT NULL,
    sec_nombre character varying(160) NOT NULL
);


ALTER TABLE public.seccion OWNER TO estlm;

SET default_with_oids = false;

--
-- Name: sexo; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE sexo (
    sex_codigo smallint NOT NULL,
    sex_nombre character varying(160) NOT NULL
);


ALTER TABLE public.sexo OWNER TO estlm;

--
-- Name: subd; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE subd (
    subd_id integer NOT NULL,
    subd_codemp integer NOT NULL,
    subd_idptov integer,
    subd_nombre character varying(160),
    subd_titulo character varying(160),
    subd_fecd date,
    subd_fech date,
    subd_estado smallint DEFAULT 1 NOT NULL,
    subd_proxnum integer,
    subd_orden integer,
    subd_dia integer
);


ALTER TABLE public.subd OWNER TO estlm;

--
-- Name: subd_subd_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE subd_subd_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.subd_subd_id_seq OWNER TO estlm;

--
-- Name: subd_subd_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE subd_subd_id_seq OWNED BY subd.subd_id;


--
-- Name: subxcomp; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE subxcomp (
    subxc_idsub integer NOT NULL,
    subxc_comprob integer NOT NULL,
    subxc_codemp integer
);


ALTER TABLE public.subxcomp OWNER TO estlm;

SET default_with_oids = true;

--
-- Name: sucursalc; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE sucursalc (
    sucu_cliente integer NOT NULL,
    sucu_codigo smallint DEFAULT 1 NOT NULL,
    sucu_nombre character varying(160) NOT NULL,
    sucu_direcc character varying(160),
    sucu_locali character varying(160),
    sucu_codpos character varying(15),
    sucu_provin integer,
    sucu_pais smallint,
    sucu_repres character varying(160),
    sucu_contacto character varying(160),
    sucu_observ text,
    sucu_direccl character varying(160),
    sucu_localil character varying(160),
    sucu_codposl character varying(15),
    sucu_codprovl integer,
    sucu_paisl smallint
);


ALTER TABLE public.sucursalc OWNER TO estlm;

--
-- Name: sucursalp; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE sucursalp (
    suc_prove integer NOT NULL,
    suc_codigo smallint DEFAULT 1 NOT NULL,
    suc_nombre character varying(160) NOT NULL,
    suc_direcc character varying(160),
    suc_locali character varying(160),
    suc_codpos character varying(15),
    suc_codprov integer,
    suc_pais smallint,
    suc_repres character varying(160),
    suc_contacto character varying(160),
    suc_observ text,
    suc_direccl character varying(160),
    suc_localil character varying(160),
    suc_codposl character varying(15),
    suc_codprovl integer,
    suc_paisl smallint
);


ALTER TABLE public.sucursalp OWNER TO estlm;

--
-- Name: talon; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE talon (
    tal_id integer NOT NULL,
    tal_codemp integer NOT NULL,
    tal_idptov integer,
    tal_comprob integer,
    tal_nombre character varying(160) NOT NULL,
    tal_valor integer,
    tal_fecha date,
    tal_estado smallint DEFAULT 1,
    tal_vald integer DEFAULT 1,
    tal_valh integer DEFAULT 100000,
    tal_fecvto date DEFAULT '2028-12-31'::date
);


ALTER TABLE public.talon OWNER TO estlm;

--
-- Name: talon_tal_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE talon_tal_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.talon_tal_id_seq OWNER TO estlm;

--
-- Name: talon_tal_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE talon_tal_id_seq OWNED BY talon.tal_id;


--
-- Name: telefon; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE telefon (
    tel_id integer NOT NULL,
    tel_codemp integer NOT NULL,
    tel_tipent integer NOT NULL,
    tel_codigo integer NOT NULL,
    tel_tiptel integer NOT NULL,
    tel_contact character varying(160) NOT NULL,
    tel_leyen text,
    tel_dato character varying(300)
);


ALTER TABLE public.telefon OWNER TO estlm;

--
-- Name: telefon_tel_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE telefon_tel_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.telefon_tel_id_seq OWNER TO estlm;

--
-- Name: telefon_tel_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE telefon_tel_id_seq OWNED BY telefon.tel_id;


SET default_with_oids = false;

--
-- Name: tipasi; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE tipasi (
    tas_codemp integer NOT NULL,
    tas_codigo integer NOT NULL,
    tas_nombre character varying(160) NOT NULL
);


ALTER TABLE public.tipasi OWNER TO estlm;

SET default_with_oids = true;

--
-- Name: tipcta; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE tipcta (
    tct_codigo integer NOT NULL,
    tct_nombre character varying(160) NOT NULL
);


ALTER TABLE public.tipcta OWNER TO estlm;

--
-- Name: tipcta_tct_codigo_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE tipcta_tct_codigo_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.tipcta_tct_codigo_seq OWNER TO estlm;

--
-- Name: tipcta_tct_codigo_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE tipcta_tct_codigo_seq OWNED BY tipcta.tct_codigo;


--
-- Name: tipdocu; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE tipdocu (
    td_codigo character varying(5) NOT NULL,
    td_nombre character varying(160) NOT NULL
);


ALTER TABLE public.tipdocu OWNER TO estlm;

--
-- Name: tipemp; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE tipemp (
    tem_codigo smallint NOT NULL,
    tem_nombre character varying(160) NOT NULL
);


ALTER TABLE public.tipemp OWNER TO estlm;

--
-- Name: tipentid; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE tipentid (
    tet_codigo integer NOT NULL,
    tet_nombre character varying(30) NOT NULL
);


ALTER TABLE public.tipentid OWNER TO estlm;

--
-- Name: tipentid_tet_codigo_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE tipentid_tet_codigo_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.tipentid_tet_codigo_seq OWNER TO estlm;

--
-- Name: tipentid_tet_codigo_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE tipentid_tet_codigo_seq OWNED BY tipentid.tet_codigo;


--
-- Name: tiptel; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE tiptel (
    ttl_codigo integer NOT NULL,
    ttl_nombre character varying(160) NOT NULL
);


ALTER TABLE public.tiptel OWNER TO estlm;

--
-- Name: tiptel_ttl_codigo_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE tiptel_ttl_codigo_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.tiptel_ttl_codigo_seq OWNER TO estlm;

--
-- Name: tiptel_ttl_codigo_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE tiptel_ttl_codigo_seq OWNED BY tiptel.ttl_codigo;


--
-- Name: unimed; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE unimed (
    uni_codigo smallint NOT NULL,
    uni_coef numeric(20,5) DEFAULT 0,
    uni_nombre character varying(160),
    uni_simbolo character varying(160)
);


ALTER TABLE public.unimed OWNER TO estlm;

--
-- Name: varambi; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE varambi (
    vari_codemp integer DEFAULT 0 NOT NULL,
    vari_idptov integer DEFAULT 0 NOT NULL,
    vari_codigo character varying(160) NOT NULL,
    vari_nombre character varying(160) NOT NULL,
    vari_valor character varying(160),
    vari_tipo integer DEFAULT 1
);


ALTER TABLE public.varambi OWNER TO estlm;

SET default_with_oids = false;

--
-- Name: vencimiento; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE vencimiento (
    vto_id integer NOT NULL,
    vto_codemp integer NOT NULL,
    vto_idptov integer,
    vto_fecvto date,
    vto_proxvto date,
    vto_leyen text,
    vto_cuotan integer,
    vto_cuotad integer,
    vto_importe numeric(15,2) DEFAULT 0,
    vto_estado integer DEFAULT 1 NOT NULL,
    vto_ctacble integer,
    vto_idastoh integer
);


ALTER TABLE public.vencimiento OWNER TO estlm;

--
-- Name: vencimiento_vto_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE vencimiento_vto_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.vencimiento_vto_id_seq OWNER TO estlm;

--
-- Name: vencimiento_vto_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE vencimiento_vto_id_seq OWNED BY vencimiento.vto_id;


SET default_with_oids = true;

--
-- Name: vendedor; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE vendedor (
    ven_id integer NOT NULL,
    ven_codemp integer NOT NULL,
    ven_nombre character varying(160) NOT NULL,
    ven_direcc character varying(160),
    ven_locali character varying(160),
    ven_codpos character varying(10),
    ven_provin integer,
    ven_pais smallint,
    ven_nrcuit character varying(20),
    ven_estado smallint DEFAULT 1,
    ven_comis numeric(20,5) DEFAULT 0
);


ALTER TABLE public.vendedor OWNER TO estlm;

--
-- Name: vendedor_ven_id_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE vendedor_ven_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.vendedor_ven_id_seq OWNER TO estlm;

--
-- Name: vendedor_ven_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE vendedor_ven_id_seq OWNED BY vendedor.ven_id;


--
-- Name: zona; Type: TABLE; Schema: public; Owner: estlm; Tablespace: 
--

CREATE TABLE zona (
    zon_codigo integer NOT NULL,
    zon_codemp integer NOT NULL,
    zon_pais integer,
    zon_provin smallint,
    zon_ciudad integer,
    zon_barrio integer,
    zon_nombre character varying(160) NOT NULL
);


ALTER TABLE public.zona OWNER TO estlm;

--
-- Name: zona_zon_codigo_seq; Type: SEQUENCE; Schema: public; Owner: estlm
--

CREATE SEQUENCE zona_zon_codigo_seq
    START WITH 1
    INCREMENT BY 1
    NO MAXVALUE
    NO MINVALUE
    CACHE 1;


ALTER TABLE public.zona_zon_codigo_seq OWNER TO estlm;

--
-- Name: zona_zon_codigo_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: estlm
--

ALTER SEQUENCE zona_zon_codigo_seq OWNED BY zona.zon_codigo;


--
-- Name: art_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY articvta ALTER COLUMN art_id SET DEFAULT nextval('articvta_art_id_seq'::regclass);


--
-- Name: astc_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY astoctas ALTER COLUMN astc_id SET DEFAULT nextval('astoctas_astc_id_seq'::regclass);


--
-- Name: ash_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY astoh ALTER COLUMN ash_id SET DEFAULT nextval('astoh_ash_id_seq'::regclass);


--
-- Name: fe_id; Type: DEFAULT; Schema: public; Owner: zona
--

ALTER TABLE ONLY auxfe ALTER COLUMN fe_id SET DEFAULT nextval('auxfe_fe_id_seq'::regclass);


--
-- Name: cat_codigo; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY catego ALTER COLUMN cat_codigo SET DEFAULT nextval('catego_cat_codigo_seq'::regclass);


--
-- Name: cco_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY centroc ALTER COLUMN cco_id SET DEFAULT nextval('centroc_cco_id_seq'::regclass);


--
-- Name: chq_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY cheques ALTER COLUMN chq_id SET DEFAULT nextval('cheques_chq_id_seq'::regclass);


--
-- Name: cli_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY clientes ALTER COLUMN cli_id SET DEFAULT nextval('clientes_cli_id_seq'::regclass);


--
-- Name: cpra_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY compra ALTER COLUMN cpra_id SET DEFAULT nextval('compra_cpra_id_seq'::regclass);


--
-- Name: comp_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY comprob ALTER COLUMN comp_id SET DEFAULT nextval('comprob_comp_id_seq'::regclass);


--
-- Name: cdp_codigo; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY conpag ALTER COLUMN cdp_codigo SET DEFAULT nextval('conpag_cdp_codigo_seq'::regclass);


--
-- Name: cbl_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY ctacble ALTER COLUMN cbl_id SET DEFAULT nextval('ctacble_cbl_id_seq'::regclass);


--
-- Name: cte_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY ctes ALTER COLUMN cte_id SET DEFAULT nextval('ctes_cte_id_seq'::regclass);


--
-- Name: div_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY division ALTER COLUMN div_id SET DEFAULT nextval('division_div_id_seq'::regclass);


--
-- Name: doc_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY docum ALTER COLUMN doc_id SET DEFAULT nextval('docum_doc_id_seq'::regclass);


--
-- Name: emi_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY emiti ALTER COLUMN emi_id SET DEFAULT nextval('emiti_emi_id_seq'::regclass);


--
-- Name: e_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY empleados ALTER COLUMN e_id SET DEFAULT nextval('empleados_e_id_seq'::regclass);


--
-- Name: fir_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY firman ALTER COLUMN fir_id SET DEFAULT nextval('firman_fir_id_seq'::regclass);


--
-- Name: gpo_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY grupos ALTER COLUMN gpo_id SET DEFAULT nextval('grupos_gpo_id_seq'::regclass);


--
-- Name: ltp_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY listpre ALTER COLUMN ltp_id SET DEFAULT nextval('listpre_ltp_id_seq'::regclass);


--
-- Name: mne_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY monex ALTER COLUMN mne_id SET DEFAULT nextval('monex_mne_id_seq'::regclass);


--
-- Name: movs_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY movsto ALTER COLUMN movs_id SET DEFAULT nextval('movsto_movs_id_seq'::regclass);


--
-- Name: movc_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY movstoc ALTER COLUMN movc_id SET DEFAULT nextval('movstoc_movc_id_seq'::regclass);


--
-- Name: nd_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY notdeb ALTER COLUMN nd_id SET DEFAULT nextval('notdeb_nd_id_seq'::regclass);


--
-- Name: ne_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY novemple ALTER COLUMN ne_id SET DEFAULT nextval('novemple_ne_id_seq'::regclass);


--
-- Name: operad_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY operadores ALTER COLUMN operad_id SET DEFAULT nextval('operadores_operad_id_seq'::regclass);


--
-- Name: prov_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY prove ALTER COLUMN prov_id SET DEFAULT nextval('prove_prov_id_seq'::regclass);


--
-- Name: pro_codigo; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY provin ALTER COLUMN pro_codigo SET DEFAULT nextval('provin_pro_codigo_seq'::regclass);


--
-- Name: ptv_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY ptovta ALTER COLUMN ptv_id SET DEFAULT nextval('ptovta_ptv_id_seq'::regclass);


--
-- Name: subd_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY subd ALTER COLUMN subd_id SET DEFAULT nextval('subd_subd_id_seq'::regclass);


--
-- Name: tal_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY talon ALTER COLUMN tal_id SET DEFAULT nextval('talon_tal_id_seq'::regclass);


--
-- Name: tel_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY telefon ALTER COLUMN tel_id SET DEFAULT nextval('telefon_tel_id_seq'::regclass);


--
-- Name: tct_codigo; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY tipcta ALTER COLUMN tct_codigo SET DEFAULT nextval('tipcta_tct_codigo_seq'::regclass);


--
-- Name: tet_codigo; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY tipentid ALTER COLUMN tet_codigo SET DEFAULT nextval('tipentid_tet_codigo_seq'::regclass);


--
-- Name: ttl_codigo; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY tiptel ALTER COLUMN ttl_codigo SET DEFAULT nextval('tiptel_ttl_codigo_seq'::regclass);


--
-- Name: vto_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY vencimiento ALTER COLUMN vto_id SET DEFAULT nextval('vencimiento_vto_id_seq'::regclass);


--
-- Name: ven_id; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY vendedor ALTER COLUMN ven_id SET DEFAULT nextval('vendedor_ven_id_seq'::regclass);


--
-- Name: zon_codigo; Type: DEFAULT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY zona ALTER COLUMN zon_codigo SET DEFAULT nextval('zona_zon_codigo_seq'::regclass);


--
-- Name: aduanas_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY aduanas
    ADD CONSTRAINT aduanas_pkey PRIMARY KEY (adu_codigo);


--
-- Name: articvta_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY articvta
    ADD CONSTRAINT articvta_pkey PRIMARY KEY (art_id);


--
-- Name: astoctas_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY astoctas
    ADD CONSTRAINT astoctas_pkey PRIMARY KEY (astc_id);


--
-- Name: astoh_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY astoh
    ADD CONSTRAINT astoh_pkey PRIMARY KEY (ash_id);


--
-- Name: auxfe_pkey; Type: CONSTRAINT; Schema: public; Owner: zona; Tablespace: 
--

ALTER TABLE ONLY auxfe
    ADD CONSTRAINT auxfe_pkey PRIMARY KEY (fe_id);


--
-- Name: bancos_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY bancos
    ADD CONSTRAINT bancos_pkey PRIMARY KEY (bco_codigo);


--
-- Name: catego_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY catego
    ADD CONSTRAINT catego_pkey PRIMARY KEY (cat_codigo);


--
-- Name: catemple_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY catemple
    ADD CONSTRAINT catemple_pkey PRIMARY KEY (ce_codigo);


--
-- Name: cblexasi_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY cblexasi
    ADD CONSTRAINT cblexasi_pkey PRIMARY KEY (cxa_codemp, cxa_tipasi, cxa_cble);


--
-- Name: centroc_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY centroc
    ADD CONSTRAINT centroc_pkey PRIMARY KEY (cco_id);


--
-- Name: cheques_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY cheques
    ADD CONSTRAINT cheques_pkey PRIMARY KEY (chq_id);


--
-- Name: clientes_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY clientes
    ADD CONSTRAINT clientes_pkey PRIMARY KEY (cli_id);


--
-- Name: compra_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY compra
    ADD CONSTRAINT compra_pkey PRIMARY KEY (cpra_id);


--
-- Name: comprob_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY comprob
    ADD CONSTRAINT comprob_pkey PRIMARY KEY (comp_id);


--
-- Name: coniva_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY coniva
    ADD CONSTRAINT coniva_pkey PRIMARY KEY (iva_codigo);


--
-- Name: conpag_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY conpag
    ADD CONSTRAINT conpag_pkey PRIMARY KEY (cdp_codigo);


--
-- Name: convmult_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY convmult
    ADD CONSTRAINT convmult_pkey PRIMARY KEY (cmt_codemp, cmt_provin);


--
-- Name: cotiza_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY cotiza
    ADD CONSTRAINT cotiza_pkey PRIMARY KEY (cot_codemp, cot_moneda, cot_fecha);


--
-- Name: ctacble_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY ctacble
    ADD CONSTRAINT ctacble_pkey PRIMARY KEY (cbl_id);


--
-- Name: ctes_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY ctes
    ADD CONSTRAINT ctes_pkey PRIMARY KEY (cte_id);


--
-- Name: division_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY division
    ADD CONSTRAINT division_pkey PRIMARY KEY (div_id);


--
-- Name: docum_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY docum
    ADD CONSTRAINT docum_pkey PRIMARY KEY (doc_id);


--
-- Name: emiti_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY emiti
    ADD CONSTRAINT emiti_pkey PRIMARY KEY (emi_id);


--
-- Name: empleados_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY empleados
    ADD CONSTRAINT empleados_pkey PRIMARY KEY (e_id);


--
-- Name: empresa_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY empresa
    ADD CONSTRAINT empresa_pkey PRIMARY KEY (emp_codigo);


--
-- Name: estcivil_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY estcivil
    ADD CONSTRAINT estcivil_pkey PRIMARY KEY (ec_codigo);


--
-- Name: estlm_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY zona
    ADD CONSTRAINT estlm_pkey PRIMARY KEY (zon_codigo);


--
-- Name: evindi_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY evindi
    ADD CONSTRAINT evindi_pkey PRIMARY KEY (evi_indice, evi_fecha);


--
-- Name: firman_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY firman
    ADD CONSTRAINT firman_pkey PRIMARY KEY (fir_id);


--
-- Name: grupos_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY grupos
    ADD CONSTRAINT grupos_pkey PRIMARY KEY (gpo_id);


--
-- Name: impresiones_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY impresiones
    ADD CONSTRAINT impresiones_pkey PRIMARY KEY (imp_codigo);


--
-- Name: indices_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY indices
    ADD CONSTRAINT indices_pkey PRIMARY KEY (ind_codigo);


--
-- Name: interes_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY interes
    ADD CONSTRAINT interes_pkey PRIMARY KEY (int_codemp, int_fecha);


--
-- Name: listpre_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY listpre
    ADD CONSTRAINT listpre_pkey PRIMARY KEY (ltp_id);


--
-- Name: moneda_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY moneda
    ADD CONSTRAINT moneda_pkey PRIMARY KEY (mon_codigo);


--
-- Name: monex_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY monex
    ADD CONSTRAINT monex_pkey PRIMARY KEY (mne_id);


--
-- Name: movsto_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY movsto
    ADD CONSTRAINT movsto_pkey PRIMARY KEY (movs_id);


--
-- Name: movstoc_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY movstoc
    ADD CONSTRAINT movstoc_pkey PRIMARY KEY (movc_id);


--
-- Name: notdeb_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY notdeb
    ADD CONSTRAINT notdeb_pkey PRIMARY KEY (nd_id);


--
-- Name: novemple_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY novemple
    ADD CONSTRAINT novemple_pkey PRIMARY KEY (ne_id);


--
-- Name: operadores_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY operadores
    ADD CONSTRAINT operadores_pkey PRIMARY KEY (operad_id);


--
-- Name: pais_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY pais
    ADD CONSTRAINT pais_pkey PRIMARY KEY (pai_codigo);


--
-- Name: posaran_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY posaran
    ADD CONSTRAINT posaran_pkey PRIMARY KEY (posa_codigo);


--
-- Name: prove_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY prove
    ADD CONSTRAINT prove_pkey PRIMARY KEY (prov_id);


--
-- Name: provin_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY provin
    ADD CONSTRAINT provin_pkey PRIMARY KEY (pro_codigo);


--
-- Name: ptovta_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY ptovta
    ADD CONSTRAINT ptovta_pkey PRIMARY KEY (ptv_id);


--
-- Name: seccion_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY seccion
    ADD CONSTRAINT seccion_pkey PRIMARY KEY (sec_codigo);


--
-- Name: sexo_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY sexo
    ADD CONSTRAINT sexo_pkey PRIMARY KEY (sex_codigo);


--
-- Name: subxcomp_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY subxcomp
    ADD CONSTRAINT subxcomp_pkey PRIMARY KEY (subxc_idsub, subxc_comprob);


--
-- Name: sucursalc_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY sucursalc
    ADD CONSTRAINT sucursalc_pkey PRIMARY KEY (sucu_cliente, sucu_codigo);


--
-- Name: sucursalp_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY sucursalp
    ADD CONSTRAINT sucursalp_pkey PRIMARY KEY (suc_prove, suc_codigo);


--
-- Name: talon_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY talon
    ADD CONSTRAINT talon_pkey PRIMARY KEY (tal_id);


--
-- Name: telefon_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY telefon
    ADD CONSTRAINT telefon_pkey PRIMARY KEY (tel_id);


--
-- Name: tipasi_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY tipasi
    ADD CONSTRAINT tipasi_pkey PRIMARY KEY (tas_codemp, tas_codigo);


--
-- Name: tipcta_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY tipcta
    ADD CONSTRAINT tipcta_pkey PRIMARY KEY (tct_codigo);


--
-- Name: tipdocu_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY tipdocu
    ADD CONSTRAINT tipdocu_pkey PRIMARY KEY (td_codigo);


--
-- Name: tipemp_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY tipemp
    ADD CONSTRAINT tipemp_pkey PRIMARY KEY (tem_codigo);


--
-- Name: tipentid_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY tipentid
    ADD CONSTRAINT tipentid_pkey PRIMARY KEY (tet_codigo);


--
-- Name: tiptel_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY tiptel
    ADD CONSTRAINT tiptel_pkey PRIMARY KEY (ttl_codigo);


--
-- Name: unimed_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY unimed
    ADD CONSTRAINT unimed_pkey PRIMARY KEY (uni_codigo);


--
-- Name: varambi_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY varambi
    ADD CONSTRAINT varambi_pkey PRIMARY KEY (vari_codemp, vari_idptov, vari_codigo);


--
-- Name: vendedor_pkey; Type: CONSTRAINT; Schema: public; Owner: estlm; Tablespace: 
--

ALTER TABLE ONLY vendedor
    ADD CONSTRAINT vendedor_pkey PRIMARY KEY (ven_id);


--
-- Name: empleados_objetivosd; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE UNIQUE INDEX empleados_objetivosd ON novemple USING btree (ne_codemp, ne_objetivo, ne_fecha, ne_legajo, ne_horasd);


--
-- Name: empleados_objetivosh; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE UNIQUE INDEX empleados_objetivosh ON novemple USING btree (ne_codemp, ne_objetivo, ne_fecha, ne_legajo, ne_horash);


--
-- Name: idx_articvta_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE UNIQUE INDEX idx_articvta_1 ON articvta USING btree (art_codemp, art_codigo);


--
-- Name: idx_astoctas_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_astoctas_1 ON astoctas USING btree (astc_idastoh);


--
-- Name: idx_astoctas_10; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_astoctas_10 ON astoctas USING btree (astc_codemp, astc_idptov, astc_tipcta, astc_ctacte);


--
-- Name: idx_astoctas_11; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_astoctas_11 ON astoctas USING btree (astc_codemp, astc_idptov, astc_tipcta, astc_ctacte, astc_cierra, astc_fecval);


--
-- Name: idx_astoctas_12; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_astoctas_12 ON astoctas USING btree (astc_codemp, astc_ctacble, astc_moneda);


--
-- Name: idx_astoctas_13; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_astoctas_13 ON astoctas USING btree (astc_codemp, astc_idptov, astc_ctacble, astc_estado, astc_fecval);


--
-- Name: idx_astoctas_14; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_astoctas_14 ON astoctas USING btree (astc_codemp, astc_ctacble, astc_estado, astc_fecval);


--
-- Name: idx_astoctas_15; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_astoctas_15 ON astoctas USING btree (astc_codemp, astc_estado, astc_tipcta, astc_ctacte);


--
-- Name: idx_astoctas_2; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_astoctas_2 ON astoctas USING btree (astc_codemp, astc_ctacble, astc_fecval);


--
-- Name: idx_astoctas_3; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_astoctas_3 ON astoctas USING btree (astc_codemp, astc_idptov, astc_ctacble, astc_fecval);


--
-- Name: idx_astoctas_4; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_astoctas_4 ON astoctas USING btree (astc_codemp, astc_ctacble, astc_ctacte, astc_fecval);


--
-- Name: idx_astoctas_5; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_astoctas_5 ON astoctas USING btree (astc_codemp, astc_ctacble, astc_ctacte, astc_cierra, astc_fecval);


--
-- Name: idx_astoctas_6; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_astoctas_6 ON astoctas USING btree (astc_codemp, astc_ctacble, astc_ctacte, astc_cierra, astc_fecvto);


--
-- Name: idx_astoctas_7; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_astoctas_7 ON astoctas USING btree (astc_ctacble, astc_fecval);


--
-- Name: idx_astoctas_8; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_astoctas_8 ON astoctas USING btree (astc_codemp, astc_idptov, astc_ctacble, astc_ctacte, astc_grupo);


--
-- Name: idx_astoctas_9; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_astoctas_9 ON astoctas USING btree (astc_codemp, astc_idptov, astc_comprob, astc_numero);


--
-- Name: idx_astoh_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE UNIQUE INDEX idx_astoh_1 ON astoh USING btree (ash_codemp, ash_idptov, ash_comprob, ash_numero);


--
-- Name: idx_astoh_2; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_astoh_2 ON astoh USING btree (ash_codemp, ash_anio, ash_mes, ash_fecomp);


--
-- Name: idx_astoh_3; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_astoh_3 ON astoh USING btree (ash_codemp, ash_idptov, ash_anio, ash_mes, ash_fecomp);


--
-- Name: idx_astoh_4; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_astoh_4 ON astoh USING btree (ash_idemiti);


--
-- Name: idx_astoh_5; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_astoh_5 ON astoh USING btree (ash_idcpra);


--
-- Name: idx_auxfe_1; Type: INDEX; Schema: public; Owner: zona; Tablespace: 
--

CREATE INDEX idx_auxfe_1 ON auxfe USING btree (fe_estado, fe_fechaf, fe_idcli);


--
-- Name: idx_centroc_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE UNIQUE INDEX idx_centroc_1 ON centroc USING btree (cco_codemp, cco_idptov, cco_iddiv, cco_codigo);


--
-- Name: idx_cheques_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_cheques_1 ON cheques USING btree (chq_codemp, chq_estado);


--
-- Name: idx_cheques_10; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_cheques_10 ON cheques USING btree (chq_moneda, chq_codemp, chq_estado, chq_fecheq);


--
-- Name: idx_cheques_2; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_cheques_2 ON cheques USING btree (chq_codemp, chq_idptov, chq_estado);


--
-- Name: idx_cheques_3; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_cheques_3 ON cheques USING btree (chq_codbco, chq_nucheq);


--
-- Name: idx_cheques_4; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_cheques_4 ON cheques USING btree (chq_idastoc);


--
-- Name: idx_cheques_5; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_cheques_5 ON cheques USING btree (chq_idastoce);


--
-- Name: idx_cheques_6; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_cheques_6 ON cheques USING btree (chq_estado);


--
-- Name: idx_cheques_7; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_cheques_7 ON cheques USING btree (chq_codemp, chq_estado, chq_fecheq);


--
-- Name: idx_cheques_8; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_cheques_8 ON cheques USING btree (chq_estado, chq_fecheq);


--
-- Name: idx_cheques_9; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_cheques_9 ON cheques USING btree (chq_moneda);


--
-- Name: idx_clientes_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE UNIQUE INDEX idx_clientes_1 ON clientes USING btree (cli_codemp, cli_idptov, cli_codigo);


--
-- Name: idx_clientes_2; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_clientes_2 ON clientes USING btree (cli_codemp, cli_codigo);


--
-- Name: idx_clientes_3; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_clientes_3 ON clientes USING btree (cli_nrcuit);


--
-- Name: idx_clientes_4; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_clientes_4 ON clientes USING btree (cli_nombre);


--
-- Name: idx_compra_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE UNIQUE INDEX idx_compra_1 ON compra USING btree (cpra_codemp, cpra_idptov, cpra_comprob, cpra_numero);


--
-- Name: idx_compra_2; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_compra_2 ON compra USING btree (cpra_codemp, cpra_fecval);


--
-- Name: idx_compra_3; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_compra_3 ON compra USING btree (cpra_idastoh);


--
-- Name: idx_comprob_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE UNIQUE INDEX idx_comprob_1 ON comprob USING btree (comp_codemp, comp_idptov, comp_codigo);


--
-- Name: idx_comprob_2; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_comprob_2 ON comprob USING btree (comp_codemp, comp_idptov, comp_siste, comp_codigo);


--
-- Name: idx_conpag_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_conpag_1 ON conpag USING btree (cdp_codemp, cdp_codigo);


--
-- Name: idx_ctacble_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE UNIQUE INDEX idx_ctacble_1 ON ctacble USING btree (cbl_codemp, cbl_codigo);


--
-- Name: idx_ctacble_2; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_ctacble_2 ON ctacble USING btree (cbl_codemp, cbl_posic);


--
-- Name: idx_ctes_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE UNIQUE INDEX idx_ctes_1 ON ctes USING btree (cte_codemp, cte_tipcta, cte_tipct, cte_codigo);


--
-- Name: idx_division_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE UNIQUE INDEX idx_division_1 ON division USING btree (div_codemp, div_idptov, div_codigo);


--
-- Name: idx_docum_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_docum_1 ON docum USING btree (doc_codemp, doc_nrcuit);


--
-- Name: idx_docum_2; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_docum_2 ON docum USING btree (doc_codemp, doc_estado, doc_nrcuit);


--
-- Name: idx_docum_3; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_docum_3 ON docum USING btree (doc_codemp, doc_idptov, doc_estado);


--
-- Name: idx_docum_4; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_docum_4 ON docum USING btree (doc_idastoc);


--
-- Name: idx_docum_5; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_docum_5 ON docum USING btree (doc_idastoce);


--
-- Name: idx_docum_6; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_docum_6 ON docum USING btree (doc_codemp, doc_estado);


--
-- Name: idx_emiti_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE UNIQUE INDEX idx_emiti_1 ON emiti USING btree (emi_codemp, emi_idptov, emi_comprob, emi_numero);


--
-- Name: idx_emiti_2; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_emiti_2 ON emiti USING btree (emi_codemp, emi_fecval);


--
-- Name: idx_emiti_3; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_emiti_3 ON emiti USING btree (emi_idastoh);


--
-- Name: idx_empleados_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE UNIQUE INDEX idx_empleados_1 ON empleados USING btree (e_codemp, e_legajo);


--
-- Name: idx_empleados_2; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_empleados_2 ON empleados USING btree (e_codemp, e_nombre);


--
-- Name: idx_empresa_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE UNIQUE INDEX idx_empresa_1 ON empresa USING btree (emp_nrcuit);


--
-- Name: idx_firman_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE UNIQUE INDEX idx_firman_1 ON firman USING btree (fir_codemp, fir_nrcuit);


--
-- Name: idx_firman_2; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_firman_2 ON firman USING btree (fir_nrcuit);


--
-- Name: idx_listpre_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_listpre_1 ON listpre USING btree (ltp_codemp, ltp_idcli, ltp_idart, ltp_orden);


--
-- Name: idx_listpre_2; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_listpre_2 ON listpre USING btree (ltp_codemp, ltp_idcli, ltp_nrolista, ltp_idart, ltp_orden);


--
-- Name: idx_monex_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_monex_1 ON monex USING btree (mne_idastoc);


--
-- Name: idx_monex_2; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_monex_2 ON monex USING btree (mne_idastoce);


--
-- Name: idx_movsto_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_movsto_1 ON movsto USING btree (movs_idemiti);


--
-- Name: idx_movsto_2; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_movsto_2 ON movsto USING btree (movs_idastoh);


--
-- Name: idx_movsto_3; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_movsto_3 ON movsto USING btree (movs_artic);


--
-- Name: idx_movsto_4; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_movsto_4 ON movsto USING btree (movs_codemp, movs_idptov, movs_artic);


--
-- Name: idx_movsto_5; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_movsto_5 ON movsto USING btree (movs_idastoh, movs_artic);


--
-- Name: idx_movstoc_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_movstoc_1 ON movstoc USING btree (movc_idcompra);


--
-- Name: idx_movstoc_2; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_movstoc_2 ON movstoc USING btree (movc_idastoh);


--
-- Name: idx_movstoc_3; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_movstoc_3 ON movstoc USING btree (movc_artic);


--
-- Name: idx_movstoc_4; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_movstoc_4 ON movstoc USING btree (movc_codemp, movc_idptov, movc_artic);


--
-- Name: idx_movstoc_5; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_movstoc_5 ON movstoc USING btree (movc_idastoh, movc_artic);


--
-- Name: idx_novemplne_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_novemplne_1 ON novemple USING btree (ne_codemp, ne_legajo);


--
-- Name: idx_novemplne_2; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_novemplne_2 ON novemple USING btree (ne_codemp, ne_fecha);


--
-- Name: idx_operadores_2; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE UNIQUE INDEX idx_operadores_2 ON operadores USING btree (operad_login);


--
-- Name: idx_prove_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE UNIQUE INDEX idx_prove_1 ON prove USING btree (prov_codemp, prov_nrcuit);


--
-- Name: idx_prove_2; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_prove_2 ON prove USING btree (prov_nrcuit);


--
-- Name: idx_prove_3; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_prove_3 ON prove USING btree (prov_codemp, prov_codigo);


--
-- Name: idx_ptovta_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE UNIQUE INDEX idx_ptovta_1 ON ptovta USING btree (ptv_codemp, ptv_codigo);


--
-- Name: idx_subd_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_subd_1 ON subd USING btree (subd_codemp, subd_idptov);


--
-- Name: idx_talon_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE UNIQUE INDEX idx_talon_1 ON talon USING btree (tal_idptov, tal_comprob);


--
-- Name: idx_telefon_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_telefon_1 ON telefon USING btree (tel_codemp, tel_tipent, tel_codigo, tel_tiptel);


--
-- Name: idx_telefon_2; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_telefon_2 ON telefon USING btree (tel_dato);


--
-- Name: idx_telefon_3; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_telefon_3 ON telefon USING btree (tel_contact);


--
-- Name: idx_vencimiento_1; Type: INDEX; Schema: public; Owner: estlm; Tablespace: 
--

CREATE INDEX idx_vencimiento_1 ON vencimiento USING btree (vto_codemp, vto_estado);


--
-- Name: ai_astoctas; Type: TRIGGER; Schema: public; Owner: estlm
--

CREATE TRIGGER ai_astoctas
    AFTER INSERT ON astoctas
    FOR EACH ROW
    EXECUTE PROCEDURE f_ai_astoctas();


--
-- Name: ai_clientes; Type: TRIGGER; Schema: public; Owner: estlm
--

CREATE TRIGGER ai_clientes
    AFTER INSERT ON clientes
    FOR EACH ROW
    EXECUTE PROCEDURE f_ai_clientes();


--
-- Name: ai_empresa; Type: TRIGGER; Schema: public; Owner: estlm
--

CREATE TRIGGER ai_empresa
    AFTER INSERT ON empresa
    FOR EACH ROW
    EXECUTE PROCEDURE f_ai_empresa();


--
-- Name: au_astoctas; Type: TRIGGER; Schema: public; Owner: estlm
--

CREATE TRIGGER au_astoctas
    AFTER UPDATE ON astoctas
    FOR EACH ROW
    EXECUTE PROCEDURE f_au_astoctas();


--
-- Name: au_astoh; Type: TRIGGER; Schema: public; Owner: estlm
--

CREATE TRIGGER au_astoh
    AFTER UPDATE ON astoh
    FOR EACH ROW
    EXECUTE PROCEDURE f_au_astoh();


--
-- Name: au_clientes; Type: TRIGGER; Schema: public; Owner: estlm
--

CREATE TRIGGER au_clientes
    AFTER UPDATE ON clientes
    FOR EACH ROW
    EXECUTE PROCEDURE f_au_clientes();


--
-- Name: au_compra; Type: TRIGGER; Schema: public; Owner: estlm
--

CREATE TRIGGER au_compra
    AFTER UPDATE ON compra
    FOR EACH ROW
    EXECUTE PROCEDURE f_au_compra();


--
-- Name: au_emiti; Type: TRIGGER; Schema: public; Owner: estlm
--

CREATE TRIGGER au_emiti
    AFTER UPDATE ON emiti
    FOR EACH ROW
    EXECUTE PROCEDURE f_au_emiti();


--
-- Name: au_prove; Type: TRIGGER; Schema: public; Owner: estlm
--

CREATE TRIGGER au_prove
    AFTER UPDATE ON prove
    FOR EACH ROW
    EXECUTE PROCEDURE f_au_prove();


--
-- Name: bd_astoctas; Type: TRIGGER; Schema: public; Owner: estlm
--

CREATE TRIGGER bd_astoctas
    BEFORE DELETE ON astoctas
    FOR EACH ROW
    EXECUTE PROCEDURE f_bd_astoctas();


--
-- Name: bd_astoh; Type: TRIGGER; Schema: public; Owner: estlm
--

CREATE TRIGGER bd_astoh
    BEFORE DELETE ON astoh
    FOR EACH ROW
    EXECUTE PROCEDURE f_bd_astoh();


--
-- Name: bd_emiti; Type: TRIGGER; Schema: public; Owner: estlm
--

CREATE TRIGGER bd_emiti
    BEFORE DELETE ON emiti
    FOR EACH ROW
    EXECUTE PROCEDURE f_bd_emiti();


--
-- Name: bd_empresa; Type: TRIGGER; Schema: public; Owner: estlm
--

CREATE TRIGGER bd_empresa
    BEFORE DELETE ON empresa
    FOR EACH ROW
    EXECUTE PROCEDURE f_bd_empresa();


--
-- Name: bu_astoh; Type: TRIGGER; Schema: public; Owner: estlm
--

CREATE TRIGGER bu_astoh
    BEFORE UPDATE ON astoh
    FOR EACH ROW
    EXECUTE PROCEDURE f_bu_astoh();


--
-- Name: bu_cheques; Type: TRIGGER; Schema: public; Owner: estlm
--

CREATE TRIGGER bu_cheques
    BEFORE UPDATE ON cheques
    FOR EACH ROW
    EXECUTE PROCEDURE f_bu_cheques();


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY ptovta
    ADD CONSTRAINT "$1" FOREIGN KEY (ptv_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY division
    ADD CONSTRAINT "$1" FOREIGN KEY (div_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY centroc
    ADD CONSTRAINT "$1" FOREIGN KEY (cco_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY comprob
    ADD CONSTRAINT "$1" FOREIGN KEY (comp_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY articvta
    ADD CONSTRAINT "$1" FOREIGN KEY (art_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY astoh
    ADD CONSTRAINT "$1" FOREIGN KEY (ash_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY astoctas
    ADD CONSTRAINT "$1" FOREIGN KEY (astc_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY listpre
    ADD CONSTRAINT "$1" FOREIGN KEY (ltp_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY monex
    ADD CONSTRAINT "$1" FOREIGN KEY (mne_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY firman
    ADD CONSTRAINT "$1" FOREIGN KEY (fir_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY interes
    ADD CONSTRAINT "$1" FOREIGN KEY (int_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY cheques
    ADD CONSTRAINT "$1" FOREIGN KEY (chq_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY conpag
    ADD CONSTRAINT "$1" FOREIGN KEY (cdp_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY cotiza
    ADD CONSTRAINT "$1" FOREIGN KEY (cot_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY ctacble
    ADD CONSTRAINT "$1" FOREIGN KEY (cbl_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY ctes
    ADD CONSTRAINT "$1" FOREIGN KEY (cte_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY docum
    ADD CONSTRAINT "$1" FOREIGN KEY (doc_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY clientes
    ADD CONSTRAINT "$1" FOREIGN KEY (cli_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY compra
    ADD CONSTRAINT "$1" FOREIGN KEY (cpra_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY emiti
    ADD CONSTRAINT "$1" FOREIGN KEY (emi_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY movsto
    ADD CONSTRAINT "$1" FOREIGN KEY (movs_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY movstoc
    ADD CONSTRAINT "$1" FOREIGN KEY (movc_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY notdeb
    ADD CONSTRAINT "$1" FOREIGN KEY (nd_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY prove
    ADD CONSTRAINT "$1" FOREIGN KEY (prov_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY sucursalc
    ADD CONSTRAINT "$1" FOREIGN KEY (sucu_cliente) REFERENCES clientes(cli_id);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY sucursalp
    ADD CONSTRAINT "$1" FOREIGN KEY (suc_prove) REFERENCES prove(prov_id);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY talon
    ADD CONSTRAINT "$1" FOREIGN KEY (tal_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY telefon
    ADD CONSTRAINT "$1" FOREIGN KEY (tel_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY varambi
    ADD CONSTRAINT "$1" FOREIGN KEY (vari_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY vendedor
    ADD CONSTRAINT "$1" FOREIGN KEY (ven_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY zona
    ADD CONSTRAINT "$1" FOREIGN KEY (zon_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY empleados
    ADD CONSTRAINT "$1" FOREIGN KEY (e_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY novemple
    ADD CONSTRAINT "$1" FOREIGN KEY (ne_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $1; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY subd
    ADD CONSTRAINT "$1" FOREIGN KEY (subd_codemp) REFERENCES empresa(emp_codigo);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY division
    ADD CONSTRAINT "$2" FOREIGN KEY (div_idptov) REFERENCES ptovta(ptv_id);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY centroc
    ADD CONSTRAINT "$2" FOREIGN KEY (cco_idptov) REFERENCES ptovta(ptv_id);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY comprob
    ADD CONSTRAINT "$2" FOREIGN KEY (comp_idptov) REFERENCES ptovta(ptv_id);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY astoh
    ADD CONSTRAINT "$2" FOREIGN KEY (ash_idptov) REFERENCES ptovta(ptv_id);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY astoctas
    ADD CONSTRAINT "$2" FOREIGN KEY (astc_idptov) REFERENCES ptovta(ptv_id);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY listpre
    ADD CONSTRAINT "$2" FOREIGN KEY (ltp_idart) REFERENCES articvta(art_id);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY monex
    ADD CONSTRAINT "$2" FOREIGN KEY (mne_idastoc) REFERENCES astoctas(astc_id);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY cheques
    ADD CONSTRAINT "$2" FOREIGN KEY (chq_idptov) REFERENCES ptovta(ptv_id);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY cotiza
    ADD CONSTRAINT "$2" FOREIGN KEY (cot_moneda) REFERENCES moneda(mon_codigo);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY ctacble
    ADD CONSTRAINT "$2" FOREIGN KEY (cbl_moneda) REFERENCES moneda(mon_codigo);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY ctes
    ADD CONSTRAINT "$2" FOREIGN KEY (cte_tipcta) REFERENCES tipcta(tct_codigo);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY docum
    ADD CONSTRAINT "$2" FOREIGN KEY (doc_idptov) REFERENCES ptovta(ptv_id);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY clientes
    ADD CONSTRAINT "$2" FOREIGN KEY (cli_idptov) REFERENCES ptovta(ptv_id);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY compra
    ADD CONSTRAINT "$2" FOREIGN KEY (cpra_idptov) REFERENCES ptovta(ptv_id);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY emiti
    ADD CONSTRAINT "$2" FOREIGN KEY (emi_idptov) REFERENCES ptovta(ptv_id);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY movsto
    ADD CONSTRAINT "$2" FOREIGN KEY (movs_idptov) REFERENCES ptovta(ptv_id);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY movstoc
    ADD CONSTRAINT "$2" FOREIGN KEY (movc_idptov) REFERENCES ptovta(ptv_id);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY notdeb
    ADD CONSTRAINT "$2" FOREIGN KEY (nd_idptov) REFERENCES ptovta(ptv_id);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY prove
    ADD CONSTRAINT "$2" FOREIGN KEY (prov_idptov) REFERENCES ptovta(ptv_id);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY talon
    ADD CONSTRAINT "$2" FOREIGN KEY (tal_idptov) REFERENCES ptovta(ptv_id);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY telefon
    ADD CONSTRAINT "$2" FOREIGN KEY (tel_tipent) REFERENCES tipentid(tet_codigo);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY cblexasi
    ADD CONSTRAINT "$2" FOREIGN KEY (cxa_cble) REFERENCES ctacble(cbl_id);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY empleados
    ADD CONSTRAINT "$2" FOREIGN KEY (e_sexo) REFERENCES sexo(sex_codigo);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY novemple
    ADD CONSTRAINT "$2" FOREIGN KEY (ne_idemple) REFERENCES empleados(e_id);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY subd
    ADD CONSTRAINT "$2" FOREIGN KEY (subd_idptov) REFERENCES ptovta(ptv_id);


--
-- Name: $2; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY subxcomp
    ADD CONSTRAINT "$2" FOREIGN KEY (subxc_comprob) REFERENCES comprob(comp_id);


--
-- Name: $3; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY centroc
    ADD CONSTRAINT "$3" FOREIGN KEY (cco_iddiv) REFERENCES division(div_id);


--
-- Name: $3; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY astoh
    ADD CONSTRAINT "$3" FOREIGN KEY (ash_comprob) REFERENCES comprob(comp_id);


--
-- Name: $3; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY astoctas
    ADD CONSTRAINT "$3" FOREIGN KEY (astc_comprob) REFERENCES comprob(comp_id);


--
-- Name: $3; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY monex
    ADD CONSTRAINT "$3" FOREIGN KEY (mne_moneda) REFERENCES moneda(mon_codigo);


--
-- Name: $3; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY cheques
    ADD CONSTRAINT "$3" FOREIGN KEY (chq_idastoc) REFERENCES astoctas(astc_id);


--
-- Name: $3; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY docum
    ADD CONSTRAINT "$3" FOREIGN KEY (doc_idastoc) REFERENCES astoctas(astc_id);


--
-- Name: $3; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY compra
    ADD CONSTRAINT "$3" FOREIGN KEY (cpra_comprob) REFERENCES comprob(comp_id);


--
-- Name: $3; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY emiti
    ADD CONSTRAINT "$3" FOREIGN KEY (emi_comprob) REFERENCES comprob(comp_id);


--
-- Name: $3; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY movsto
    ADD CONSTRAINT "$3" FOREIGN KEY (movs_idastoh) REFERENCES astoh(ash_id);


--
-- Name: $3; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY movstoc
    ADD CONSTRAINT "$3" FOREIGN KEY (movc_idastoh) REFERENCES astoh(ash_id);


--
-- Name: $3; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY notdeb
    ADD CONSTRAINT "$3" FOREIGN KEY (nd_idastoh) REFERENCES astoh(ash_id);


--
-- Name: $3; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY telefon
    ADD CONSTRAINT "$3" FOREIGN KEY (tel_tiptel) REFERENCES tiptel(ttl_codigo);


--
-- Name: $3; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY empleados
    ADD CONSTRAINT "$3" FOREIGN KEY (e_tipdoc) REFERENCES tipdocu(td_codigo);


--
-- Name: $4; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY astoctas
    ADD CONSTRAINT "$4" FOREIGN KEY (astc_idastoh) REFERENCES astoh(ash_id);


--
-- Name: $4; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY cheques
    ADD CONSTRAINT "$4" FOREIGN KEY (chq_moneda) REFERENCES moneda(mon_codigo);


--
-- Name: $4; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY compra
    ADD CONSTRAINT "$4" FOREIGN KEY (cpra_idastoh) REFERENCES astoh(ash_id);


--
-- Name: $4; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY emiti
    ADD CONSTRAINT "$4" FOREIGN KEY (emi_idastoh) REFERENCES astoh(ash_id);


--
-- Name: $4; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY movsto
    ADD CONSTRAINT "$4" FOREIGN KEY (movs_idemiti) REFERENCES emiti(emi_id);


--
-- Name: $4; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY movstoc
    ADD CONSTRAINT "$4" FOREIGN KEY (movc_idcompra) REFERENCES compra(cpra_id);


--
-- Name: $4; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY empleados
    ADD CONSTRAINT "$4" FOREIGN KEY (e_estciv) REFERENCES estcivil(ec_codigo);


--
-- Name: $5; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY astoctas
    ADD CONSTRAINT "$5" FOREIGN KEY (astc_moneda) REFERENCES moneda(mon_codigo);


--
-- Name: $5; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY movsto
    ADD CONSTRAINT "$5" FOREIGN KEY (movs_artic) REFERENCES articvta(art_id);


--
-- Name: $5; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY movstoc
    ADD CONSTRAINT "$5" FOREIGN KEY (movc_artic) REFERENCES articvta(art_id);


--
-- Name: $5; Type: FK CONSTRAINT; Schema: public; Owner: estlm
--

ALTER TABLE ONLY empleados
    ADD CONSTRAINT "$5" FOREIGN KEY (e_catego) REFERENCES catemple(ce_codigo);


--
-- Name: public; Type: ACL; Schema: -; Owner: postgres
--

REVOKE ALL ON SCHEMA public FROM PUBLIC;
REVOKE ALL ON SCHEMA public FROM postgres;
GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO PUBLIC;


--
-- Name: aduanas; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE aduanas FROM PUBLIC;
REVOKE ALL ON TABLE aduanas FROM estlm;
GRANT ALL ON TABLE aduanas TO estlm;
GRANT ALL ON TABLE aduanas TO nobody;


--
-- Name: articvta; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE articvta FROM PUBLIC;
REVOKE ALL ON TABLE articvta FROM estlm;
GRANT ALL ON TABLE articvta TO estlm;
GRANT ALL ON TABLE articvta TO nobody;


--
-- Name: articvta_art_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE articvta_art_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE articvta_art_id_seq FROM estlm;
GRANT ALL ON SEQUENCE articvta_art_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE articvta_art_id_seq TO nobody;


--
-- Name: astoctas; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE astoctas FROM PUBLIC;
REVOKE ALL ON TABLE astoctas FROM estlm;
GRANT ALL ON TABLE astoctas TO estlm;
GRANT ALL ON TABLE astoctas TO nobody;


--
-- Name: astoctas_astc_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE astoctas_astc_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE astoctas_astc_id_seq FROM estlm;
GRANT ALL ON SEQUENCE astoctas_astc_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE astoctas_astc_id_seq TO nobody;


--
-- Name: astoh; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE astoh FROM PUBLIC;
REVOKE ALL ON TABLE astoh FROM estlm;
GRANT ALL ON TABLE astoh TO estlm;
GRANT ALL ON TABLE astoh TO nobody;


--
-- Name: astoh_ash_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE astoh_ash_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE astoh_ash_id_seq FROM estlm;
GRANT ALL ON SEQUENCE astoh_ash_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE astoh_ash_id_seq TO nobody;


--
-- Name: auxfe; Type: ACL; Schema: public; Owner: zona
--

REVOKE ALL ON TABLE auxfe FROM PUBLIC;
REVOKE ALL ON TABLE auxfe FROM zona;
GRANT ALL ON TABLE auxfe TO zona;
GRANT ALL ON TABLE auxfe TO nobody;


--
-- Name: auxfe_fe_id_seq; Type: ACL; Schema: public; Owner: zona
--

REVOKE ALL ON SEQUENCE auxfe_fe_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE auxfe_fe_id_seq FROM zona;
GRANT ALL ON SEQUENCE auxfe_fe_id_seq TO zona;
GRANT UPDATE ON SEQUENCE auxfe_fe_id_seq TO nobody;


--
-- Name: bancos; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE bancos FROM PUBLIC;
REVOKE ALL ON TABLE bancos FROM estlm;
GRANT ALL ON TABLE bancos TO estlm;
GRANT ALL ON TABLE bancos TO nobody;


--
-- Name: catego; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE catego FROM PUBLIC;
REVOKE ALL ON TABLE catego FROM estlm;
GRANT ALL ON TABLE catego TO estlm;
GRANT ALL ON TABLE catego TO nobody;


--
-- Name: catego_cat_codigo_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE catego_cat_codigo_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE catego_cat_codigo_seq FROM estlm;
GRANT ALL ON SEQUENCE catego_cat_codigo_seq TO estlm;
GRANT UPDATE ON SEQUENCE catego_cat_codigo_seq TO nobody;


--
-- Name: catemple; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE catemple FROM PUBLIC;
REVOKE ALL ON TABLE catemple FROM estlm;
GRANT ALL ON TABLE catemple TO estlm;
GRANT ALL ON TABLE catemple TO nobody;


--
-- Name: cblexasi; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE cblexasi FROM PUBLIC;
REVOKE ALL ON TABLE cblexasi FROM estlm;
GRANT ALL ON TABLE cblexasi TO estlm;
GRANT ALL ON TABLE cblexasi TO nobody;


--
-- Name: centroc; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE centroc FROM PUBLIC;
REVOKE ALL ON TABLE centroc FROM estlm;
GRANT ALL ON TABLE centroc TO estlm;
GRANT ALL ON TABLE centroc TO nobody;


--
-- Name: centroc_cco_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE centroc_cco_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE centroc_cco_id_seq FROM estlm;
GRANT ALL ON SEQUENCE centroc_cco_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE centroc_cco_id_seq TO nobody;


--
-- Name: cheques; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE cheques FROM PUBLIC;
REVOKE ALL ON TABLE cheques FROM estlm;
GRANT ALL ON TABLE cheques TO estlm;
GRANT ALL ON TABLE cheques TO nobody;


--
-- Name: cheques_chq_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE cheques_chq_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE cheques_chq_id_seq FROM estlm;
GRANT ALL ON SEQUENCE cheques_chq_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE cheques_chq_id_seq TO nobody;


--
-- Name: clientes; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE clientes FROM PUBLIC;
REVOKE ALL ON TABLE clientes FROM estlm;
GRANT ALL ON TABLE clientes TO estlm;
GRANT ALL ON TABLE clientes TO nobody;


--
-- Name: clientes_cli_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE clientes_cli_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE clientes_cli_id_seq FROM estlm;
GRANT ALL ON SEQUENCE clientes_cli_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE clientes_cli_id_seq TO nobody;


--
-- Name: compra; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE compra FROM PUBLIC;
REVOKE ALL ON TABLE compra FROM estlm;
GRANT ALL ON TABLE compra TO estlm;
GRANT ALL ON TABLE compra TO nobody;


--
-- Name: compra_cpra_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE compra_cpra_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE compra_cpra_id_seq FROM estlm;
GRANT ALL ON SEQUENCE compra_cpra_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE compra_cpra_id_seq TO nobody;


--
-- Name: comprob; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE comprob FROM PUBLIC;
REVOKE ALL ON TABLE comprob FROM estlm;
GRANT ALL ON TABLE comprob TO estlm;
GRANT ALL ON TABLE comprob TO nobody;


--
-- Name: comprob_comp_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE comprob_comp_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE comprob_comp_id_seq FROM estlm;
GRANT ALL ON SEQUENCE comprob_comp_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE comprob_comp_id_seq TO nobody;


--
-- Name: coniva; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE coniva FROM PUBLIC;
REVOKE ALL ON TABLE coniva FROM estlm;
GRANT ALL ON TABLE coniva TO estlm;
GRANT ALL ON TABLE coniva TO nobody;


--
-- Name: conpag; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE conpag FROM PUBLIC;
REVOKE ALL ON TABLE conpag FROM estlm;
GRANT ALL ON TABLE conpag TO estlm;
GRANT ALL ON TABLE conpag TO nobody;


--
-- Name: conpag_cdp_codigo_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE conpag_cdp_codigo_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE conpag_cdp_codigo_seq FROM estlm;
GRANT ALL ON SEQUENCE conpag_cdp_codigo_seq TO estlm;
GRANT UPDATE ON SEQUENCE conpag_cdp_codigo_seq TO nobody;


--
-- Name: convmult; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE convmult FROM PUBLIC;
REVOKE ALL ON TABLE convmult FROM estlm;
GRANT ALL ON TABLE convmult TO estlm;
GRANT ALL ON TABLE convmult TO nobody;


--
-- Name: cotiza; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE cotiza FROM PUBLIC;
REVOKE ALL ON TABLE cotiza FROM estlm;
GRANT ALL ON TABLE cotiza TO estlm;
GRANT ALL ON TABLE cotiza TO nobody;


--
-- Name: ctacble; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE ctacble FROM PUBLIC;
REVOKE ALL ON TABLE ctacble FROM estlm;
GRANT ALL ON TABLE ctacble TO estlm;
GRANT ALL ON TABLE ctacble TO nobody;


--
-- Name: ctacble_cbl_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE ctacble_cbl_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE ctacble_cbl_id_seq FROM estlm;
GRANT ALL ON SEQUENCE ctacble_cbl_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE ctacble_cbl_id_seq TO nobody;


--
-- Name: ctes; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE ctes FROM PUBLIC;
REVOKE ALL ON TABLE ctes FROM estlm;
GRANT ALL ON TABLE ctes TO estlm;
GRANT ALL ON TABLE ctes TO nobody;


--
-- Name: ctes_cte_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE ctes_cte_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE ctes_cte_id_seq FROM estlm;
GRANT ALL ON SEQUENCE ctes_cte_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE ctes_cte_id_seq TO nobody;


--
-- Name: division; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE division FROM PUBLIC;
REVOKE ALL ON TABLE division FROM estlm;
GRANT ALL ON TABLE division TO estlm;
GRANT ALL ON TABLE division TO nobody;


--
-- Name: division_div_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE division_div_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE division_div_id_seq FROM estlm;
GRANT ALL ON SEQUENCE division_div_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE division_div_id_seq TO nobody;


--
-- Name: docum; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE docum FROM PUBLIC;
REVOKE ALL ON TABLE docum FROM estlm;
GRANT ALL ON TABLE docum TO estlm;
GRANT ALL ON TABLE docum TO nobody;


--
-- Name: docum_doc_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE docum_doc_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE docum_doc_id_seq FROM estlm;
GRANT ALL ON SEQUENCE docum_doc_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE docum_doc_id_seq TO nobody;


--
-- Name: emiti; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE emiti FROM PUBLIC;
REVOKE ALL ON TABLE emiti FROM estlm;
GRANT ALL ON TABLE emiti TO estlm;
GRANT ALL ON TABLE emiti TO nobody;


--
-- Name: emiti_emi_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE emiti_emi_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE emiti_emi_id_seq FROM estlm;
GRANT ALL ON SEQUENCE emiti_emi_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE emiti_emi_id_seq TO nobody;


--
-- Name: empleados; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE empleados FROM PUBLIC;
REVOKE ALL ON TABLE empleados FROM estlm;
GRANT ALL ON TABLE empleados TO estlm;
GRANT ALL ON TABLE empleados TO nobody;


--
-- Name: empleados_e_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE empleados_e_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE empleados_e_id_seq FROM estlm;
GRANT ALL ON SEQUENCE empleados_e_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE empleados_e_id_seq TO nobody;


--
-- Name: empresa; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE empresa FROM PUBLIC;
REVOKE ALL ON TABLE empresa FROM estlm;
GRANT ALL ON TABLE empresa TO estlm;
GRANT ALL ON TABLE empresa TO nobody;


--
-- Name: estcivil; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE estcivil FROM PUBLIC;
REVOKE ALL ON TABLE estcivil FROM estlm;
GRANT ALL ON TABLE estcivil TO estlm;
GRANT ALL ON TABLE estcivil TO nobody;


--
-- Name: evindi; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE evindi FROM PUBLIC;
REVOKE ALL ON TABLE evindi FROM estlm;
GRANT ALL ON TABLE evindi TO estlm;
GRANT ALL ON TABLE evindi TO nobody;


--
-- Name: firman; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE firman FROM PUBLIC;
REVOKE ALL ON TABLE firman FROM estlm;
GRANT ALL ON TABLE firman TO estlm;
GRANT ALL ON TABLE firman TO nobody;


--
-- Name: firman_fir_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE firman_fir_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE firman_fir_id_seq FROM estlm;
GRANT ALL ON SEQUENCE firman_fir_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE firman_fir_id_seq TO nobody;


--
-- Name: grupos; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE grupos FROM PUBLIC;
REVOKE ALL ON TABLE grupos FROM estlm;
GRANT ALL ON TABLE grupos TO estlm;
GRANT ALL ON TABLE grupos TO nobody;


--
-- Name: grupos_gpo_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE grupos_gpo_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE grupos_gpo_id_seq FROM estlm;
GRANT ALL ON SEQUENCE grupos_gpo_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE grupos_gpo_id_seq TO nobody;


--
-- Name: impresiones; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE impresiones FROM PUBLIC;
REVOKE ALL ON TABLE impresiones FROM estlm;
GRANT ALL ON TABLE impresiones TO estlm;
GRANT ALL ON TABLE impresiones TO nobody;


--
-- Name: indices; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE indices FROM PUBLIC;
REVOKE ALL ON TABLE indices FROM estlm;
GRANT ALL ON TABLE indices TO estlm;
GRANT ALL ON TABLE indices TO nobody;


--
-- Name: interes; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE interes FROM PUBLIC;
REVOKE ALL ON TABLE interes FROM estlm;
GRANT ALL ON TABLE interes TO estlm;
GRANT ALL ON TABLE interes TO nobody;


--
-- Name: listpre; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE listpre FROM PUBLIC;
REVOKE ALL ON TABLE listpre FROM estlm;
GRANT ALL ON TABLE listpre TO estlm;
GRANT ALL ON TABLE listpre TO nobody;


--
-- Name: listpre_ltp_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE listpre_ltp_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE listpre_ltp_id_seq FROM estlm;
GRANT ALL ON SEQUENCE listpre_ltp_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE listpre_ltp_id_seq TO nobody;


--
-- Name: moneda; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE moneda FROM PUBLIC;
REVOKE ALL ON TABLE moneda FROM estlm;
GRANT ALL ON TABLE moneda TO estlm;
GRANT ALL ON TABLE moneda TO nobody;


--
-- Name: monex; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE monex FROM PUBLIC;
REVOKE ALL ON TABLE monex FROM estlm;
GRANT ALL ON TABLE monex TO estlm;
GRANT ALL ON TABLE monex TO nobody;


--
-- Name: monex_mne_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE monex_mne_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE monex_mne_id_seq FROM estlm;
GRANT ALL ON SEQUENCE monex_mne_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE monex_mne_id_seq TO nobody;


--
-- Name: movsto; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE movsto FROM PUBLIC;
REVOKE ALL ON TABLE movsto FROM estlm;
GRANT ALL ON TABLE movsto TO estlm;
GRANT ALL ON TABLE movsto TO nobody;


--
-- Name: movsto_movs_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE movsto_movs_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE movsto_movs_id_seq FROM estlm;
GRANT ALL ON SEQUENCE movsto_movs_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE movsto_movs_id_seq TO nobody;


--
-- Name: movstoc; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE movstoc FROM PUBLIC;
REVOKE ALL ON TABLE movstoc FROM estlm;
GRANT ALL ON TABLE movstoc TO estlm;
GRANT ALL ON TABLE movstoc TO nobody;


--
-- Name: movstoc_movc_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE movstoc_movc_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE movstoc_movc_id_seq FROM estlm;
GRANT ALL ON SEQUENCE movstoc_movc_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE movstoc_movc_id_seq TO nobody;


--
-- Name: notdeb; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE notdeb FROM PUBLIC;
REVOKE ALL ON TABLE notdeb FROM estlm;
GRANT ALL ON TABLE notdeb TO estlm;
GRANT ALL ON TABLE notdeb TO nobody;


--
-- Name: notdeb_nd_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE notdeb_nd_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE notdeb_nd_id_seq FROM estlm;
GRANT ALL ON SEQUENCE notdeb_nd_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE notdeb_nd_id_seq TO nobody;


--
-- Name: novemple; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE novemple FROM PUBLIC;
REVOKE ALL ON TABLE novemple FROM estlm;
GRANT ALL ON TABLE novemple TO estlm;
GRANT ALL ON TABLE novemple TO nobody;


--
-- Name: novemple_ne_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE novemple_ne_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE novemple_ne_id_seq FROM estlm;
GRANT ALL ON SEQUENCE novemple_ne_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE novemple_ne_id_seq TO nobody;


--
-- Name: operadores; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE operadores FROM PUBLIC;
REVOKE ALL ON TABLE operadores FROM estlm;
GRANT ALL ON TABLE operadores TO estlm;
GRANT ALL ON TABLE operadores TO nobody;


--
-- Name: operadores_operad_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE operadores_operad_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE operadores_operad_id_seq FROM estlm;
GRANT ALL ON SEQUENCE operadores_operad_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE operadores_operad_id_seq TO nobody;


--
-- Name: pais; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE pais FROM PUBLIC;
REVOKE ALL ON TABLE pais FROM estlm;
GRANT ALL ON TABLE pais TO estlm;
GRANT ALL ON TABLE pais TO nobody;


--
-- Name: posaran; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE posaran FROM PUBLIC;
REVOKE ALL ON TABLE posaran FROM estlm;
GRANT ALL ON TABLE posaran TO estlm;
GRANT ALL ON TABLE posaran TO nobody;


--
-- Name: prove; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE prove FROM PUBLIC;
REVOKE ALL ON TABLE prove FROM estlm;
GRANT ALL ON TABLE prove TO estlm;
GRANT ALL ON TABLE prove TO nobody;


--
-- Name: prove_prov_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE prove_prov_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE prove_prov_id_seq FROM estlm;
GRANT ALL ON SEQUENCE prove_prov_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE prove_prov_id_seq TO nobody;


--
-- Name: provin; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE provin FROM PUBLIC;
REVOKE ALL ON TABLE provin FROM estlm;
GRANT ALL ON TABLE provin TO estlm;
GRANT ALL ON TABLE provin TO nobody;


--
-- Name: provin_pro_codigo_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE provin_pro_codigo_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE provin_pro_codigo_seq FROM estlm;
GRANT ALL ON SEQUENCE provin_pro_codigo_seq TO estlm;
GRANT UPDATE ON SEQUENCE provin_pro_codigo_seq TO nobody;


--
-- Name: ptovta; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE ptovta FROM PUBLIC;
REVOKE ALL ON TABLE ptovta FROM estlm;
GRANT ALL ON TABLE ptovta TO estlm;
GRANT ALL ON TABLE ptovta TO nobody;


--
-- Name: ptovta_ptv_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE ptovta_ptv_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE ptovta_ptv_id_seq FROM estlm;
GRANT ALL ON SEQUENCE ptovta_ptv_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE ptovta_ptv_id_seq TO nobody;


--
-- Name: sexo; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE sexo FROM PUBLIC;
REVOKE ALL ON TABLE sexo FROM estlm;
GRANT ALL ON TABLE sexo TO estlm;
GRANT ALL ON TABLE sexo TO nobody;


--
-- Name: subd; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE subd FROM PUBLIC;
REVOKE ALL ON TABLE subd FROM estlm;
GRANT ALL ON TABLE subd TO estlm;
GRANT ALL ON TABLE subd TO nobody;


--
-- Name: subd_subd_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE subd_subd_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE subd_subd_id_seq FROM estlm;
GRANT ALL ON SEQUENCE subd_subd_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE subd_subd_id_seq TO nobody;


--
-- Name: subxcomp; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE subxcomp FROM PUBLIC;
REVOKE ALL ON TABLE subxcomp FROM estlm;
GRANT ALL ON TABLE subxcomp TO estlm;
GRANT ALL ON TABLE subxcomp TO nobody;


--
-- Name: sucursalc; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE sucursalc FROM PUBLIC;
REVOKE ALL ON TABLE sucursalc FROM estlm;
GRANT ALL ON TABLE sucursalc TO estlm;
GRANT ALL ON TABLE sucursalc TO nobody;


--
-- Name: sucursalp; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE sucursalp FROM PUBLIC;
REVOKE ALL ON TABLE sucursalp FROM estlm;
GRANT ALL ON TABLE sucursalp TO estlm;
GRANT ALL ON TABLE sucursalp TO nobody;


--
-- Name: talon; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE talon FROM PUBLIC;
REVOKE ALL ON TABLE talon FROM estlm;
GRANT ALL ON TABLE talon TO estlm;
GRANT ALL ON TABLE talon TO nobody;


--
-- Name: talon_tal_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE talon_tal_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE talon_tal_id_seq FROM estlm;
GRANT ALL ON SEQUENCE talon_tal_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE talon_tal_id_seq TO nobody;


--
-- Name: telefon; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE telefon FROM PUBLIC;
REVOKE ALL ON TABLE telefon FROM estlm;
GRANT ALL ON TABLE telefon TO estlm;
GRANT ALL ON TABLE telefon TO nobody;


--
-- Name: telefon_tel_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE telefon_tel_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE telefon_tel_id_seq FROM estlm;
GRANT ALL ON SEQUENCE telefon_tel_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE telefon_tel_id_seq TO nobody;


--
-- Name: tipasi; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE tipasi FROM PUBLIC;
REVOKE ALL ON TABLE tipasi FROM estlm;
GRANT ALL ON TABLE tipasi TO estlm;
GRANT ALL ON TABLE tipasi TO nobody;


--
-- Name: tipcta; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE tipcta FROM PUBLIC;
REVOKE ALL ON TABLE tipcta FROM estlm;
GRANT ALL ON TABLE tipcta TO estlm;
GRANT ALL ON TABLE tipcta TO nobody;


--
-- Name: tipcta_tct_codigo_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE tipcta_tct_codigo_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE tipcta_tct_codigo_seq FROM estlm;
GRANT ALL ON SEQUENCE tipcta_tct_codigo_seq TO estlm;
GRANT UPDATE ON SEQUENCE tipcta_tct_codigo_seq TO nobody;


--
-- Name: tipdocu; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE tipdocu FROM PUBLIC;
REVOKE ALL ON TABLE tipdocu FROM estlm;
GRANT ALL ON TABLE tipdocu TO estlm;
GRANT ALL ON TABLE tipdocu TO nobody;


--
-- Name: tipemp; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE tipemp FROM PUBLIC;
REVOKE ALL ON TABLE tipemp FROM estlm;
GRANT ALL ON TABLE tipemp TO estlm;
GRANT ALL ON TABLE tipemp TO nobody;


--
-- Name: tipentid; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE tipentid FROM PUBLIC;
REVOKE ALL ON TABLE tipentid FROM estlm;
GRANT ALL ON TABLE tipentid TO estlm;
GRANT ALL ON TABLE tipentid TO nobody;


--
-- Name: tiptel; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE tiptel FROM PUBLIC;
REVOKE ALL ON TABLE tiptel FROM estlm;
GRANT ALL ON TABLE tiptel TO estlm;
GRANT ALL ON TABLE tiptel TO nobody;


--
-- Name: tiptel_ttl_codigo_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE tiptel_ttl_codigo_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE tiptel_ttl_codigo_seq FROM estlm;
GRANT ALL ON SEQUENCE tiptel_ttl_codigo_seq TO estlm;
GRANT UPDATE ON SEQUENCE tiptel_ttl_codigo_seq TO nobody;


--
-- Name: unimed; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE unimed FROM PUBLIC;
REVOKE ALL ON TABLE unimed FROM estlm;
GRANT ALL ON TABLE unimed TO estlm;
GRANT ALL ON TABLE unimed TO nobody;


--
-- Name: varambi; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE varambi FROM PUBLIC;
REVOKE ALL ON TABLE varambi FROM estlm;
GRANT ALL ON TABLE varambi TO estlm;
GRANT ALL ON TABLE varambi TO nobody;


--
-- Name: vencimiento; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE vencimiento FROM PUBLIC;
REVOKE ALL ON TABLE vencimiento FROM estlm;
GRANT ALL ON TABLE vencimiento TO estlm;
GRANT ALL ON TABLE vencimiento TO nobody;


--
-- Name: vencimiento_vto_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE vencimiento_vto_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE vencimiento_vto_id_seq FROM estlm;
GRANT ALL ON SEQUENCE vencimiento_vto_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE vencimiento_vto_id_seq TO nobody;


--
-- Name: vendedor; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON TABLE vendedor FROM PUBLIC;
REVOKE ALL ON TABLE vendedor FROM estlm;
GRANT ALL ON TABLE vendedor TO estlm;
GRANT ALL ON TABLE vendedor TO nobody;


--
-- Name: vendedor_ven_id_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE vendedor_ven_id_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE vendedor_ven_id_seq FROM estlm;
GRANT ALL ON SEQUENCE vendedor_ven_id_seq TO estlm;
GRANT UPDATE ON SEQUENCE vendedor_ven_id_seq TO nobody;


--
-- Name: zona_zon_codigo_seq; Type: ACL; Schema: public; Owner: estlm
--

REVOKE ALL ON SEQUENCE zona_zon_codigo_seq FROM PUBLIC;
REVOKE ALL ON SEQUENCE zona_zon_codigo_seq FROM estlm;
GRANT ALL ON SEQUENCE zona_zon_codigo_seq TO estlm;
GRANT UPDATE ON SEQUENCE zona_zon_codigo_seq TO nobody;


--
-- PostgreSQL database dump complete
--

