--
--


--
-- Name: plpgsql; Type: EXTENSION; Schema: -; Owner: 
--

CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;


--
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: 
--

COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';



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

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

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

CREATE FUNCTION actfeclose() RETURNS numeric
    LANGUAGE plpgsql
    AS $$
DECLARE
registro 	RECORD;
registror 	RECORD;
stm		integer;
retval		numeric;
maxfecha	date;
fecharet	date;
BEGIN

retval:=0;

for registro in select op_id as x from operaciones where op_estado=101 and int4lt(op_tipoper,100::int4) and op_fecha_close is null loop
    maxfecha:='01-01-1900';
    select sitem_id into stm from subitem where sitem_idoper=registro.x and sitem_estado=1;
    if stm is null then
	for registror in select distinct ret_idopera as y from retiros where ret_idsitem in (select sitem_id from subitem where sitem_idoper=registro.x) loop
	    select op_fechain into fecharet from operaciones where op_id=registror.y;
	    if date_gt(fecharet,maxfecha) then
		maxfecha:=fecharet;
	    end if;
	end loop;
	update operaciones set op_fecha_close=maxfecha where op_id=registro.x;
    end if;
end loop; 

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

RETURN retval;
END;$$;


ALTER FUNCTION public.actfeclose() OWNER TO zona;

--
-- Name: actualizoweb(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION actualizoweb(integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
modo		 alias for $1;
ret 		 boolean;
registro	 record;
regist		 record;
registw2	 record;
disponible	 numeric;
dispon		 numeric;
compromweb	 numeric;
llevo		 numeric;
elultimo	 numeric;
begin


update wsubitem set wsitem_estado=7;

for registro in select 
     * from subitem where sitem_estado=1 and estadop(sitem_idoper)=101
    loop

	select cantidispw(wsitem_id),wsitem_cantcompw into disponible,compromweb  from wsubitem where wsitem_id=registro.sitem_id;
	if not found then
		insert into wsubitem (wsitem_id,wsitem_iditem,wsitem_idoper,wsitem_codigo,wsitem_artic,wsitem_canting,wsitem_cantret,wsitem_cantcomp,wsitem_cantmala,wsitem_importe,wsitem_imp_dolar,wsitem_volumen,wsitem_peso,wsitem_tipemb,wsitem_deposito,wsitem_idacta,wsitem_estado,wsitem_directo,wsitem_indirecto,wsitem_compbte,wsitem_consig,wsitem_item,wsitem_moneda,wsitem_unimed,wsitem_comptrans,wsitem_tipoper,wsitem_nrotaldir,wsitem_codart,wsitem_marca,wsitem_modelo,wsitem_descrip,wsitem_posa,wsitem_cantcompw) 
		    values (registro.sitem_id,registro.sitem_iditem,registro.sitem_idoper,registro.sitem_codigo,registro.sitem_artic,registro.sitem_canting,registro.sitem_cantret,registro.sitem_cantcomp,registro.sitem_cantmala,registro.sitem_importe,registro.sitem_imp_dolar,registro.sitem_volumen,registro.sitem_peso,registro.sitem_tipemb,registro.sitem_deposito,registro.sitem_idacta,registro.sitem_estado,registro.sitem_directo,registro.sitem_indirecto,registro.sitem_compbte,consigdeop(registro.sitem_idoper),itemdeitem(registro.sitem_iditem),monedadeitem(registro.sitem_iditem),unimeddeitem(registro.sitem_iditem),transitodeop(registro.sitem_idoper),tipoperdeop(registro.sitem_idoper),nrotaldiroper(registro.sitem_idoper),codigodeartic(registro.sitem_artic),marcadeartic(registro.sitem_artic),modelodeartic(registro.sitem_artic),descripdeartic(registro.sitem_artic),posadeartic(registro.sitem_artic),0);

		for regist in select 
		    * from retiros where ret_idsitem=registro.sitem_id
		    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; 

	    else

		dispon:=registro.sitem_canting-registro.sitem_cantcomp-registro.sitem_cantret-registro.sitem_cantmala;

		if(compromweb<=dispon) then 

			delete from wretiros where wret_idsitem=registro.sitem_id;
			delete from wsubitem where wsitem_id=registro.sitem_id;

			insert into wsubitem (wsitem_id,wsitem_iditem,wsitem_idoper,wsitem_codigo,wsitem_artic,wsitem_canting,wsitem_cantret,wsitem_cantcomp,wsitem_cantmala,wsitem_importe,wsitem_imp_dolar,wsitem_volumen,wsitem_peso,wsitem_tipemb,wsitem_deposito,wsitem_idacta,wsitem_estado,wsitem_directo,wsitem_indirecto,wsitem_compbte,wsitem_consig,wsitem_item,wsitem_moneda,wsitem_unimed,wsitem_comptrans,wsitem_tipoper,wsitem_nrotaldir,wsitem_codart,wsitem_marca,wsitem_modelo,wsitem_descrip,wsitem_posa,wsitem_cantcompw) 
			    values (registro.sitem_id,registro.sitem_iditem,registro.sitem_idoper,registro.sitem_codigo,registro.sitem_artic,registro.sitem_canting,registro.sitem_cantret,registro.sitem_cantcomp,registro.sitem_cantmala,registro.sitem_importe,registro.sitem_imp_dolar,registro.sitem_volumen,registro.sitem_peso,registro.sitem_tipemb,registro.sitem_deposito,registro.sitem_idacta,registro.sitem_estado,registro.sitem_directo,registro.sitem_indirecto,registro.sitem_compbte,consigdeop(registro.sitem_idoper),itemdeitem(registro.sitem_iditem),monedadeitem(registro.sitem_iditem),unimeddeitem(registro.sitem_iditem),transitodeop(registro.sitem_idoper),tipoperdeop(registro.sitem_idoper),nrotaldiroper(registro.sitem_idoper),codigodeartic(registro.sitem_artic),marcadeartic(registro.sitem_artic),modelodeartic(registro.sitem_artic),descripdeartic(registro.sitem_artic),posadeartic(registro.sitem_artic),compromweb);

			for regist in select 
			    * from retiros where ret_idsitem=registro.sitem_id
			    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; 
		
		    else

			delete from wretiros where wret_idsitem=registro.sitem_id;
			delete from wsubitem where wsitem_id=registro.sitem_id;

			insert into wsubitem (wsitem_id,wsitem_iditem,wsitem_idoper,wsitem_codigo,wsitem_artic,wsitem_canting,wsitem_cantret,wsitem_cantcomp,wsitem_cantmala,wsitem_importe,wsitem_imp_dolar,wsitem_volumen,wsitem_peso,wsitem_tipemb,wsitem_deposito,wsitem_idacta,wsitem_estado,wsitem_directo,wsitem_indirecto,wsitem_compbte,wsitem_consig,wsitem_item,wsitem_moneda,wsitem_unimed,wsitem_comptrans,wsitem_tipoper,wsitem_nrotaldir,wsitem_codart,wsitem_marca,wsitem_modelo,wsitem_descrip,wsitem_posa,wsitem_cantcompw) 
			    values (registro.sitem_id,registro.sitem_iditem,registro.sitem_idoper,registro.sitem_codigo,registro.sitem_artic,registro.sitem_canting,registro.sitem_cantret,registro.sitem_cantcomp,registro.sitem_cantmala,registro.sitem_importe,registro.sitem_imp_dolar,registro.sitem_volumen,registro.sitem_peso,registro.sitem_tipemb,registro.sitem_deposito,registro.sitem_idacta,registro.sitem_estado,registro.sitem_directo,registro.sitem_indirecto,registro.sitem_compbte,consigdeop(registro.sitem_idoper),itemdeitem(registro.sitem_iditem),monedadeitem(registro.sitem_iditem),unimeddeitem(registro.sitem_iditem),transitodeop(registro.sitem_idoper),tipoperdeop(registro.sitem_idoper),nrotaldiroper(registro.sitem_idoper),codigodeartic(registro.sitem_artic),marcadeartic(registro.sitem_artic),modelodeartic(registro.sitem_artic),descripdeartic(registro.sitem_artic),posadeartic(registro.sitem_artic),0);

			for regist in select 
			    * from retiros where ret_idsitem=registro.sitem_id
			    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; 

			--grabo temporalweb

			llevo:=0;
			elultimo:=0;

			for registw2 in select 
    			    * from wret2 where wret2_idsitem=registro.sitem_id and wret2_estado<50
    			    loop
				elultimo:=registw2.wret2_cantidad;
				llevo:=llevo+registw2.wret2_cantidad;
				if(llevo<=dispon) then
					update wsubitem set wsitem_cantcompw=wsitem_cantcompw + registw2.wret2_cantidad where wsitem_id=registw2.wret2_idsitem;
				    else
					if((dispon+registw2.wret2_cantidad-llevo) > 0) then
						insert into temporalweb (wtmp_idsitem,wtmp_disponib,wtmp_compweb,wtmp_idret,wtmp_valor) values (registro.sitem_id,dispon,compromweb,registw2.wret2_id,dispon+registw2.wret2_cantidad-llevo);
					    else
						insert into temporalweb (wtmp_idsitem,wtmp_disponib,wtmp_compweb,wtmp_idret,wtmp_valor) values (registro.sitem_id,dispon,compromweb,registw2.wret2_id,-1);
					end if;
				end if;
			    end loop; 
		end if;
	end if;
    end loop; 


delete from wsubitem where wsitem_estado=7;

ret:='t';

return ret;
end;$_$;


ALTER FUNCTION public.actualizoweb(integer) OWNER TO zona;

--
-- Name: actualizowebnew(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION actualizowebnew(integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
modo		 alias for $1;
ret 		 boolean;
registro	 record;
regist		 record;
registw2	 record;
disponible	 numeric;
dispon		 numeric;
compromweb	 numeric;
llevo		 numeric;
elultimo	 numeric;
begin


for registw2 in select 
    * from wret2 where wret2_estado<50
    loop

	elultimo:=0;
	dispon:=0;
	dispon:=cantidispw(registw2.wret2_idsitem);
	elultimo:=registw2.wret2_cantidad;

	if(elultimo<=dispon) then
		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:='t';

return ret;
end;$_$;


ALTER FUNCTION public.actualizowebnew(integer) OWNER TO zona;

--
-- Name: almacenajeconfactur(date, smallint, smallint, smallint, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION almacenajeconfactur(date, smallint, smallint, smallint, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
fecha		 alias for $1;
dias		 alias for $2;
anio 		 alias for $3;
mes 		 alias for $4;
usuario		 alias for $5;
ret 		 boolean;
ultfec 		 date;
registro	 record;
regi		 record;
hay	 	 int4;
begin

ret:='t';

if(int4eq(usuario,0::int4)) then
	delete from confactur where cfc_idart in (5,7,8,11) and cfc_anio=anio and cfc_mes=mes;
	for registro in select 
	    * from almacenaje where al_estado=1 and al_tiprod=1 
	    loop
		ret:='f';
		insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_leyen,cfc_estado,cfc_anio,cfc_mes,cfc_dias,cfc_idalm) values (registro.al_idusu,fecha,8,1,(registro.al_importe / dias * registro.al_dias * registro.al_tarifa)::numeric,(registro.al_importe / dias * registro.al_dias * registro.al_tarifa)::numeric,registro.al_leyenda,1::int2,anio,mes,registro.al_dias,registro.al_id);
	    end loop; 

	for regi in select 
	    * from almacenaje where al_estado=1 and al_tiprod!=1 
	    loop
		ret:='f';
		insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_leyen,cfc_estado,cfc_anio,cfc_mes,cfc_dias,cfc_idalm) values (regi.al_idusu,fecha,idartdetipp(regi.al_tiprod),(regi.al_canti * regi.al_dias),regi.al_tarifa::numeric,(regi.al_tarifa * regi.al_dias * regi.al_canti)::numeric,regi.al_leyenda,1::int2,anio,mes,regi.al_dias,regi.al_id);
	    end loop; 

    else
	delete from confactur where cfc_idart in (5,7,8,11) and cfc_anio=anio and cfc_mes=mes and cfc_usuario=usuario;
	for registro in select 
	    * from almacenaje where al_estado=1 and al_tiprod=1 and cfc_usurio=usuario
	    loop
		ret:='f';
		insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_leyen,cfc_estado,cfc_anio,cfc_mes,cfc_dias,cfc_idalm) values (registro.al_idusu,fecha,8,1,(registro.al_importe / dias * registro.al_dias * registro.al_tarifa)::numeric,(registro.al_importe / dias * registro.al_dias * registro.al_tarifa)::numeric,registro.al_leyenda,1::int2,anio,mes,registro.al_dias,registro.al_id);
	    end loop; 

	for regi in select 
	    * from almacenaje where al_estado=1 and al_tiprod!=1 and al_idusu=usuario
	    loop
		ret:='f';
		insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_leyen,cfc_estado,cfc_anio,cfc_mes,cfc_dias,cfc_idalm) values (regi.al_idusu,fecha,idartdetipp(regi.al_tiprod),(regi.al_canti * regi.al_dias),regi.al_tarifa::numeric,(regi.al_tarifa * regi.al_dias * regi.al_canti)::numeric,regi.al_leyenda,1::int2,anio,mes,regi.al_dias,regi.al_id);
	    end loop; 


    end if;

return ret;
end;$_$;


ALTER FUNCTION public.almacenajeconfactur(date, smallint, smallint, smallint, integer) OWNER TO zona;

--
-- Name: almconfactur(date, smallint, smallint, smallint, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION almconfactur(date, smallint, smallint, smallint, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
fecha		 alias for $1;
estado		 alias for $2;
anio 		 alias for $3;
mes 		 alias for $4;
usuario		 alias for $5;
ret 		 boolean;
ultfec 		 date;
registro	 record;
hay	 	 int4;
begin

ret:='t';

if(int4eq(usuario,0::int4)) then
	delete from confactur where cfc_idart in (5,7,11) and cfc_anio=anio and cfc_mes=mes;

	for registro in select 
	    * from almacen where alm_estado=estado  
	    loop
	    ret:='f';
	    if(registro.alm_retiro is NULL) then ultfec:=fecha; else ultfec:=registro.alm_retiro; end if;

	    if((int4eq(registro.alm_idusu,4030::int4) and int4eq(idartdetipp(registro.alm_tiprod),6))  or (int4eq(registro.alm_idusu,4117::int4) and int4eq(idartdetipp(registro.alm_tiprod),6))) then
		    ret:='f';
		else
		    insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_leyen,cfc_estado,cfc_anio,cfc_mes,cfc_dias,cfc_idalm) values (registro.alm_idusu,fecha,idartdetipp(registro.alm_tiprod),1::numeric,registro.alm_tarifa::numeric,registro.alm_tarifa*date_mi(ultfec,registro.alm_ultfac)::numeric,registro.alm_leyenda,1::int2,anio,mes,date_mi(ultfec,registro.alm_ultfac),registro.alm_id);
		    ret:='t';
		end if;
	    end loop; 

    else
	delete from confactur where cfc_anio=anio and cfc_mes=mes and cfc_usuario=usuario and cfc_idart in (5,7,11);
	for registro in select 
	    * from almacen where alm_estado=estado and alm_idusu=usuario 
	    loop
	    ret:='f';
	    if(registro.alm_retiro is NULL) then ultfec:=fecha; else ultfec:=registro.alm_retiro; end if;
	    insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_leyen,cfc_estado,cfc_anio,cfc_mes,cfc_dias,cfc_idalm) values (registro.alm_idusu,fecha,idartdetipp(registro.alm_tiprod),1::numeric,registro.alm_tarifa::numeric,registro.alm_tarifa*date_mi(ultfec,registro.alm_ultfac)::numeric,registro.alm_leyenda,1::int2,anio,mes,date_mi(ultfec,registro.alm_ultfac),registro.alm_id);
	    end loop; 

end if;

return ret;
end;$_$;


ALTER FUNCTION public.almconfactur(date, smallint, smallint, smallint, integer) OWNER TO zona;

--
-- Name: alqconfactur(integer, smallint, smallint, date); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION alqconfactur(integer, smallint, smallint, date) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
usuario		 alias for $1;
anio 		 alias for $2;
mes 		 alias for $3;
fecha		 alias for $4;
ret 		 boolean;
registro	 record;
aux_iva		 numeric;
hay	 	 int4;
importe 	 numeric;
articulo 	 int4;
begin

ret:='f';

SELECT  var_valor 
INTO     aux_iva -- Monto no grabado de alquileres
FROM varamb    WHERE var_codigo like 'IMP_SIN_IVA%';


if(int4eq(usuario,0::int4)) then
	delete from confactur where cfc_idart in (22,23,24,25,26,27,28,29,30,31,111) and cfc_anio=anio and cfc_mes=mes;
	for registro in select 
	    * from tarifas where tari_idart in (22,23,24,25,26,27,28,29,30,31,111) 
		and estadocontr(tari_idcontr)=1 and date_ge(tari_fhasta,fecha) and date_le(tari_fdesde,fecha)
	loop
	    ret:='t';
	    if(int2eq(facturacontr(registro.tari_idcontr),1::int2)) then
    		articulo:=registro.tari_idart;
		importe:=valtarico(registro.tari_usuario,articulo,0::numeric,0::int2,fecha::date,registro.tari_idcontr,registro.tari_orden);
		if(importe < aux_iva) then articulo:=articulo + 5; end if;
--		insert into confactur (cfc_ptov,cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_estado,cfc_anio,cfc_mes) values (1::int2,registro.tari_usuario,fecha,articulo::int4,1::numeric,registro.tari_importe::numeric,registro.tari_importe::numeric,1::int2,anio,mes);
		insert into confactur (cfc_ptov,cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_estado,cfc_anio,cfc_mes) values (1::int2,registro.tari_usuario,fecha,articulo::int4,1::numeric,importe,importe,1::int2,anio,mes);
	    end if; 
	end loop; 

    else

	delete from confactur where cfc_anio=anio and cfc_mes=mes and cfc_usuario=usuario and cfc_idart in (22,23,24,25,26,27,28,29,30,31,111);
	for registro in select 
	    * from tarifas where tari_idart in (22,23,24,25,26,27,28,29,30,31,111) and tari_usuario=usuario and estadocontr(tari_idcontr)=1 
		and date_ge(tari_fhasta,fecha) and date_le(tari_fdesde,fecha)
	loop
	    ret:='t';
	    if(int2eq(facturacontr(registro.tari_idcontr),1::int2)) then
    		articulo:=registro.tari_idart;
		importe:=valtarico(registro.tari_usuario,articulo,0::numeric,0::int2,fecha::date,registro.tari_idcontr,registro.tari_orden);
		if(importe < aux_iva) then articulo:=articulo + 5; end if;
--		insert into confactur (cfc_ptov,cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_estado,cfc_anio,cfc_mes) values (1::int2,registro.tari_usuario,fecha,articulo::int4,1::numeric,registro.tari_importe::numeric,registro.tari_importe::numeric,1::int2,anio,mes);
		insert into confactur (cfc_ptov,cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_estado,cfc_anio,cfc_mes) values (1::int2,registro.tari_usuario,fecha,articulo::int4,1::numeric,importe,importe,1::int2,anio,mes);
    	    end if; 
	end loop; 
end if;

return ret;
end;$_$;


ALTER FUNCTION public.alqconfactur(integer, smallint, smallint, date) OWNER TO zona;

--
-- Name: analiz1_astc(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION analiz1_astc(integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	empresa		ALIAS FOR $1; 
	retval 		integer;
	idastc		integer;
	registro	 record;
	imp		numeric;
    BEGIN
    retval:=1;


    for registro in select idastoh,idcli(1,codcli) as idcli,importe,grupo from m_ctacte order by idastoh
    loop
	select astc_id into idastc from astoctas where astc_idastoh=registro.idastoh and astc_ctacble=18 and astc_importe=registro.importe and astc_ctacte=registro.idcli limit 1;
	if not found then
	    select astc_id into idastc from astoctas where astc_idastoh=registro.idastoh and astc_ctacble=18 and astc_importe=registro.importe and astc_ctacte=-1 limit 1;
	    if found then
		update astoctas set astc_ctacte=registro.idcli, astc_grupo=registro.grupo where astc_id=idastc;
	      else		
		insert into m_difer (numero,dif1,astoc) values (idastoh,'no lo encontre en astoctas',idcli);
	    end if;
	end if;
    end loop;

    RETURN retval;
    END;$_$;


ALTER FUNCTION public.analiz1_astc(integer) OWNER TO zona;

--
-- Name: analiz2_astc(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION analiz2_astc(integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	empresa		ALIAS FOR $1; 
	retval 		integer;
	idastc		integer;
	nume		integer;
	idastoh1		integer;
	registro	 record;
	imp		numeric;
    BEGIN
    retval:=1;


    for registro in select * from m_difer where tip=1 and codigo='PG' order by numero
    loop
	select astc_id,astc_idastoh into idastc,idastoh1 from astoctas where astc_comprob=838 and astc_numero=registro.numero order by astc_id limit 1;
	nume:=idastc -1;
	update astoctas set astc_ctacte=idcli(1,ctacte::integer) from m_astoctas where astc_idastoh=idastoh and astc_ctacble=idcbl(1,ctacble) and astc_ctacble=18 and idastoh=idastoh1 and orden+nume=astc_id;
    end loop;

    RETURN retval;
    END;$_$;


ALTER FUNCTION public.analiz2_astc(integer) OWNER TO zona;

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

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

--
-- Name: anul_factu_alm(integer, smallint, smallint, integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION anul_factu_alm(integer, smallint, smallint, integer, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	cliente		ALIAS FOR $1; 
	anio		ALIAS FOR $2; 
	mes		ALIAS FOR $3; 
	opera		ALIAS FOR $4; 
	codemp		ALIAS FOR $5; 
	articulo	integer;
	artsegur	integer;
	registro	record;
	regist		record;
	retval 		integer;
    BEGIN
    retval:=0;

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

    if(int4ne(cliente,0) and int4eq(opera,0)) then
	for registro in select distinct(fac_idoper) from facturacion where fac_codemp=codemp and fac_cliente=cliente and fac_anio=anio and fac_mes=mes and fac_estado=1 and fac_idart=articulo
	loop
	    update voling set vol_ultfac=vol_ultfac-registro.fac_dias where vol_idoper=registro.fac_idoper;
	end loop;

	delete from facturacion where fac_codemp=codemp and fac_cliente=cliente and fac_anio=anio and fac_mes=mes and fac_estado=1 and fac_idart in (articulo,artsegur);
	for regist in select * from complfac where cfac_codemp=codemp and cfac_estado=1 and cfac_evento=3 
	    loop
		delete from facturacion where fac_codemp=codemp and fac_ptov=regist.cfac_ptov and fac_idart=regist.cfac_idart and fac_anio=anio and fac_mes=mes and fac_estado=1 and fac_cliente=cliente;
	    end loop; 
    end if;


    if(int4eq(cliente,0) and  int4eq(opera,0)) then
	for registro in select distinct(fac_idoper) from facturacion where fac_codemp=codemp and fac_anio=anio and fac_mes=mes and fac_estado=1 and fac_idart=articulo
	loop
	update voling set vol_ultfac=vol_ultfac-registro.fac_dias where vol_idoper=registro.fac_idoper;
	end loop;
	delete from facturacion where fac_codemp=codemp and fac_anio=anio and fac_mes=mes and fac_estado=1 and fac_idart in (articulo,artsegur);
	for regist in select * from complfac where cfac_codemp=codemp and cfac_estado=1 and cfac_evento=3 
	    loop
		delete from facturacion where fac_codemp=codemp and fac_ptov=regist.cfac_ptov and fac_idart=regist.cfac_idart and fac_anio=anio and fac_mes=mes and fac_estado=1;
	    end loop; 
    end if;


    if(int4ne(opera,0)) then
	for registro in select distinct(fac_idoper) from facturacion where fac_codemp=codemp and fac_idoper=opera and fac_anio=anio and fac_mes=mes and fac_estado=1 and fac_idart=articulo
	loop
	update voling set vol_ultfac=vol_ultfac-registro.fac_dias where vol_idoper=registro.fac_idoper;
	end loop;
	delete from facturacion where fac_codemp=codemp and fac_idoper=opera and fac_anio=anio and fac_mes=mes and fac_estado=1 and fac_idart in (articulo,artsegur);
	for regist in select * from complfac where cfac_codemp=codemp and cfac_estado=1 and cfac_evento=3 
	    loop
		delete from facturacion where fac_codemp=codemp and fac_ptov=regist.cfac_ptov and fac_idart=regist.cfac_idart and fac_anio=anio and fac_mes=mes and fac_estado=1 and fac_idoper=opera;
	    end loop; 
    end if;

RETURN retval;
END;$_$;


ALTER FUNCTION public.anul_factu_alm(integer, smallint, smallint, integer, integer) OWNER TO zona;

--
-- Name: arrcompvsret(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION arrcompvsret(integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
opid		 alias for $1;
ret 		 boolean;
registro	 record;
cantidad	 numeric(15,5);

begin
for registro in select 
    * from auxoperv
    loop
	if int4gt(registro.avh_idoper,0) then 
		update subitem set sitem_cantcomp=0 where sitem_id=registro.avh_idoper;
	end if;
end loop; 

delete from auxoperv where avh_idoper>0;

ret:='t';
return ret;
end;$_$;


ALTER FUNCTION public.arrcompvsret(integer) OWNER TO zona;

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

CREATE FUNCTION arreart() RETURNS integer
    LANGUAGE plpgsql
    AS $$
declare
regi 		RECORD;
ret		int4;
operid		int4;
idart		int4;
rowintotal 	int4;
ruflo 	int4;
idsitem 	int4;
begin
ret:=0;

idsitem:=1;
for regi in select * from intotal order by int_directo,int_indirecto,int_tipoper,int_numero,int_articod,int_lotenum
	loop
	idart:=cidart(regi.int_indirecto::int4,regi.int_articod::varchar);
	update subitem set sitem_artic=idart where sitem_id=idsitem;
	idsitem:=idsitem+1;
    end loop; 

return ret;
end;$$;


ALTER FUNCTION public.arreart() OWNER TO zona;

--
-- Name: arreartic(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION arreartic(integer, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare

mal		alias for $1;
bien		alias for $2;
codigobien	varchar;
codigomal	varchar;
ret		int4;

begin
ret:=20;

select sitem_id into ret from subitem where sitem_artic=mal; 

return ret;
end;$_$;


ALTER FUNCTION public.arreartic(integer, integer) OWNER TO zona;

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

CREATE FUNCTION arrecono() RETURNS integer
    LANGUAGE plpgsql
    AS $$
declare
regi 		RECORD;
ret		int4;
idoper		int4;
itemid		int4;
rowintotal 	int4;
ruflo 	int4;
conocim 	varchar;
ruflo2 	int4;
begin
ret:=0;
idoper:=1;

for regi in select distinct on (int_directo,int_indirecto,int_tipoper,int_numero) * from intotal
	loop
	conocim:=trim(regi.int_conocim);
	update operaciones  set op_conocim=conocim where op_id=idoper;
	idoper:=idoper+1;
        end loop; 

return ret;
end;$$;


ALTER FUNCTION public.arrecono() OWNER TO zona;

--
-- Name: arrecontr(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION arrecontr(integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
usuario		 alias for $1;
ret 		 boolean;
registro	 record;
regi		 record;
regi2		 record;
regi3		 record;
unif	 	 int4;
anterior 	 int2;
begin

    ret:='f';
--    for registro in select 
--	* from contratos where contr_locador=usuario and contr_estado in (1,0) and contr_unifun=0  
--	loop
--	    anterior:=1;
--	    for regi in select 
--		* from unifun where unif_usuario=usuario and unif_estado=1  
--		loop
--		    if(int2ne(anterior,regi.unif_codigo)) then
--			update contratos set contr_unifun=regi.unif_codigo where contr_id=registro.contr_id;
--			anterior:=regi.unif_codigo;		
--		      else
--			insert into contratos1 (contr1_id,contr1_locador,contr1_locatario,contr1_idsubt,contr1_unifun,contr1_garantia,contr1_step,contr1_facturable,contr1_leyenda,contr1_estado,contr1_metros,contr1_puxmtro,contr1_inter,contr1_fecha1,contr1_fecha2,contr1_fecha3,contr1_fecha4,contr1_fecha5,contr1_fecha6,contr1_fecha7,contr1_fecha8,contr1_dispos)
--			     values (registro.contr_id,registro.contr_locador,registro.contr_locatario,registro.contr_idsubt,regi.unif_codigo,registro.contr_garantia,registro.contr_step,registro.contr_facturable,registro.contr_leyenda,registro.contr_estado,registro.contr_metros,registro.contr_puxmtro,registro.contr_inter,registro.contr_fecha1,registro.contr_fecha2,registro.contr_fecha3,registro.contr_fecha4,registro.contr_fecha5,registro.contr_fecha6,registro.contr_fecha7,registro.contr_fecha8,registro.contr_dispos);
--			ret:='t';
--		    end if;
--		    anterior:=regi.unif_codigo;		
--		end loop; 
--	end loop; 



	for regi3 in select 
	    * from contratos1 where contr1_locador=usuario  
	    loop
		select contr_unifun into anterior from contratos where contr_id=regi3.contr1_id and contr_unifun=regi3.contr1_unifun;
		if not found then
		    insert into contratos (contr_locador,contr_locatario,contr_idsubt,contr_unifun,contr_garantia,contr_step,contr_facturable,contr_leyenda,contr_estado,contr_metros,contr_puxmtro,contr_inter,contr_fecha1,contr_fecha2,contr_fecha3,contr_fecha4,contr_fecha5,contr_fecha6,contr_fecha7,contr_fecha8,contr_dispos)
    		     values (regi3.contr1_locador,regi3.contr1_locatario,regi3.contr1_idsubt,regi3.contr1_unifun,regi3.contr1_garantia,regi3.contr1_step,regi3.contr1_facturable,regi3.contr1_leyenda,regi3.contr1_estado,regi3.contr1_metros,regi3.contr1_puxmtro,regi3.contr1_inter,regi3.contr1_fecha1,regi3.contr1_fecha2,regi3.contr1_fecha3,regi3.contr1_fecha4,regi3.contr1_fecha5,regi3.contr1_fecha6,regi3.contr1_fecha7,regi3.contr1_fecha8,regi3.contr1_dispos);
		end if;
	end loop; 


    return ret;
    end;$_$;


ALTER FUNCTION public.arrecontr(integer) OWNER TO zona;

--
-- Name: arreglo4030(integer, integer, numeric, numeric, smallint, smallint); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION arreglo4030(integer, integer, numeric, numeric, smallint, smallint) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	usuario		ALIAS FOR $1; 
	tope		ALIAS FOR $2; 
	tarifamayor	ALIAS FOR $3; 
	tarifamenor	ALIAS FOR $4; 
	anio		ALIAS FOR $5; 
	mes		ALIAS FOR $6; 
	ret 		integer;
	cuantos		int4;
    BEGIN
    ret:=0;

    select count(*) into cuantos from almacen where alm_estado=1 and alm_idusu=usuario and alm_retiro is null;

    ret:=cuantos;

    if int4gt(cuantos,tope) then
	    update almacen set alm_tarifa=tarifamayor where alm_estado=1 and alm_idusu=usuario;    
	    update confactur set cfc_precio=tarifamayor,cfc_importe=cfc_dias*tarifamayor where cfc_anio=anio and cfc_mes=mes and cfc_usuario=usuario and cfc_idart=11 and cfc_ptov=2;
	else    
	    update almacen set alm_tarifa=tarifamenor where alm_estado=1 and alm_idusu=usuario;    
	    update confactur set cfc_precio=tarifamenor,cfc_importe=cfc_dias*tarifamenor where cfc_anio=anio and cfc_mes=mes and cfc_usuario=usuario and cfc_idart=11 and cfc_ptov=2;
    end if;    
    
return ret;
	
    END;$_$;


ALTER FUNCTION public.arreglo4030(integer, integer, numeric, numeric, smallint, smallint) OWNER TO zona;

--
-- Name: arreglo_cantcompret(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION arreglo_cantcompret(integer, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
DECLARE
operacion	ALIAS FOR $1; 	-- id de la Operacion
modo		ALIAS FOR $2; 	-- 1 arregla cantcomp
				-- 2 arregla cantret
cuantos		numeric;
registro 	RECORD;
retval 		boolean;
BEGIN

retval:='f';

if int4ne(operacion,0) then    
	if int4eq(modo,2) then        

		for registro in select sitem_id as x
    		    from subitem where sitem_idoper = operacion
			loop
			    cuantos:=0;
			    select sum(ret_cantidad) into cuantos from retiros 
				where ret_idsitem=registro.x 
				      and int2eq(estadop(ret_idopera),101::int2);

			    update subitem set sitem_cantret=cuantos
				where sitem_id=registro.x;
			end loop; 

	    else

		for registro in select sitem_id as x
    		    from subitem where sitem_idoper = operacion
			loop
			    cuantos:=0;
			    select sum(ret_cantidad) into cuantos from retiros 
				where ret_idsitem=registro.x 
				      and int2lt(estadop(ret_idopera),100::int2);

			    update subitem set sitem_cantcomp=cuantos
				where sitem_id=registro.x;
			end loop; 

retval:='t';

	end if;    

    else

	if int4eq(modo,2) then        

		for registro in select sitem_id as x
    		    from subitem 
			loop
			    cuantos:=0;
			    select sum(ret_cantidad) into cuantos from retiros 
				where ret_idsitem=registro.x 
				      and int2eq(estadop(ret_idopera),101::int2);

			    update subitem set sitem_cantret=cuantos
				where sitem_id=registro.x;
			end loop; 

	    else

		for registro in select sitem_id as x
    		    from subitem 
			loop
			    cuantos:=0;
			    select sum(ret_cantidad) into cuantos from retiros 
				where ret_idsitem=registro.x 
				      and int2lt(estadop(ret_idopera),100::int2);

			    update subitem set sitem_cantcomp=cuantos
				where sitem_id=registro.x;
			end loop; 

retval:='t';

	end if;    


end if;    

RETURN retval;
END;$_$;


ALTER FUNCTION public.arreglo_cantcompret(integer, integer) OWNER TO zona;

--
-- Name: arreglo_importo(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION arreglo_importo(integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	caratul		ALIAS FOR $1; -- id de la Caratula.
	despachos	text;
	xx		int4;
	retval		boolean;
	registro	record;
    BEGIN
	
	select despacho into despachos from caratula where car_id=caratul;

	select items_idcaratula into xx from items where items_idcaratula=caratul;
	if not found then
		update items set items_idcaratula=caratul where bpchareq(despachos,items_despacho);
		update items set codigo_articulo=modelo_articulo where items_idcaratula=caratul and trim(codigo_articulo) like '';
		update items set codigo_articulo=descrip_articulo where items_idcaratula=caratul and trim(codigo_articulo) like '';
		update items set codigo_articulo=marca_articulo where items_idcaratula=caratul and trim(codigo_articulo) like '';
		update items set codigo_articulo='S/C' where items_idcaratula=caratul and trim(codigo_articulo) like '';
	end if;

	retval:='t';

    RETURN retval;
    END;$_$;


ALTER FUNCTION public.arreglo_importo(integer) OWNER TO zona;

--
-- Name: articdeocb(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION articdeocb(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select ocb_articc from ocb where ocb_id = $1;$_$;


ALTER FUNCTION public.articdeocb(integer) OWNER TO zona;

--
-- Name: articderb(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION articderb(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select rb_articc from requeb where rb_id = $1;$_$;


ALTER FUNCTION public.articderb(integer) OWNER TO zona;

--
-- Name: articdesitem(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION articdesitem(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select sitem_artic from subitem where sitem_id= $1 ;$_$;


ALTER FUNCTION public.articdesitem(integer) OWNER TO zona;

--
-- Name: articulodewret2(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION articulodewret2(integer) RETURNS character
    LANGUAGE sql
    AS $_$select a.wsitem_codart from wsubitem a, wret2 b where a.wsitem_id=b.wret2_idsitem and b.wret2_id= $1 ;$_$;


ALTER FUNCTION public.articulodewret2(integer) OWNER TO zona;

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

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

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

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

--
-- Name: astcdecompchq(character varying, integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION astcdecompchq(character varying, integer, integer) RETURNS integer
    LANGUAGE sql
    AS $_$select astc_id from astoctas where astc_codemp=1 and astc_idptov=$2 and bpchareq(codcomp(astc_comprob)::varchar, $1::varchar) and astc_numero= $3 and astc_ctacble=10 limit 1 ;$_$;


ALTER FUNCTION public.astcdecompchq(character varying, integer, integer) OWNER TO zona;

--
-- Name: astcdecompchqn(character varying, integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION astcdecompchqn(character varying, integer, integer) RETURNS integer
    LANGUAGE sql
    AS $_$select astc_id from astoctas where astc_codemp=1 and astc_idptov=$2 and bpchareq(codcomp(astc_comprob)::varchar, $1::varchar) and astc_numero= $3 and astc_ctacble=10 and astc_importe<0 limit 1 ;$_$;


ALTER FUNCTION public.astcdecompchqn(character varying, integer, integer) OWNER TO zona;

--
-- Name: astcdecompchqp(character varying, integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION astcdecompchqp(character varying, integer, integer) RETURNS integer
    LANGUAGE sql
    AS $_$select astc_id from astoctas where astc_codemp=1 and astc_idptov=$2 and bpchareq(codcomp(astc_comprob)::varchar, $1::varchar) and astc_numero= $3 and astc_ctacble=10 and astc_importe>0 limit 1 ;$_$;


ALTER FUNCTION public.astcdecompchqp(character varying, integer, integer) OWNER TO zona;

--
-- Name: astcdecompxctacte(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

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


ALTER FUNCTION public.astcdecompxctacte(integer, integer, integer) OWNER TO zona;

--
-- Name: astcdecompxctacte2(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

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


ALTER FUNCTION public.astcdecompxctacte2(integer, integer, integer) OWNER TO zona;

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

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

--
-- Name: auto_adentro(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION auto_adentro(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select iol_liviano from inoutliv where iol_estado=1 and iol_liviano= $1 ;$_$;


ALTER FUNCTION public.auto_adentro(integer) OWNER TO zona;

--
-- Name: borro_la_operacion(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION borro_la_operacion(integer) 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.borro_la_operacion(integer) OWNER TO zona;

--
-- Name: borro_todo_ingre(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION borro_todo_ingre(integer, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	operacion		ALIAS FOR $1; -- id  Operacion
	cholo			ALIAS FOR $2; -- id  Operador
	estado_operacion	int2;
	salidas 		numeric;
	ret boolean;
	aux_texto 		text;
    BEGIN
    ret:=true;
    select op_estado into estado_operacion from
	 operaciones where op_id=operacion;

    if int2eq(estado_operacion,1::int2) 	-- A Futuro
	then
	delete from subitem where sitem_idoper=operacion;	
	delete from item where item_idoper=operacion;	
    	update operaciones set op_estado=999 where op_id=operacion;
    end if;

    if int2eq(estado_operacion,101::int2) 	-- Oficializada
	then
	select sum(sitem_cantret)+sum(sitem_cantcomp) into salidas 
	    from subitem where sitem_idoper=operacion;
--	raise notice 'oficializada ';
	if(numeric_ne(salidas,0::numeric)) then
	aux_texto:='No se puede Anular esta operacion por existir retiros o reexpediciones ';
	insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
--      raise notice 'No se puede Anular esta operacion por existir retiros o reexpediciones ';
	else
    	    update operaciones set op_estado=102 where op_id=operacion;
	    update subitem set sitem_estado=3 where sitem_idoper=operacion;
	    insert into modopub (mod_idoperador,mod_idoper,mod_modalidad,mod_estado) values(cholo,operacion,'A', 1);
--	    raise notice 'la op paso a 102 ';
	end if;

    end if;

    if int2eq(estado_operacion,102::int2) 	-- Modificada
	then
	    if(check_autorizacion(operacion,cholo))
	    then
    	    update operaciones set op_estado=999 where op_id=operacion;
	    delete from subitem where sitem_idoper=operacion;	
	    delete from item where item_idoper=operacion;	
--	    raise notice 'la op paso a 999 ';
	    end if;
    end if;

return ret;
	
    END;$_$;


ALTER FUNCTION public.borro_todo_ingre(integer, integer) OWNER TO zona;

--
-- Name: bzaconfactur(date, date, smallint, smallint); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION bzaconfactur(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 opervehi where opv_est_camion=50 and date_ge(date(opv_fecha_egr),desde) and date_le(date(opv_fecha_egr),hasta) and opv_pesa='S' and opv_nro_ticket is not null and opv_idoper>10
	loop

	ret:='f';
	select op_directo,op_indirecto,op_tipoper into directo,indirecto,tipoper from operaciones where op_id=registro.opv_idoper;

	select cfc_id into hay from confactur where cfc_idoper=registro.opv_idoper and cfc_ticket=registro.opv_nro_ticket;
	if not found then
	    if directo is not null then
		auxot:=substr(nomusu(indirecto),1,25) || ' / ' || substr(traigo_simbtipoper(tipoper),1,3) || '-'|| nrotaldiroper(registro.opv_idoper);
--		insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_idoper,cfc_leyen,cfc_estado,cfc_ticket,cfc_anio,cfc_mes,cfc_indirecto) values (directo,registro.opv_fecha_egr,40::int4,1::numeric,15::numeric,15::numeric,registro.opv_idoper,auxot,1::int2,registro.opv_nro_ticket,anio,mes,indirecto);
		insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_idoper,cfc_leyen,cfc_estado,cfc_ticket,cfc_anio,cfc_mes,cfc_indirecto) values (directo,registro.opv_fecha_egr,40::int4,1::numeric,valtari(directo,40,0::numeric,0::int2,registro.opv_fecha_egr::date),valtari(directo,40,0::numeric,0::int2,registro.opv_fecha_egr::date),registro.opv_idoper,auxot,1::int2,registro.opv_nro_ticket,anio,mes,indirecto);
	    end if;
	end if;

end loop; 

return ret;
end;$_$;


ALTER FUNCTION public.bzaconfactur(date, date, smallint, smallint) OWNER TO zona;

--
-- Name: calcnd(integer, integer, integer, numeric, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION calcnd(integer, integer, integer, numeric, integer) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
declare
idastoh		 alias for $1;
elcliente	 alias for $2;
nrogpo		 alias for $3;
totpag		 alias for $4;
modo		 alias for $5;
ret 		 numeric;
registro	 record;
regi		 record;
regi2		 record;
codemp		 integer;
idpto		 integer;
tipct		 integer;
ctadxv		 integer;
ctabco		 integer;
ctachq		 integer;
ctadocu		 integer;
salgrup		 numeric;
llevo		 numeric;
interd		 numeric;
prompago	 date;
divis		 numeric;
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 and astc_estado=2;
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,7,8,9,10,11) and contr_inter is not null order by contr_id desc limit 1;
select valvaramb(codemp,0,'VALMINND') into valmin;   

if(numeric_le(totpag,salgrup)) then
    salgrup:=totpag;
end if;

RAISE NOTICE 'SALDO: %',salgrup;

idpto:=6;

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

tempor:=0;
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:= 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; 

divis:=(tempor / totpag)::integer;
RAISE NOTICE 'TEMPOR: %, TOTPAG %, DIV %',tempor,totpag,divis;
select ('01-01-1900'::date + (tempor / totpag)::integer) into prompago;
RAISE NOTICE 'PROMPAGO: %',prompago;

llevo:=0;
for registro in select 
     * from astoctas where astc_codemp=codemp and astc_ctacble=ctadxv and astc_ctacte=elcliente and astc_grupo=nrogpo and astc_idastoh!=idastoh and astc_estado=2 order by astc_fecval asc ,astc_idastoh asc
loop
    if(numeric_gt(salgrup,0::numeric)) then
	if(numeric_le(registro.astc_importe,salgrup) and numeric_gt(registro.astc_importe,0::numeric)) then
	    RAISE NOTICE 'FACTURA %,LLEVO: %, SALDO %, IMPORTE %, PROMPAGO %, FECVTO %, INTERD %, PROMPAGOVSFECVTO %',registro.astc_numero,llevo, salgrup,registro.astc_importe,prompago,registro.astc_fecvto,interd,(prompago - registro.astc_fecvto);
	    llevo:= llevo + (registro.astc_importe * (prompago - registro.astc_fecvto) * interd / 100 / 30);
	    salgrup:= salgrup - registro.astc_importe;
	    RAISE NOTICE 'LLEVO: %, SALDO %',llevo, salgrup;
	else 
	    if(numeric_gt(registro.astc_importe,salgrup) and numeric_gt(registro.astc_importe,0::numeric)) then
		RAISE NOTICE 'FACTURA %, LLEVO: %, SALDO %, PROMPAGO %, FECVTO %, INTERD %, PROMPAGOVSFECVTO %',registro.astc_numero,llevo, salgrup,prompago,registro.astc_fecvto,interd,(prompago - registro.astc_fecvto);
		llevo:=llevo + (salgrup * (prompago - registro.astc_fecvto) * interd  / 100 / 30);
		salgrup:= salgrup - registro.astc_importe;
		RAISE NOTICE 'QUEDA SALDO LLEVO: %, SALDO %',llevo, salgrup;
	    else
		if (numeric_lt(registro.astc_importe,0::numeric)) then
		    RAISE NOTICE 'NOTA DE CREDITO %,LLEVO: %, SALDO %, IMPORTE %, PROMPAGO %, FECVTO %, INTERD %, PROMPAGOVSFECVTO %',registro.astc_numero,llevo, salgrup,registro.astc_importe,prompago,registro.astc_fecvto,interd,(prompago - registro.astc_fecvto);
		    if(registro.astc_fecvto is not null) then
			llevo:= llevo + (registro.astc_importe * (prompago - registro.astc_fecvto) * interd / 100 / 30);
		    else
			llevo:= llevo + (registro.astc_importe * (prompago - registro.astc_fecval) * interd / 100 / 30);
		    end if;
		    salgrup:= salgrup - registro.astc_importe;
		    RAISE NOTICE 'LLEVO: %, SALDO %',llevo, salgrup;
		end if;
	    end if;
	end if;
    end if;
end loop; 


if int4eq(modo,1::int4) then
    if numeric_ge(llevo,valmin) then
	ret:=llevo;
    else
	ret:=0;
    end if;
else
    if int4eq(modo,2::int4) then
	ret:=interd;
    end if;
end if;

return ret;
end;$_$;


ALTER FUNCTION public.calcnd(integer, integer, integer, numeric, integer) OWNER TO zona;

--
-- Name: calcnd1(integer, integer, integer, numeric, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION calcnd1(integer, integer, integer, numeric, integer) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
declare
idastoh		 alias for $1;
elcliente	 alias for $2;
nrogpo		 alias for $3;
totpag		 alias for $4;
modo		 alias for $5;
ret 		 numeric;
registro	 record;
regi		 record;
regi2		 record;
codemp		 integer;
idpto		 integer;
tipct		 integer;
ctadxv		 integer;
ctabco		 integer;
ctachq		 integer;
ctadocu		 integer;
salgrup		 numeric;
llevo		 numeric;
cuenta		 numeric;
interd		 numeric;
prompago	 date;
maxvto		 date;
divis		 numeric;
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 and astc_estado=2;
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,7,8,9,10,11) and contr_inter is not null order by contr_id desc limit 1;
select valvaramb(codemp,0,'VALMINND') into valmin;

select max(astc_fecvto) into maxvto from astoctas where astc_codemp=codemp and codcomp(astc_comprob)='FA' and astc_ctacble=ctadxv and astc_ctacte=elcliente and astc_grupo=nrogpo and astc_idastoh!=idastoh and astc_estado=2;
if maxvto is null then
    select max(astc_fecval) into maxvto from astoctas where astc_codemp=codemp and codcomp(astc_comprob)='FA' and astc_ctacble=ctadxv and astc_ctacte=elcliente and astc_grupo=nrogpo and astc_idastoh!=idastoh and astc_estado=2;
end if;

RAISE NOTICE 'FECHA VENCIMIENTO MAXIMA %',maxvto;

idpto:=6;

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

tempor:=0;
llevo:=0;
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
			if date_gt(regi2.chq_fecheq,maxvto) then
			    cuenta:=(regi2.chq_importe * (regi2.chq_fecheq - maxvto) * interd / 30 / 100);
			    RAISE NOTICE 'IMP CHQ %, FECHA CHEQUE %, DIAS %, INTERES %',regi2.chq_importe,regi2.chq_fecheq,(regi2.chq_fecheq - maxvto),interd;
			    llevo:= llevo + cuenta;
			    RAISE NOTICE 'LLEVO %',llevo;
			end if;
		    end loop; 
	    else
		if(int4eq(regi.astc_ctacble,ctadocu)) then
		    for regi2 in select * from docum where doc_idastoc=regi.astc_id
			loop
			    if date_gt(regi2.doc_fecdoc,maxvto) then
				llevo:= llevo + (regi2.doc_importe * (regi2.doc_fecdoc - maxvto) * interd / 30 / 100);
				RAISE NOTICE 'LLEVO %, IMPORTE %, FECHA DOC %, INTERES %',llevo,regi2.doc_importe,regi2.doc_fecdoc,interd;
			    end if;
			end loop; 
	        else
		    if(int4eq(regi.astc_ctacble,ctabco)) then
			if date_gt(regi.astc_fecvto,maxvto) then
			    llevo:= llevo + (regi.astc_importe * (regi.astc_fecvto - maxvto) * interd / 30 / 100);
			    RAISE NOTICE 'LLEVO %, IMPORTE %, FECHA BCO %, INTERES %',llevo,regi.astc_importe,regi.astc_fecvto,interd;
			end if;
		    end if;
		end if;
	    end if;
	end if;
    end loop; 

RAISE NOTICE 'LLEVO %',llevo;

if int4eq(modo,1::int4) then
    if numeric_ge(llevo,valmin) then
	ret:=llevo;
    else
	ret:=0;
    end if;
else
    if int4eq(modo,2::int4) then
	ret:=interd;
    end if;
end if;

return ret;
end;$_$;


ALTER FUNCTION public.calcnd1(integer, integer, integer, numeric, integer) OWNER TO zona;

--
-- Name: calculo_alm(integer, date, integer, smallint, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION calculo_alm(integer, date, integer, smallint, integer) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	cliente		ALIAS FOR $1; 
	fechah		ALIAS FOR $2; 
	opera		ALIAS FOR $3; 
	deposito	ALIAS FOR $4; 
	codemp		ALIAS FOR $5; 
	registro	record;
	regi		record;
	regist		record;
	mal		int2;
	pase		int4;
	aux_texto 	text;
	aux_texto2 	text;
	articulo	integer;
	sigo		integer;
	retval 		numeric;
	valstoc		numeric;
	retire		numeric;
	volumen		numeric;
	precio		numeric;
	importe		numeric;
    BEGIN
    retval:=0;

    select valvaramb(codemp,0,'ARTALM')  into articulo;   

    if(int4ne(cliente,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
	    pase:=1;
	    volumen:=registro.vol_canting;

	    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;

	    select elprecioid(codemp,registro.vol_cliente,articulo) into precio;

	    for regi in select * from volegr where vole_idoperi=registro.vol_idoper and vole_fechaeg>registro.vol_ultfac and vole_fechaeg<=fechah and vole_cantret!=0 and vole_estado!=999
		loop
		    pase:=2;
		    volumen:=volumen - regi.vole_cantret;
		    retval:=retval+ ((regi.vole_fechaeg - registro.vol_ultfac) * regi.vole_cantret * precio);
		end loop;

	    if(volumen) then
		retval:=retval+ ((fechah - registro.vol_ultfac) * volumen * precio);
	    end if;
	end loop;
    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
	    pase:=1;
	    volumen:=registro.vol_canting;

	    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;

	    select elprecioid(codemp,registro.vol_cliente,articulo) into precio;

	    for regi in select * from volegr where vole_idoperi=registro.vol_idoper and vole_fechaeg>registro.vol_ultfac and vole_fechaeg<=fechah and vole_cantret!=0 and vole_estado!=999
		loop
		    pase:=2;
		    volumen:=volumen - regi.vole_cantret;
		    retval:=retval+ ((regi.vole_fechaeg - registro.vol_ultfac) * regi.vole_cantret * precio);
		end loop;

	    if(volumen) then
		retval:=retval+ ((fechah - registro.vol_ultfac) * volumen * precio);
	    end if;
	end loop;
    end if;


    if(int2ne(deposito,0::int2)) then
	for registro in select * from voling where vol_directo=codemp and depositop(vol_idoper)=deposito and vol_estado=101 and vol_ultfac<fechah 
	loop
	    pase:=1;
	    volumen:=registro.vol_canting;

	    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;

	    select elprecioid(codemp,registro.vol_cliente,articulo) into precio;

	    for regi in select * from volegr where vole_idoperi=registro.vol_idoper and vole_fechaeg>registro.vol_ultfac and vole_fechaeg<=fechah and vole_cantret!=0 and vole_estado!=999
		loop
		    pase:=2;
		    volumen:=volumen - regi.vole_cantret;
		    retval:=retval+ ((regi.vole_fechaeg - registro.vol_ultfac) * regi.vole_cantret * precio);
		end loop;

	    if(volumen) then
		retval:=retval+ ((fechah - registro.vol_ultfac) * volumen * precio);
	    end if;
	end loop;
    end if;

    RETURN retval;
    END;$_$;


ALTER FUNCTION public.calculo_alm(integer, date, integer, smallint, integer) OWNER TO zona;

--
-- Name: calculo_funcion(integer, integer, integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION calculo_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;
	registro	record;
	valorfob	text;
	funcion		text;
	funcion2	text;
	funcion3	text;
	cotiz		text;
	peso		text;
	volumen		numeric;
	cantidad	numeric;
	preciopul	numeric;
	precio		numeric;
	sinfun		int4;
	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;

	    funcion:='('||funcion; 
	    funcion:=funcion||')'; 


	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 numeric_eq(preciopul,0) 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
		    funcion:= funcion ||'*'||preciopul; 
		else
		    if(precio) then
			funcion:= funcion ||'*'||precio; 
		    end if;
	    end if;


	    if(funcion like '%FOB%') then
	    pase:=1;
		if int4eq(tabla,1) then
		    select valfob_ahora(idoper) into valorfob;
		end if;
		if int4eq(tabla,2) then
		    select valfob_reti(idoper) into valorfob;
		end if;
		select replace(funcion,'FOB',valorfob) into funcion2;
		select ult_cotiz(1) into cotiz;
		funcion2:= cotiz ||'*'||funcion2; 
		funcion3:=funcion2; 
	    end if;

	    if(funcion3) then
		funcion:=funcion3; 
	    end if;

	    if(funcion like '%VOL%' or funcion like '%PESO%' or funcion like '%CANT%') then
	    pase:=1;
		volumen:=0;
		peso:=0;
		cantidad:=0;

		if int4eq(tabla,1) then
		    select volton_hay(idoper) into valorfob;
		    select vol_modo into modo from voling where vol_idoper=idoper; 
		    if int4eq(modo,1) then volumen:=valorfob; end if;
		    if int4eq(modo,2) then cantidad:=valorfob; end if;
		    if int4eq(modo,3) then peso:=valorfob; end if;
		end if;

		if int4eq(tabla,2) then
		    for registro in select vol_modo as modalidad,sum(vole_cantret) as cuanto from volegr,voling where vole_idoper=idoper 
			and vole_idoperi=vol_idoper  group by 1 
			loop
			    if int4eq(registro.modalidad,1) then volumen:=registro.cuanto; end if;
			    if int4eq(registro.modalidad,2) then cantidad:=registro.cuanto; end if;
			    if int4eq(registro.modalidad,3) then peso:=registro.cuanto; end if;
			end loop;
		end if;

		select replace(funcion,'VOL',volumen) into funcion2;
		select replace(funcion2,'PESO',peso) into funcion;
		select replace(funcion,'CANT',cantidad) into funcion2;

		funcion3:=funcion2; 
	    end if;

	    if int4eq(pase,0) then
		funcion3:=funcion;
	    end if;

	    select eval_funcion(funcion3) into retval;

	  else

	    if numeric_gt(preciopul,0) then
		    retval:=preciopul; 
		else
		    if(precio) then
			retval:= precio; 
		    end if;
	    end if;

	end if;

  else
    if numeric_gt(preciopul,0) then
	    retval:=preciopul; 
		    if(precio) then
			retval:= precio; 
		    end if;
    end if;
end if;


RETURN retval;
END;$_$;


ALTER FUNCTION public.calculo_funcion(integer, integer, integer, integer) OWNER TO zona;

--
-- Name: cambio_estado(integer, smallint, smallint); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cambio_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;
	consign		int4;
	duedepo		int4;
	nrotalzon	int4;
	nrotaldir	int4;
	vencecsg	int4;
	deposito	int2;
	importe		numeric;
	aux_texto 	text;
	aux_motivo 	text;
	mal		int2;
	trans 		boolean;
	trans1 		boolean;
	notid		int4;
	fobopera	numeric;
	foboperai	numeric;
	foboperaim	numeric;
	ret		boolean;
	registro	RECORD;
	registro1	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,consign
	    from operaciones where op_id=operacion;

select unif_usuario into duedepo from unifun where unif_codigo=deposito;


vencecsg:=2;
if(consign is null) then 
    consign:=-1; 
  else 
    select 1 into vencecsg from consig where csg_id = consign and csg_fecvto < date(now()) ; 
end if;

------------------- I N G R E S O S


if(int4lt(tipoper,100::int2))  THEN 
    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);
		foboperaim:=fob_hijos1(operacion,1::int2);
		update operaciones set op_importe=foboperaim,op_impdolar=foboperai WHERE op_id = operacion;
	    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 consign=-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;

	    if(vencecsg=1) then
		aux_texto:='En la Operacion '||traigo_simbtipoper(tipoper)||' '||nrotaldir||' la disposicion de Almacenaje se ha vencido';
		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,sitem_deposito  from subitem where sitem_idoper=operacion and estadunif(sitem_deposito) in (999,500) 
		loop
		    select inh_motivo into aux_motivo from inhabilit where inh_deposito=registro.sitem_deposito order by inh_cont desc limit 1;
		    aux_texto:='En la Operacion '||traigo_simbtipoper(tipoper)||' '||nrotaldir|| ' Hay mercaderia que intenta ingresar en un deposito INHABILITADO ';
		    insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
		end loop; 


--ESTO ES LO NUEVO
--	    for registro1 in select sitem_deposito,count(*) as item  from subitem where sitem_idoper=operacion group by 1 
--		loop
--		    trans1:=hay_cont_valido_new(usuariodepo(registro1.sitem_deposito::int2),directo,registro1.sitem_deposito::int2,operacion,2::int2);
--		end loop; 
--HASTA ACA

	    trans1:=controlo_op(operacion,2);


    END IF;
else
    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 ctacte_ok(directo)!=true THEN 
		select inh_motivo into aux_motivo from inhabilit where inh_usuario=directo order by inh_cont desc limit 1;
		if not found or aux_motivo is null then
		    aux_texto:='Usuario Directo Inhabilitado';
		  else
		    aux_texto:='En la Operacion '||traigo_simbtipoper(tipoper)||' '||nrotaldir||' el usuario directo '||directo||'  ('||nomusu(directo) ||')  esta inhabilitado por '||aux_motivo;
		end if;
		insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
		RAISE NOTICE 'ctacte_okd %',aux_texto;
	    END IF;

	    if ctacte_ok(indirecto)!=true THEN 
		select inh_motivo into aux_motivo from inhabilit where inh_usuario=indirecto order by inh_cont desc limit 1;
		if not found or aux_motivo is null then
		    aux_texto:='Usuario Indirecto Inhabilitado';
		  else
		    aux_texto:='En la Operacion '||traigo_simbtipoper(tipoper)||' '||nrotaldir||' el usuario indirecto '||indirecto||'  ('||nomusu(indirecto) ||')  esta inhabilitado por '||aux_motivo;
		END IF;
		insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
		RAISE NOTICE 'ctacte_oki %',aux_texto;
	    END IF;

	    if(tipoper=105 and consign=-1) then
		aux_texto:='En la Operacion '||traigo_simbtipoper(tipoper)||' '||nrotaldir||' no se ha definio el consignatario';
		insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
	    END IF;

	    if(vencecsg=1) then
		aux_texto:='En la Operacion '||traigo_simbtipoper(tipoper)||' '||nrotaldir||' la disposicion de Almacenaje se ha vencido';
		insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
		RAISE NOTICE 'vencecsg %',aux_texto;
	    END IF;

	    fobopera:=fob_hijos2(operacion,2::int2);

	    for registro in select itemitemdesitem(ret_idsitem) as item, depositem(ret_idsitem) as depositem, sitemcodigo(ret_idsitem) as sitem_codigo from retiros where ret_idopera=operacion and estadunif(depositem(ret_idsitem))=999 
		loop
		    select inh_motivo into aux_motivo from inhabilit where inh_deposito=registro.depositem order by inh_cont desc limit 1;
		    aux_texto:='En la Operacion '||traigo_simbtipoper(tipoper)||' '||nrotaldir|| ' Hay mercaderia que intenta sacar de un deposito INHABILITADO ';
		    insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
		RAISE NOTICE 'itemitemdesitem %',aux_texto;
		end loop; 



--ESTO ES LO NUEVO
--	    for registro1 in select depositem(ret_idsitem) as depositem, count(*) as item  from retiros where ret_idopera=operacion group by 1 
--		loop
--		    trans1:=hay_cont_valido_new(usuariodepo(registro1.depositem::int2),directo,registro1.depositem::int2,operacion,2::int2);
--		end loop; 
--HASTA ACA

	    trans1:=controlo_op(operacion,2);

	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.cambio_estado(integer, smallint, smallint) OWNER TO zona;

--
-- Name: cambioestadoatodos(smallint, smallint); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cambioestadoatodos(smallint, smallint) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
modalidad	alias for $1;	-- 1 cambia de 11 a   1
				-- 2 cambia de  1 a 101
tipoper		alias for $2;	-- 1 Operaciones de Ingreso
				-- 2 Operaciones de Egreso

registro	RECORD;
operacion	int4;
bien		boolean;
ret 		int4;
begin
ret:=0;

if(int2eq(modalidad,1::int2) and int2eq(tipoper,1::int2))  THEN 
    for registro in select * from operaciones where op_estado=11 and op_tipoper<100
	loop
	    bien:=cambio_estado(registro.op_id,1::int2,1::int2);
	    ret:= ret+1;
	end loop; 
end if;

if(int2eq(modalidad,1::int2) and int2eq(tipoper,2::int2))  THEN 
    for registro in select * from operaciones where op_estado=11 and op_tipoper>100
	loop
	    bien:=cambio_estado(registro.op_id,1::int2,1::int2);
	    ret:= ret+1;
	end loop; 
end if;

return ret;
END;$_$;


ALTER FUNCTION public.cambioestadoatodos(smallint, smallint) OWNER TO zona;

--
-- Name: cantcomp_cantret(integer, smallint); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cantcomp_cantret(integer, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
DECLARE
operacion	ALIAS FOR $1; 	-- id de la Operacion
modalidad	ALIAS FOR $2; 	-- Modalidad sumo o resto 
				--  1=actualizo normal
				--  2=Me arrepiento y corrijo lo ya hecho
registro 	RECORD;
retval 		boolean;
BEGIN

if modalidad=1 then    

	for registro in select ret_idsitem as x, ret_cantidad as y
    	    from retiros where ret_idopera=operacion
		loop
		    update subitem set sitem_cantcomp=sitem_cantcomp - registro.y,
				   sitem_cantret=sitem_cantret + registro.y
			where sitem_id=registro.x;
		end loop; 

    else

	for registro in select ret_idsitem as x, ret_cantidad as y
    	    from retiros where ret_idopera=operacion
		loop
		    update subitem set sitem_cantcomp=sitem_cantcomp + registro.y,
		    	    sitem_cantret=sitem_cantret - registro.y
				where sitem_id=registro.x;
		end loop; 

end if;    
RETURN retval;
END;$_$;


ALTER FUNCTION public.cantcomp_cantret(integer, smallint) OWNER TO zona;

--
-- Name: cantcompdeidsitem(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cantcompdeidsitem(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sitem_cantcomp from subitem where sitem_id= $1 ;$_$;


ALTER FUNCTION public.cantcompdeidsitem(integer) OWNER TO zona;

--
-- Name: cantcompwdeidwsitem(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cantcompwdeidwsitem(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select wsitem_cantcompw from wsubitem where wsitem_id= $1 ;$_$;


ALTER FUNCTION public.cantcompwdeidwsitem(integer) OWNER TO zona;

--
-- Name: cantdispalm(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cantdispalm(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select b.sitem_canting-b.sitem_cantret-b.sitem_cantmala from almacen a, subitem b where b.sitem_id=a.alm_idsitem and a.alm_id= $1 and a.alm_retiro is NULL;$_$;


ALTER FUNCTION public.cantdispalm(integer) OWNER TO zona;

--
-- Name: cantidad_disponible(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cantidad_disponible(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sitem_canting-sitem_cantret-sitem_cantcomp-sitem_cantmala from subitem where sitem_id = $1;$_$;


ALTER FUNCTION public.cantidad_disponible(integer) OWNER TO zona;

--
-- Name: cantidispd(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cantidispd(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sitemd_canting-sitemd_cantret-sitemd_cantcomp-sitemd_cantmala from subitemd where sitemd_id = $1;$_$;


ALTER FUNCTION public.cantidispd(integer) OWNER TO zona;

--
-- Name: cantidisponib(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cantidisponib(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sitem_canting-sitem_cantret-sitem_cantcomp-sitem_cantmala from subitem where sitem_id = $1;$_$;


ALTER FUNCTION public.cantidisponib(integer) OWNER TO zona;

--
-- Name: cantidispw(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cantidispw(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select wsitem_canting-wsitem_cantret-wsitem_cantcomp-wsitem_cantmala-wsitem_cantcompw from wsubitem where wsitem_id = $1;$_$;


ALTER FUNCTION public.cantidispw(integer) OWNER TO zona;

--
-- Name: cantingdeidsitem(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cantingdeidsitem(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sitem_canting from subitem where sitem_id= $1 ;$_$;


ALTER FUNCTION public.cantingdeidsitem(integer) OWNER TO zona;

--
-- Name: cantitem(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cantitem(integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
opid		 alias for $1;
ret 		 int4;
begin
select count(*) into ret from item where item_idoper= opid;
return ret;
end;$_$;


ALTER FUNCTION public.cantitem(integer) OWNER TO zona;

--
-- Name: cantmaladeidsitem(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cantmaladeidsitem(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sitem_cantmala from subitem where sitem_id= $1 ;$_$;


ALTER FUNCTION public.cantmaladeidsitem(integer) OWNER TO zona;

--
-- Name: cantretdeidsitem(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cantretdeidsitem(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sitem_cantret from subitem where sitem_id= $1 ;$_$;


ALTER FUNCTION public.cantretdeidsitem(integer) OWNER TO zona;

--
-- Name: cantreweb(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cantreweb(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sum(wret2_cantidad) from wret2 where wret2_estado<50 and wret2_idsitem= $1 ;$_$;


ALTER FUNCTION public.cantreweb(integer) OWNER TO zona;

--
-- Name: capiposadeitem(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION capiposadeitem(integer, integer) RETURNS character
    LANGUAGE plpgsql
    AS $_$
declare
nroitem		 alias for $1;
nroartic	 alias for $2;
ret 		 varchar;
hay	 	 int4;
auxot		 varchar;
begin

    select trim(item_posa) into ret from item where item_id=nroitem ;

    if (bpchareq(ret,'DESCONOCIDA') or bpchareq(trim(ret),'')) then

	select trim(artic_posa) into ret from articu where artic_id=nroartic;

	if ret is null then 
	    ret:='DESCONOCIDA';
	end if;
    end if;

    ret:=substr(ret,1,4);

return ret;
end;$_$;


ALTER FUNCTION public.capiposadeitem(integer, integer) OWNER TO zona;

--
-- Name: carga_almacenaje(date, date, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION carga_almacenaje(date, date, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
desde		 alias for $1;
hasta		 alias for $2;
usuario		 alias for $3;
ret 		 boolean;
registro	 record;
regi		 record;
regi2		 record;
regi3		 record;
contrato	 int4;
tarifa	 	 numeric;
elusu		 int4;
cantdias	 int4;
begin

ret:='f';
contrato:=-1;
tarifa:=-1;

select (hasta-desde)::int4 into cantdias;

for registro in select 
    * from unifun where unif_usuario=1
    loop
    if(int4eq(usuario,0::int4)) then
	    for regi in select 
		* from subitem,operaciones  where sitem_deposito=registro.unif_codigo and op_id=sitem_idoper and date_ge(op_fechain,desde) and date_le(op_fechain,hasta) and op_estado=101
		loop
		ret:='t';
		select tari_idcontr,tari_importe into contrato,tarifa from tarifas where tari_usuario=regi.sitem_directo and idartdetipp(tiprodsitem(regi.sitem_id))=tari_idart	and estadocontr(tari_idcontr)=1 and tari_fhasta>=hasta;
		if found then 
		    if numeric_eq(tarifa,0::numeric) then
			select valtarico(tari_usuario,tari_idart,0::numeric,0::int2,hasta::date,tari_idcontr,tari_orden) into tarifa from tarifas where tari_usuario=regi.sitem_directo and idartdetipp(tiprodsitem(regi.sitem_id))=tari_idart	and estadocontr(tari_idcontr)=1 and tari_fhasta>=hasta;
		    end if;
		end if;

		if contrato is null then 
		    contrato:=-1;
		end if;

		if tarifa is null then 
		    tarifa:=-1;
		end if;

		delete from almacenaje where al_idsitem=regi.sitem_id;
		insert into almacenaje (al_fech,al_idoper,al_idusu,al_idsitem,al_idcontr,al_canti,al_impdolar,al_fecing,al_ultfac,al_tiprod,al_tarifa,al_leyenda) values (hasta,regi.op_id,regi.sitem_directo,regi.sitem_id,contrato,regi.sitem_canting,regi.sitem_imp_dolar,regi.op_fechain,regi.op_fechain,tiprodsitem(regi.sitem_id),tarifa,traigo_codarticu(regi.sitem_id));
	    end loop; 
	else
	    for regi in select 
		* from subitem,operaciones where sitem_deposito=registro.unif_codigo and sitem_directo=usuario and op_id=sitem_idoper and date_ge(op_fechain,desde) and date_le(op_fechain,hasta) and op_estado=101
		loop
		ret:='t';
		select tari_idcontr,tari_importe into contrato,tarifa from tarifas where tari_usuario=regi.sitem_directo and idartdetipp(tiprodsitem(regi.sitem_id))=tari_idart	and estadocontr(tari_idcontr)=1 and tari_fhasta>=hasta;
		if found then 
		    if numeric_eq(tarifa,0::numeric) then
			select valtarico(tari_usuario,tari_idart,0::numeric,0::int2,hasta::date,tari_idcontr,tari_orden) into tarifa from tarifas where tari_usuario=regi.sitem_directo and idartdetipp(tiprodsitem(regi.sitem_id))=tari_idart	and estadocontr(tari_idcontr)=1 and tari_fhasta>=hasta;
		    end if;
		end if;
		if contrato is null then 
		    contrato:=-1;
		end if;

		if tarifa is null then 
		    tarifa:=-1;
		end if;

		delete from almacenaje where al_idsitem=regi.sitem_id;
		insert into almacenaje (al_fech,al_idoper,al_idusu,al_idsitem,al_idcontr,al_canti,al_impdolar,al_fecing,al_ultfac,al_tiprod,al_tarifa,al_leyenda) values (hasta,regi.op_id,regi.sitem_directo,regi.sitem_id,contrato,regi.sitem_canting,regi.sitem_imp_dolar,regi.op_fechain,regi.op_fechain,tiprodsitem(regi.sitem_id),tarifa,traigo_codarticu(regi.sitem_id));
	    end loop; 
    end if;
end loop; 

update almacenaje set al_retiro=fechainretsitem(al_idsitem) where al_estado=1;
update almacenaje set al_importe=al_impdolar*cotpeso(date(now())) where al_estado=1 and al_impdolar is not null;
update almacenaje set al_dias=(al_retiro-al_ultfac)::int4 where al_estado=1 and al_retiro is not null;
update almacenaje set al_dias=(al_fech-al_ultfac)::int4 where al_estado=1 and al_retiro is null;

for regi3 in select al_idusu, sum(al_importe) as totfob from almacenaje where al_estado=1 and al_tiprod not in (4,5,6,7,8,9,32) group by 1
    loop
    if numeric_gt(regi3.totfob,500000::numeric) then
    tarifa:=0.0057;
      else
	if numeric_gt(regi3.totfob,200000::numeric) then
	    tarifa:=0.0076;
	  else
	    tarifa:=0.0096;
	end if;
    end if;
update almacenaje set al_tarifa=tarifa, al_total=(tarifa * al_importe / cantdias * al_dias) where al_estado=1 and al_importe is not null and al_idusu=regi3.al_idusu and al_tiprod not in (4,5,6,7,8,9,32);
end loop; 

update almacenaje set al_total=(al_tarifa * al_dias) where al_estado=1 and al_tiprod in (4,5,6,7,8,9,32);
update almacenaje set al_tarifa=-1 where al_estado=1 and al_tarifa in (null,0);
update almacenaje set al_total=-100 where al_estado=1 and al_total in (null,0);
update almacenaje set al_dias=-1 where al_estado=1 and al_dias in (null,0);

return ret;
end;$_$;


ALTER FUNCTION public.carga_almacenaje(date, date, integer) OWNER TO zona;

--
-- Name: cargo_egrcant(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cargo_egrcant(integer, integer) RETURNS bigint
    LANGUAGE sql
    AS $_$select count(*) from operaciones where op_tipoper in (101,105) and op_estado=101 and date_part('Year',op_fechain) = $1 and date_part('month',op_fechain) = $2;$_$;


ALTER FUNCTION public.cargo_egrcant(integer, integer) OWNER TO zona;

--
-- Name: cargo_egrfob(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cargo_egrfob(integer, integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sum(op_impdolar) from operaciones where op_tipoper in (101,105) and op_estado=101 and date_part('Year',op_fechain) = $1 and date_part('month',op_fechain) = $2;$_$;


ALTER FUNCTION public.cargo_egrfob(integer, integer) OWNER TO zona;

--
-- Name: cargo_ingcam(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cargo_ingcam(integer, integer) RETURNS bigint
    LANGUAGE sql
    AS $_$select count(opv_pat_chasis) from opervehi,operaciones where op_id=opv_idoper and opv_est_camion=50 and op_estado=101 and date_part('Year',op_fechain) = $1 and date_part('month',op_fechain) = $2;$_$;


ALTER FUNCTION public.cargo_ingcam(integer, integer) OWNER TO zona;

--
-- Name: cargo_ingcam_ins(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cargo_ingcam_ins(integer, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
anio		 alias for $1;
mes		 alias for $2;
fecha		 date;
registro	 record;
registro2	 record;
cant1		 integer;
cant2		 integer;
tipoper		 integer;
begin

for registro in select distinct(opv_fecha_ing::date) as f1,case when op_tipoper in (1,5) then 1 else 101 end as tipop,count(distinct(opv_pat_tractor)) as canti from opervehi,operaciones where op_id=opv_idoper and op_estado=101 and opv_idoper!=2 and date_part('year',opv_fecha_ing)=anio and date_part('month',opv_fecha_ing)=mes and opv_est_camion=50 and opv_pat_tractor is not null group by 1,2 order by 1
loop
    cant1:=0;
    cant2:=0;

    tipoper:=registro.tipop;
    if(int4eq(tipoper,1) or int4eq(tipoper,5)) then
	cant1:=registro.canti;
	update indicador set ind_estado=999 where ind_tipo in (100) and ind_fecha=registro.f1;
	insert into indicador (ind_tipo,ind_anio,ind_mes,ind_valor,ind_estado,ind_fecha) values (100,anio,mes,cant1,1,registro.f1);
    else
	if(int4eq(tipoper,101) or int4eq(tipoper,105)) then
	    cant2:=registro.canti;
	    update indicador set ind_estado=999 where ind_tipo in (101) and ind_fecha=registro.f1;
	    insert into indicador (ind_tipo,ind_anio,ind_mes,ind_valor,ind_estado,ind_fecha) values (101,anio,mes,cant2,1,registro.f1);
	end if;
    end if;

end loop; 

return 1;
end;$_$;


ALTER FUNCTION public.cargo_ingcam_ins(integer, integer) OWNER TO zona;

--
-- Name: cargo_ingcant(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cargo_ingcant(integer, integer) RETURNS bigint
    LANGUAGE sql
    AS $_$select count(*) from operaciones where op_tipoper in (1,5) and op_estado=101 and date_part('Year',op_fechain) = $1 and date_part('month',op_fechain) = $2;$_$;


ALTER FUNCTION public.cargo_ingcant(integer, integer) OWNER TO zona;

--
-- Name: cargo_ingcont(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cargo_ingcont(integer, integer) RETURNS bigint
    LANGUAGE sql
    AS $_$select count(cont_idopv) from contene,operaciones where op_id=cont_idoper and op_estado=101 and date_part('Year',op_fechain) = $1 and date_part('month',op_fechain) = $2;$_$;


ALTER FUNCTION public.cargo_ingcont(integer, integer) OWNER TO zona;

--
-- Name: cargo_ingcont20(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cargo_ingcont20(integer, integer) RETURNS bigint
    LANGUAGE sql
    AS $_$select count(cont_idopv) from contene,operaciones where op_id=cont_idoper and medcontene(cont_clacont)=20 and op_estado=101 and date_part('Year',op_fechain) = $1 and date_part('month',op_fechain) = $2;$_$;


ALTER FUNCTION public.cargo_ingcont20(integer, integer) OWNER TO zona;

--
-- Name: cargo_ingcont40(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cargo_ingcont40(integer, integer) RETURNS bigint
    LANGUAGE sql
    AS $_$select count(cont_idopv) from contene,operaciones where op_id=cont_idoper and medcontene(cont_clacont)=40 and op_estado=101 and date_part('Year',op_fechain) = $1 and date_part('month',op_fechain) = $2;$_$;


ALTER FUNCTION public.cargo_ingcont40(integer, integer) OWNER TO zona;

--
-- Name: cargo_ingcont_ins(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cargo_ingcont_ins(integer, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
anio		 alias for $1;
mes		 alias for $2;
fecha		 date;
registro	 record;
registro2	 record;
cant1		 integer;
cant2		 integer;
cant3		 integer;
cant4		 integer;
begin

for registro in select distinct(opv_fecha_ing::date) as f1,case when op_tipoper in (1,5) then 1 else 101 end as tipop,clac_medida as medida,count(distinct(cont_nrocont)) as canti from opervehi,operaciones,contene,clacont where cont_clacont=clac_codigo and opv_idoper=op_id and cont_idopv=opv_id and opv_idoper!=2 and date_part('year',opv_fecha_ing)=anio and date_part('month',opv_fecha_ing)=mes and opv_est_camion=50 and opv_pat_tractor is not null and op_estado=101 and cont_nrocont::integer!=0 and cont_marcont>0 group by 1,2,3 order by 1
loop
    if(int4eq(registro.medida,20)) then
	if(int4eq(registro.tipop,1)) then
	    cant1:=registro.canti;
	    update indicador set ind_estado=999 where ind_tipo in (120) and ind_fecha=registro.f1;
	    insert into indicador (ind_tipo,ind_anio,ind_mes,ind_valor,ind_estado,ind_fecha) values (120,anio,mes,cant1,1,registro.f1);
	else
	    if(int4eq(registro.tipop,101)) then
		cant3:=registro.canti;
		update indicador set ind_estado=999 where ind_tipo in (122) and ind_fecha=registro.f1;
		insert into indicador (ind_tipo,ind_anio,ind_mes,ind_valor,ind_estado,ind_fecha) values (122,anio,mes,cant3,1,registro.f1);
	    end if;
	end if;
    else
	if(int4eq(registro.medida,40)) then
	    if(int4eq(registro.tipop,1)) then
		cant2:=registro.canti;
		update indicador set ind_estado=999 where ind_tipo in (121) and ind_fecha=registro.f1;
		insert into indicador (ind_tipo,ind_anio,ind_mes,ind_valor,ind_estado,ind_fecha) values (121,anio,mes,cant2,1,registro.f1);
	    else
		if(int4eq(registro.tipop,101)) then
		    cant4:=registro.canti;
		    update indicador set ind_estado=999 where ind_tipo in (123) and ind_fecha=registro.f1;
		    insert into indicador (ind_tipo,ind_anio,ind_mes,ind_valor,ind_estado,ind_fecha) values (123,anio,mes,cant4,1,registro.f1);
		end if;
	    end if;
	end if;
    end if;
end loop; 

return 1;
end;$_$;


ALTER FUNCTION public.cargo_ingcont_ins(integer, integer) OWNER TO zona;

--
-- Name: cargo_ingfob(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cargo_ingfob(integer, integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sum(op_impdolar) from operaciones where op_tipoper in (1,5) and op_estado=101 and date_part('Year',op_fechain) = $1 and date_part('month',op_fechain) = $2;$_$;


ALTER FUNCTION public.cargo_ingfob(integer, integer) OWNER TO zona;

--
-- Name: cargo_op_ins(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cargo_op_ins(integer, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
anio		 alias for $1;
mes		 alias for $2;
fecha		 date;
registro	 record;
registro2	 record;
cant1		 integer;
cant2		 integer;
cant3		 numeric;
cant4		 numeric;
begin


for registro in select distinct(op_fechain::date) as f1,case when op_tipoper in (1,5) then 1 else 101 end as tipop,count(*) as canti from operaciones where op_estado=101 and date_part('Year',op_fechain) = anio and date_part('month',op_fechain) = mes group by 1,2 order by 1
loop
    if(int4eq(registro.tipop,1)) then
	cant1:=registro.canti;
	update indicador set ind_estado=999 where ind_tipo in (3) and ind_fecha=registro.f1;
	insert into indicador (ind_tipo,ind_anio,ind_mes,ind_valor,ind_estado,ind_fecha) values (3,anio,mes,cant1,1,registro.f1);
    else
	if(int4eq(registro.tipop,101)) then
	    cant2:=registro.canti;
	    update indicador set ind_estado=999 where ind_tipo in (4) and ind_fecha=registro.f1;
	    insert into indicador (ind_tipo,ind_anio,ind_mes,ind_valor,ind_estado,ind_fecha) values (4,anio,mes,cant2,1,registro.f1);
	end if;
    end if;
end loop; 


for registro in select distinct(op_fechain::date) as f1,case when op_tipoper in (1,5) then 1 else 101 end as tipop,sum(op_impdolar) as canti from operaciones where op_estado=101 and date_part('Year',op_fechain) = anio and date_part('month',op_fechain) = mes group by 1,2 order by 1
loop
    if(int4eq(registro.tipop,1)) then
	cant3:=registro.canti;
	update indicador set ind_estado=999 where ind_tipo in (1) and ind_fecha=registro.f1;
	insert into indicador (ind_tipo,ind_anio,ind_mes,ind_valor,ind_estado,ind_fecha) values (1,anio,mes,cant3,1,registro.f1);
    else
	if(int4eq(registro.tipop,101)) then
	    cant4:=registro.canti;
	    update indicador set ind_estado=999 where ind_tipo in (2) and ind_fecha=registro.f1;
	    insert into indicador (ind_tipo,ind_anio,ind_mes,ind_valor,ind_estado,ind_fecha) values (2,anio,mes,cant4,1,registro.f1);
	end if;
    end if;
end loop; 



return 1;
end;$_$;


ALTER FUNCTION public.cargo_op_ins(integer, integer) OWNER TO zona;

--
-- Name: cargoalmacen(date, date, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cargoalmacen(date, date, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
desde		 alias for $1;
hasta		 alias for $2;
usuario		 alias for $3;
ret 		 boolean;
registro	 record;
regi		 record;
regi2		 record;
contrato	 int4;
tarifa	 	 numeric;
begin

ret:='f';
contrato:=1;
tarifa:=-1;

for registro in select 
    * from unifun where unif_usuario=1
    loop
    if(int4eq(usuario,0::int4)) then
	    for regi in select 
		* from subitem where sitem_deposito=registro.unif_codigo and tiprodsitem(sitem_id) between 4 and 9 and date_ge(fechainop(sitem_idoper),desde) and date_le(fechainop(sitem_idoper),hasta)  and estadop(sitem_idoper)>100
		loop
		select tari_idcontr,tari_importe into contrato,tarifa from tarifas where tari_usuario=regi.sitem_directo and idartdetipp(tiprodsitem(regi.sitem_id))=tari_idart	and estadocontr(tari_idcontr)=1 and tari_fhasta>=hasta;
		if found then 

		    if numeric_eq(tarifa,0::numeric) then
			select valtarico(tari_usuario,tari_idart,0::numeric,0::int2,hasta::date,tari_idcontr,tari_orden) into tarifa from tarifas where tari_usuario=regi.sitem_directo and idartdetipp(tiprodsitem(regi.sitem_id))=tari_idart	and estadocontr(tari_idcontr)=1 and tari_fhasta>=hasta;
		    end if;

		    insert into almacen (alm_idusu,alm_idsitem,alm_ultfac,alm_tiprod,alm_leyenda,alm_idcontr,alm_tarifa,alm_estado) values (regi.sitem_directo,regi.sitem_id,fechainop(regi.sitem_idoper),tiprodsitem(regi.sitem_id),traigo_codarticu(regi.sitem_id),contrato,tarifa,stepcontr(contrato));

		  else
		    insert into almacen (alm_idusu,alm_idsitem,alm_ultfac,alm_tiprod,alm_leyenda,alm_idcontr,alm_tarifa,alm_estado) values (regi.sitem_directo,regi.sitem_id,fechainop(regi.sitem_idoper),tiprodsitem(regi.sitem_id),traigo_codarticu(regi.sitem_id),3520,1000000::numeric,stepcontr(contrato));
		end if;

	    end loop; 
	else
	    for regi in select 
		* from subitem where sitem_deposito=registro.unif_codigo and tiprodsitem(sitem_id) between 4 and 9 and date_ge(fechainop(sitem_idoper),desde) and date_le(fechainop(sitem_idoper),hasta) and sitem_directo=usuario and estadop(sitem_idoper)>100
		loop
		ret:='t';
		select tari_idcontr,tari_importe into contrato,tarifa from tarifas where tari_usuario=regi.sitem_directo and idartdetipp(tiprodsitem(regi.sitem_id))=tari_idart	and estadocontr(tari_idcontr)=1 and tari_fhasta>=hasta;
		if found then 

		    if numeric_eq(tarifa,0::numeric) then
			select valtarico(tari_usuario,tari_idart,0::numeric,0::int2,hasta::date,tari_idcontr,tari_orden) into tarifa from tarifas where tari_usuario=regi.sitem_directo and idartdetipp(tiprodsitem(regi.sitem_id))=tari_idart	and estadocontr(tari_idcontr)=1 and tari_fhasta>=hasta;
		    end if;

		    insert into almacen (alm_idusu,alm_idsitem,alm_ultfac,alm_tiprod,alm_leyenda,alm_idcontr,alm_tarifa,alm_estado) values (regi.sitem_directo,regi.sitem_id,fechainop(regi.sitem_idoper),tiprodsitem(regi.sitem_id),traigo_codarticu(regi.sitem_id),contrato,tarifa,stepcontr(contrato));
		  else
		    insert into almacen (alm_idusu,alm_idsitem,alm_ultfac,alm_tiprod,alm_leyenda,alm_idcontr,alm_tarifa,alm_estado) values (regi.sitem_directo,regi.sitem_id,fechainop(regi.sitem_idoper),tiprodsitem(regi.sitem_id),traigo_codarticu(regi.sitem_id),3520,1000000::numeric,stepcontr(contrato));
		end if;
	    end loop; 
    end if;
end loop; 

update almacen set alm_retiro=fechainretsitem(alm_idsitem) where alm_estado in (1,100,3);

update almacen set alm_estado=1 where alm_estado in (100,3) and date_ge(alm_retiro,desde) and date_le(alm_retiro,hasta);

return ret;
end;$_$;


ALTER FUNCTION public.cargoalmacen(date, date, integer) OWNER TO zona;

--
-- Name: cbleok(integer, integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cbleok(integer, integer, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	codemp		ALIAS FOR $1; 
	codigo		ALIAS FOR $2;
	empre		ALIAS FOR $3;
	esisti		integer;
	retval 		boolean;
    BEGIN
    retval:='f';
    if int4eq(codemp,empre) then
	    retval:='t';
	else
	    if int4eq(codemp,0) then
		retval:='t';
		select count(*) into esisti from ctacble 
		    where cbl_codemp in (codemp,empre) and cbl_codigo=codigo;
    		if int4gt(esisti,1) then
		    retval:='f';
		end if;
	    end if;
    end if;
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.cbleok(integer, integer, integer) OWNER TO zona;

--
-- Name: check_autorizacion(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION check_autorizacion(integer, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	operacion	ALIAS FOR $1; -- id  Operacion
	operador	ALIAS FOR $2; -- id  Operador
	autorizadopor 	int4;
	retval 		boolean;
	aux_texto 	text;
    BEGIN
    retval:='f';
    select mod_autoriz1 into autorizadopor from modopub where mod_idoper=operacion;
    if autorizadopor is null then
    	    update modopub set mod_autoriz1=operador,mod_fecaut1=now() where mod_idoper=operacion;
	else
	    if int4eq(autorizadopor,operador) then
		    aux_texto:='Ya fue autorizado por usted anteriormente hace falta la autorizacion de otra persona para numericizar el cambio definitivo!!';
		    insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
		else
		    update modopub set mod_autoriz2=operador,mod_fecaut2=now() where 
		    mod_idoper=operacion;	
		    retval:='t';
	    end if;
    end if;		
    RETURN retval;
    END;$_$;


ALTER FUNCTION public.check_autorizacion(integer, integer) OWNER TO zona;

--
-- Name: chkcompvsret(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION chkcompvsret(integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
opid		 alias for $1;
ret 		 boolean;
registro	 record;
cantidad	 numeric(15,5);

begin
for registro in select 
    * from subitem where sitem_estado=1 and sitem_cantcomp!=0
    loop
	select sum(ret_cantidad) into cantidad from retiros where ret_idsitem=registro.sitem_id and estado_opera(ret_idopera)<100 group by ret_idsitem;
	if not found then 
		insert into auxoperv (avh_idoper) values (registro.sitem_id);
	    else
		if (numeric_ne(cantidad,registro.sitem_cantcomp)) then
		    insert into auxoperv (avh_idoper) values (registro.sitem_id * -1);
		end if;
	end if;
end loop; 

ret:='t';
return ret;
end;$_$;


ALTER FUNCTION public.chkcompvsret(integer) OWNER TO zona;

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

CREATE FUNCTION chkmigra(character varying) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
opid		 alias for $1;
ret 		 boolean;
registro	 record;
auxoid 		 int4;
primera		 int4;
begin
primera:=-1;
for registro in select 
    oid as oid 
     from usuarios
	loop
	if(primera<0) then 
		primera:=registro.oid;
	    else
		primera:= primera+1;
	end if;

	if(registro.oid!=primera) then 
		ret:='t';
		primera:=registro.oid;
	    else
		ret:='f';
	end if;
end loop; 

return ret;
end;$_$;


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

--
-- Name: cidart(integer, character varying); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cidart(integer, character varying) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare

indirecto	 alias for $1;
codigo		 alias for $2;
ret		int4;
begin

select artic_id into ret from articu where artic_indirecto=indirecto and
bpchareq(trim(artic_codigo),trim(codigo)) order by artic_id limit 1;

return ret;
end;$_$;


ALTER FUNCTION public.cidart(integer, character varying) OWNER TO zona;

--
-- Name: cidop(integer, integer, integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cidop(integer, integer, integer, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
directo		 alias for $1;
indirecto	 alias for $2;
tipoper		 alias for $3;
numero		 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=numero;

if ret is null then
select op_id into ret from operaciones where op_directo=directo and
op_indirecto=indirecto and op_tipoper=5 and op_nrotaldir=numero;
end if;

return ret;
end;$_$;


ALTER FUNCTION public.cidop(integer, integer, integer, integer) OWNER TO zona;

--
-- Name: cidsitem(integer, smallint, character varying, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cidsitem(integer, smallint, character varying, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
operacion	 alias for $1;
lote		 alias for $2;
compbte		 alias for $3;
articid		 alias for $4;
ret		int4;
begin

    select sitem_id into ret from subitem where 
	sitem_idoper=operacion and
	sitem_artic=articid and
	sitem_codigo=lote and
	bpchareq(sitem_compbte,compbte);
return ret;
end;$_$;


ALTER FUNCTION public.cidsitem(integer, smallint, character varying, integer) OWNER TO zona;

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

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,substr(fecha,7,4)::int2,substr(fecha,4,2)::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 date_le(astc_fecval,fecha) 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; 

	ret:='t';

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


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

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

CREATE FUNCTION cierroop() RETURNS boolean
    LANGUAGE plpgsql
    AS $$
declare
ret 		 boolean;
registro	 record;
regi1		 record;
primera		 int4;
cerrada		 date;
hayalgo		 numeric;
begin
primera:=-1;
ret:='t';
for registro in select 
    auxo_idoper from auxoper where auxo_idoper<100
	loop
	select op_fecha_close into cerrada from operaciones where op_id=registro.auxo_idoper;
	if(cerrada is null) then 
	    select sum(sitem_canting)-sum(sitem_cantret) into hayalgo from subitem where sitem_idoper=registro.auxo_idoper;
	    if(numeric_eq(hayalgo,0)) then
		update operaciones set op_fecha_close=date(now()) where op_id=registro.auxo_idoper;
	    end if;
	end if;
end loop; 

return ret;
end;$$;


ALTER FUNCTION public.cierroop() OWNER TO zona;

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

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

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

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

--
-- Name: closeop(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION closeop(integer) RETURNS date
    LANGUAGE sql
    AS $_$select op_fecha_close from operaciones where op_id= $1 ;$_$;


ALTER FUNCTION public.closeop(integer) OWNER TO zona;

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

CREATE FUNCTION cnunif(character varying) RETURNS smallint
    LANGUAGE sql
    AS $_$select unif_codigo from unifun where bpchareq(unif_newcod, trim($1));$_$;


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

--
-- Name: codartdesitem(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION codartdesitem(integer) RETURNS character
    LANGUAGE sql
    AS $_$select codigodeartic(sitem_artic) from subitem where sitem_id= $1 ;$_$;


ALTER FUNCTION public.codartdesitem(integer) OWNER TO zona;

--
-- Name: codartdewret2(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION codartdewret2(integer) RETURNS character
    LANGUAGE sql
    AS $_$select codigodeartic(a.sitem_artic) from subitem a, wret2 b where a.sitem_id=b.wret2_idsitem and b.wret2_id= $1 ;$_$;


ALTER FUNCTION public.codartdewret2(integer) OWNER TO zona;

--
-- Name: codartic(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION codartic(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select art_codigo from articvta where art_id = $1;$_$;


ALTER FUNCTION public.codartic(integer) OWNER TO zona;

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

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


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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

--
-- Name: codigodeartic(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION codigodeartic(integer) RETURNS character
    LANGUAGE sql
    AS $_$select artic_codigo from articu where artic_id= $1 ;$_$;


ALTER FUNCTION public.codigodeartic(integer) OWNER TO zona;

--
-- Name: codigodearticd(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION codigodearticd(integer) RETURNS character
    LANGUAGE sql
    AS $_$select articd_codigo from articud where articd_id= $1 ;$_$;


ALTER FUNCTION public.codigodearticd(integer) OWNER TO zona;

--
-- Name: codigopordepo(text); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION codigopordepo(text) RETURNS smallint
    LANGUAGE sql
    AS $_$select unif_codigo from unifun where unif_codmaria=trim($1)::int2;$_$;


ALTER FUNCTION public.codigopordepo(text) OWNER TO zona;

--
-- Name: codmzadeunif(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION codmzadeunif(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select a.lot_codmza from lotes a,unilot b where b.unit_idlote=a.lot_id and unil_codunifun = $1;$_$;


ALTER FUNCTION public.codmzadeunif(integer) OWNER TO zona;

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

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


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

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

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

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

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

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

CREATE FUNCTION compadunombre(character varying) RETURNS character
    LANGUAGE sql
    AS $_$select cad_nombre from compadu where bpchareq(cad_codigo::varchar, $1::varchar );$_$;


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

--
-- 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: compbte_fec(character varying, character varying, numeric); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION compbte_fec(character varying, character varying, numeric) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	comp		ALIAS FOR $1; -- Comprobante 
	letra		ALIAS FOR $2; -- letra 
	iva		ALIAS FOR $3; -- importe iva 
    BEGIN
	if trim(comp)!='NK' and trim(comp)!='DK' then
	    if trim(letra)='A' then
		RETURN 1;
	    else
		if trim(letra)='B' then
		    RETURN 6;
		else
		    if trim(letra)='C' then
			RETURN 11;
		    else
			if trim(letra)='E' then
			    RETURN 19;
			else
			    if trim(letra)='G' then
				RETURN 39;
			    else
				if trim(letra)='M' then
				    RETURN 51;
				else
				    if trim(letra)='T' then
					if iva!=0 then
					    RETURN 81;
					else
					    RETURN 83;
					end if;
				    end if;
				end if;
			    end if;
			end if;
		    end if;
		end if;
	    end if;
	else
	    if trim(comp)='NK' then
		if trim(letra)='A' then
		    RETURN 3;
		else
		    if trim(letra)='B' then
			RETURN 8;
		    else
			if trim(letra)='C' then
			    RETURN 13;
			else
			    if trim(letra)='E' then
				RETURN 21;
			    else
				if trim(letra)='M' then
				    RETURN 53;
				else
				    if trim(letra)='G' then
					RETURN 38;
				    else
					if trim(letra)='T' then
					    if iva!=0 then
						RETURN 112;
					    else
						RETURN 111;
					    end if;
					end if;
				    end if;
				end if;
			    end if;
			end if;
		    end if;
		end if;
	    else
		if trim(letra)='A' then
		    RETURN 2;
		else
		    if trim(letra)='B' then
			RETURN 7;
		    else
			if trim(letra)='C' then
			    RETURN 12;
			else
			    if trim(letra)='E' then
				RETURN 20;
			    else
				if trim(letra)='G' then
				    RETURN 37;
				else
				    if trim(letra)='M' then
					RETURN 52;
				    else
					if trim(letra)='T' then
					    if iva!=0 then
						RETURN 115;
					    else
						RETURN 116;
					    end if;
					end if;
				    end if;
				end if;
			    end if;
			end if;
		    end if;
		end if;
	    end if;
	end if;
    END;$_$;


ALTER FUNCTION public.compbte_fec(character varying, character varying, numeric) OWNER TO zona;

--
-- Name: compbteoper(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION compbteoper(integer) RETURNS character
    LANGUAGE sql
    AS $_$select op_compbte from operaciones  where op_id= $1;$_$;


ALTER FUNCTION public.compbteoper(integer) OWNER TO zona;

--
-- Name: compbteret_idalm(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION compbteret_idalm(integer) RETURNS character
    LANGUAGE sql
    AS $_$select compbteoper(b.ret_idopera) from almacen a, retiros b where b.ret_idsitem=a.alm_idsitem and a.alm_id= $1 and a.alm_retiro is not NULL order by ret_id desc limit 1;$_$;


ALTER FUNCTION public.compbteret_idalm(integer) OWNER TO zona;

--
-- Name: compbteret_idsitem(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION compbteret_idsitem(integer) RETURNS character
    LANGUAGE sql
    AS $_$select op_compbte from operaciones a, retiros b where b.ret_idsitem= $1 and b.ret_idopera=a.op_id order by ret_id desc limit 1;$_$;


ALTER FUNCTION public.compbteret_idsitem(integer) OWNER TO zona;

--
-- Name: compbtesitem(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION compbtesitem(integer) RETURNS character
    LANGUAGE sql
    AS $_$select sitem_compbte from subitem where sitem_id = $1;$_$;


ALTER FUNCTION public.compbtesitem(integer) OWNER TO zona;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

--
-- Name: conocimsitem(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION conocimsitem(integer) RETURNS character
    LANGUAGE sql
    AS $_$select op_conocim from operaciones a,subitem b where a.op_id=b.sitem_idoper and b.sitem_id= $1 ;$_$;


ALTER FUNCTION public.conocimsitem(integer) OWNER TO zona;

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

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

--
-- Name: consigdeop(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION consigdeop(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select op_consig from operaciones where op_id= $1 ;$_$;


ALTER FUNCTION public.consigdeop(integer) OWNER TO zona;

--
-- Name: consigdewop(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION consigdewop(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select wop_consig from woperaciones where wop_id= $1 ;$_$;


ALTER FUNCTION public.consigdewop(integer) OWNER TO zona;

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

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) 
		and contr_unifun=unifun
	    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 zona;

--
-- Name: contindlocador5(integer, integer, smallint, smallint, smallint); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION contindlocador5(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 in (unifusu,5979,5086) 
		and contr_locatario=indlocad 
		and tipo_de_contrato(contr_idsubt) in (2::int2,4::int2,5::int2) 
		and int2eq(contr_estado,1::int2) 
		and contr_unifun=unifun
	    loop
		ret:='t';
	    end loop;

    end if;

end if;

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

return ret;
END;$_$;


ALTER FUNCTION public.contindlocador5(integer, integer, smallint, smallint, smallint) OWNER TO zona;

--
-- Name: contrid_almacen(integer, smallint); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION contrid_almacen(integer, smallint) RETURNS integer
    LANGUAGE sql
    AS $_$select contr_id from contratos where contr_estado= $2 and contr_locador=1  and contr_idsubt in (7,8) and contr_locatario = $1 order by contr_id desc limit 1;$_$;


ALTER FUNCTION public.contrid_almacen(integer, smallint) OWNER TO zona;

--
-- Name: controlo_op(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION controlo_op(integer, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	operacion	ALIAS FOR $1; 
	modo		ALIAS FOR $2; --1 revisa true or false
				      --2 graba noticias
	registro	RECORD;
	r1		RECORD;
	r2		RECORD;
	contrato	integer;
	nrollamada	integer;
	depo		integer;
	sms		text;
	ret		boolean;

    BEGIN

    ret:=true;
    contrato:=null;

    for r1 in select * from operaciones,tipoper where op_id=operacion and top_codigo=op_tipoper loop 
	--Verifico si tienen contrato activo
	if int4ne(r1.op_directo,r1.op_indirecto) then
	    select contr_id into contrato from contratos where contr_locador=r1.op_directo and contr_locatario=r1.op_indirecto and  contr_estado=1;
	    if contrato is null then
		sms:='La operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' no registra contrato vigente entre el usuario directo '||r1.op_directo||' - '||nomusu(r1.op_directo)||' y el usuario indirecto '||r1.op_indirecto||' - '||nomusu(r1.op_indirecto)||' para ninguna unidad funcional.';
		if int4eq(modo,2) then
		    insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,sms);
		end if;
		ret:='f';
	    end if;
	end if;

	--Verifico si pueden almacenar en esa UF
	if r1.op_deposito is not null then
	    select contr_id into contrato from contratos where contr_locador=r1.op_directo and contr_locatario=r1.op_indirecto and contr_unifun=r1.op_deposito and contr_estado=1;
	    if contrato is null then
		select contr_id into contrato from contratos where contr_locatario=r1.op_directo and contr_unifun=r1.op_deposito and tipo_de_contrato(contr_idsubt) in (1,2,4,5,6) and contr_estado=1;
		if contrato is null then
		    sms:='La operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' no registra contrato vigente entre el usuario directo '||r1.op_directo||' - '||nomusu(r1.op_directo)||' y el usuario indirecto '||r1.op_indirecto||' - '||nomusu(r1.op_indirecto)||' para la unidad funcional '||newunif(r1.op_deposito);
		    if int4eq(modo,2) then
			insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,sms);
		    end if;
		    ret:='f';
		end if;
	    end if;

	    --Verifico estado UF
	    if int4lt(r1.op_tipoper,100) then
		select unif_codigo into contrato from unifun where unif_codigo=r1.op_deposito and unif_estado not in (999,500);
		if not found then
		    sms:='La operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' no puede cambiar de estado ya que el deposito '||newunif(r1.op_deposito)||' no esta habilitado';
		    if int4eq(modo,2) then
			insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,sms);
		    end if;
		    ret:='f';
		end if;
	    else
		select unif_codigo into contrato from unifun where unif_codigo=r1.op_deposito and unif_estado not in (999);
		if not found then
		    sms:='La operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' no puede cambiar de estado ya que el deposito '||newunif(r1.op_deposito)||' no esta habilitado';
		    if int4eq(modo,2) then
			insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,sms);
		    end if;
		    ret:='f';
		end if;
	    end if;

	    --Verifico permiso consig para UF
	    if r1.op_consig is not null and int4gt(r1.op_consig,1) then
		select cxu_id into contrato from csgxuf where cxu_idcsg=r1.op_consig and cxu_directo=r1.op_directo and cxu_indirecto=r1.op_indirecto and cxu_unifun=r1.op_deposito and date_le(now()::date,cxu_fecvto) and cxu_estado=1;
		if not found then
		    sms:='En la operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' el consignatario no tiene habilitado operar en el deposito '||newunif(r1.op_deposito);
		    if int4eq(modo,2) then
			insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,sms);
		    end if;
		    ret:='f';
		end if;
	    end if;

	else
	    for r2 in select distinct sitem_deposito from subitem,retiros where ret_idopera=r1.op_id and ret_idsitem=sitem_id loop
		select contr_id into contrato from contratos where contr_locador=r1.op_directo and contr_locatario=r1.op_indirecto and contr_unifun=r2.sitem_deposito and contr_estado=1;
		if contrato is null then
		    select contr_id into contrato from contratos where contr_locatario=r1.op_directo and contr_unifun=r2.sitem_deposito and tipo_de_contrato(contr_idsubt) in (1,2,4,5,6) and contr_estado=1;
		    if contrato is null then
			sms:='La operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' no registra contrato vigente entre el usuario directo '||r1.op_directo||' - '||nomusu(r1.op_directo)||' y el usuario indirecto '||r1.op_indirecto||' - '||nomusu(r1.op_indirecto)||' para la unidad funcional '||newunif(r2.sitem_deposito);
			if int4eq(modo,2) then
			    insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,sms);
			end if;
			ret:='f';
		    end if;
		end if;

		if int4lt(r1.op_tipoper,100) then
		    select unif_codigo into contrato from unifun where unif_codigo=r2.sitem_deposito and unif_estado not in (999,500);
		    if not found then
			sms:='La operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' no puede cambiar de estado ya que el deposito '||newunif(r2.sitem_deposito)||' no esta habilitado';
			if int4eq(modo,2) then
			    insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,sms);
			end if;
			ret:='f';
		    end if;
		else
		    select unif_codigo into contrato from unifun where unif_codigo=r2.sitem_deposito and unif_estado not in (999);
		    if not found then
			sms:='La operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' no puede cambiar de estado ya que el deposito '||newunif(r2.sitem_deposito)||' no esta habilitado';
			if int4eq(modo,2) then
			    insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,sms);
			end if;
			ret:='f';
		    end if;
		end if;


		--Verifico permiso consig para UF
		if r1.op_consig is not null and int4gt(r1.op_consig,1) then
		    select cxu_id into contrato from csgxuf where cxu_idcsg=r1.op_consig and cxu_directo=r1.op_directo and cxu_indirecto=r1.op_indirecto and cxu_unifun=r2.sitem_deposito and date_le(now()::date,cxu_fecvto) and cxu_estado=1;
		    if not found then
			sms:='En la operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' el consignatario no tiene habilitado operar en el deposito '||newunif(r2.sitem_deposito);
			if int4eq(modo,2) then
			    insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,sms);
			end if;
			ret:='f';
		    end if;
		end if;
	    end loop;
	end if;

	--Verifico estado usuario directo
	select usu_codigo into contrato from usuarios where usu_codigo=r1.op_directo and usu_estado=1;
	if not found then
		sms:=' '||r1.op_directo||' - '||nomusu(r1.op_directo)||' y el usuario indirecto '||r1.op_indirecto||' - '||nomusu(r1.op_indirecto)||' para ninguna unidad funcional.';
	    sms:='En la operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' el usuario directo '||r1.op_directo||' - '||nomusu(r1.op_directo)||' esta inactivo';
	    if int4eq(modo,2) then
		insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,sms);
	    end if;
	    ret:='f';
	end if;

	--Verifico estado usuario indirecto
	select usu_codigo into contrato from usuarios where usu_codigo=r1.op_indirecto and usu_estado=1;
	if not found then
	    sms:='En la operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' el usuario indirecto '||r1.op_indirecto||' - '||nomusu(r1.op_indirecto)||' esta inactivo';
	    if int4eq(modo,2) then
		insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,sms);
	    end if;
	    ret:='f';
	end if;

	--Verifico estado Consignatario
	if r1.op_consig is not null and int4gt(r1.op_consig,1) then
	    select csg_id into contrato from consig where csg_id=r1.op_consig and csg_estado=1;
	    if not found then
		sms:='En la operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' el consignatario '||nomconsig(r1.op_consig)||' esta inactivo';
		if int4eq(modo,2) then
		    insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,sms);
		end if;
		ret:='f';
	    end if;
	end if;

    end loop;


    RETURN ret;
    END;$_$;


ALTER FUNCTION public.controlo_op(integer, integer) OWNER TO zona;

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

CREATE FUNCTION controlo_pendientes() RETURNS integer
    LANGUAGE plpgsql
    AS $$
    DECLARE
	registro	RECORD;
	r1		RECORD;
	r2		RECORD;
	operacion	int4;
	contrato	integer;
	nrollamada	integer;
	depo		integer;
	sms		text;
	retval		int4;

    BEGIN

    retval:=2;
    contrato:=null;
    for registro in
	select distinct opv_idoper from opervehi where opv_est_camion < 50 and opv_fecha_egr is null and opv_idoper>10 order by opv_idoper
	loop
	    operacion:=registro.opv_idoper;
	    for r1 in select * from operaciones,tipoper where op_id=operacion and top_codigo=op_tipoper loop 
		--Verifico si tienen contrato activo
		if int4ne(r1.op_directo,r1.op_indirecto) then
		    select contr_id into contrato from contratos where contr_locador=r1.op_directo and contr_locatario=r1.op_indirecto and  contr_estado=1;
		    if contrato is null then
			select max(llam_numero) into nrollamada from llamada where llam_anio=to_char(now(),'YY')::integer;
			if nrollamada is null then
			    nrollamada:=0;
			end if;
			sms:='La operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' tiene un camion pendiente de ingreso, pero el usuario directo '||r1.op_directo||' y el usuario indirecto '||r1.op_indirecto||' no tienen ningun tipo de contrato activo en ninguna unidad funcional.';
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',18,nrollamada,to_char(now(),'YY')::integer,sms);
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',230,nrollamada,to_char(now(),'YY')::integer,sms);
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',292,nrollamada,to_char(now(),'YY')::integer,sms);
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',23,nrollamada,to_char(now(),'YY')::integer,sms);
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',239,nrollamada,to_char(now(),'YY')::integer,sms);
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',364,nrollamada,to_char(now(),'YY')::integer,sms);
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',366,nrollamada,to_char(now(),'YY')::integer,sms);
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',356,nrollamada,to_char(now(),'YY')::integer,sms);
		    end if;
		end if;

		--Verifico si pueden almacenar en esa UF
		if r1.op_deposito is not null then
		    select contr_id into contrato from contratos where contr_locador=r1.op_directo and contr_locatario=r1.op_indirecto and contr_unifun=r1.op_deposito and contr_estado=1;
		    if contrato is null then
			select contr_id into contrato from contratos where contr_locatario=r1.op_directo and contr_unifun=r1.op_deposito and tipo_de_contrato(contr_idsubt) in (1,2,4,5,6) and contr_estado=1;
			if contrato is null then
			    select max(llam_numero) into nrollamada from llamada where llam_anio=to_char(now(),'YY')::integer;
			    if nrollamada is null then
				nrollamada:=0;
			    end if;
			    sms:='La operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' tiene un camion pendiente de ingreso, pero no tiene contrato activo.';
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',18,nrollamada,to_char(now(),'YY')::integer,sms);
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',230,nrollamada,to_char(now(),'YY')::integer,sms);
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',292,nrollamada,to_char(now(),'YY')::integer,sms);
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',23,nrollamada,to_char(now(),'YY')::integer,sms);
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',239,nrollamada,to_char(now(),'YY')::integer,sms);
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',364,nrollamada,to_char(now(),'YY')::integer,sms);
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',366,nrollamada,to_char(now(),'YY')::integer,sms);
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',356,nrollamada,to_char(now(),'YY')::integer,sms);
			end if;
		    end if;

		    --Verifico estado UF
		    select unif_codigo into contrato from unifun where unif_codigo=r1.op_deposito and unif_estado not in (999,500);
		    if not found then
			select max(llam_numero) into nrollamada from llamada where llam_anio=to_char(now(),'YY')::integer;
			if nrollamada is null then
			    nrollamada:=0;
			end if;
			sms:='La operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' tiene un camion pendiente de ingreso, pero el deposito no esta habilitado';
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',18,nrollamada,to_char(now(),'YY')::integer,sms);
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',230,nrollamada,to_char(now(),'YY')::integer,sms);
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',292,nrollamada,to_char(now(),'YY')::integer,sms);
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',23,nrollamada,to_char(now(),'YY')::integer,sms);
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',239,nrollamada,to_char(now(),'YY')::integer,sms);
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',364,nrollamada,to_char(now(),'YY')::integer,sms);
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',366,nrollamada,to_char(now(),'YY')::integer,sms);
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',356,nrollamada,to_char(now(),'YY')::integer,sms);
		    end if;

		    --Verifico permiso consig para UF
		    if r1.op_consig is not null and int4gt(r1.op_consig,1) then
			select cxu_id into contrato from csgxuf where cxu_idcsg=r1.op_consig and cxu_directo=r1.op_directo and cxu_indirecto=r1.op_indirecto and cxu_unifun=r1.op_deposito and date_le(now()::date,cxu_fecvto) and cxu_estado=1;
			if not found then
			    select max(llam_numero) into nrollamada from llamada where llam_anio=to_char(now(),'YY')::integer;
			    if nrollamada is null then
				nrollamada:=0;
			    end if;
			    sms:='La operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' tiene un camion pendiente de ingreso, pero el consignatario no tiene habilitado operar en el deposito seleccionado';
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',18,nrollamada,to_char(now(),'YY')::integer,sms);
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',230,nrollamada,to_char(now(),'YY')::integer,sms);
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',292,nrollamada,to_char(now(),'YY')::integer,sms);
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',23,nrollamada,to_char(now(),'YY')::integer,sms);
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',239,nrollamada,to_char(now(),'YY')::integer,sms);
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',364,nrollamada,to_char(now(),'YY')::integer,sms);
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',366,nrollamada,to_char(now(),'YY')::integer,sms);
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',356,nrollamada,to_char(now(),'YY')::integer,sms);
			end if;
		    end if;

		else

		    for r2 in select distinct sitem_deposito from subitem,retiros where ret_idopera=r1.op_id and ret_idsitem=sitem_id loop

			select contr_id into contrato from contratos where contr_locador=r1.op_directo and contr_locatario=r1.op_indirecto and contr_unifun=r2.sitem_deposito and contr_estado=1;
			if contrato is null then
			    select contr_id into contrato from contratos where contr_locatario=r1.op_directo and contr_unifun=r2.sitem_deposito and tipo_de_contrato(contr_idsubt) in (1,2,4,5,6) and contr_estado=1;
			    if contrato is null then
				select max(llam_numero) into nrollamada from llamada where llam_anio=to_char(now(),'YY')::integer;
				if nrollamada is null then
				    nrollamada:=0;
				end if;
				sms:='La operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' tiene un camion pendiente de ingreso, pero no tiene contrato activo.';
				nrollamada:=nrollamada+1;
				insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',18,nrollamada,to_char(now(),'YY')::integer,sms);
				nrollamada:=nrollamada+1;
				insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',230,nrollamada,to_char(now(),'YY')::integer,sms);
				nrollamada:=nrollamada+1;
				insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',292,nrollamada,to_char(now(),'YY')::integer,sms);
				nrollamada:=nrollamada+1;
				insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',23,nrollamada,to_char(now(),'YY')::integer,sms);
				nrollamada:=nrollamada+1;
				insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',239,nrollamada,to_char(now(),'YY')::integer,sms);
				nrollamada:=nrollamada+1;
				insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',364,nrollamada,to_char(now(),'YY')::integer,sms);
				nrollamada:=nrollamada+1;
				insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',366,nrollamada,to_char(now(),'YY')::integer,sms);
				nrollamada:=nrollamada+1;
				insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',356,nrollamada,to_char(now(),'YY')::integer,sms);
			    end if;
			end if;

			select unif_codigo into contrato from unifun where unif_codigo=r2.sitem_deposito and unif_estado not in (999,500);
			if not found then
			    select max(llam_numero) into nrollamada from llamada where llam_anio=to_char(now(),'YY')::integer;
			    if nrollamada is null then
				nrollamada:=0;
			    end if;
			    sms:='La operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' tiene un camion pendiente de ingreso, pero el deposito no esta habilitado';
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',18,nrollamada,to_char(now(),'YY')::integer,sms);
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',230,nrollamada,to_char(now(),'YY')::integer,sms);
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',292,nrollamada,to_char(now(),'YY')::integer,sms);
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',23,nrollamada,to_char(now(),'YY')::integer,sms);
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',239,nrollamada,to_char(now(),'YY')::integer,sms);
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',364,nrollamada,to_char(now(),'YY')::integer,sms);
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',366,nrollamada,to_char(now(),'YY')::integer,sms);
			    nrollamada:=nrollamada+1;
			    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',356,nrollamada,to_char(now(),'YY')::integer,sms);
			end if;

			--Verifico permiso consig para UF
			if r1.op_consig is not null and int4gt(r1.op_consig,1) then
			    select cxu_id into contrato from csgxuf where cxu_idcsg=r1.op_consig and cxu_directo=r1.op_directo and cxu_indirecto=r1.op_indirecto and cxu_unifun=r2.sitem_deposito and date_le(now()::date,cxu_fecvto) and cxu_estado=1;
			    if not found then
				select max(llam_numero) into nrollamada from llamada where llam_anio=to_char(now(),'YY')::integer;
				if nrollamada is null then
				    nrollamada:=0;
				end if;
				sms:='La operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' tiene un camion pendiente de ingreso, pero el consignatario no tiene habilitado operar en el deposito seleccionado';
				nrollamada:=nrollamada+1;
				insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',18,nrollamada,to_char(now(),'YY')::integer,sms);
				nrollamada:=nrollamada+1;
				insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',230,nrollamada,to_char(now(),'YY')::integer,sms);
				nrollamada:=nrollamada+1;
				insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',292,nrollamada,to_char(now(),'YY')::integer,sms);
				nrollamada:=nrollamada+1;
				insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',23,nrollamada,to_char(now(),'YY')::integer,sms);
				nrollamada:=nrollamada+1;
				insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',239,nrollamada,to_char(now(),'YY')::integer,sms);
				nrollamada:=nrollamada+1;
				insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',364,nrollamada,to_char(now(),'YY')::integer,sms);
				nrollamada:=nrollamada+1;
				insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',366,nrollamada,to_char(now(),'YY')::integer,sms);
				nrollamada:=nrollamada+1;
				insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',356,nrollamada,to_char(now(),'YY')::integer,sms);
			    end if;
			end if;


		    end loop;
		end if;

		--Verifico estado usuario directo
		select usu_codigo into contrato from usuarios where usu_codigo=r1.op_directo and usu_estado=1;
		if not found then
		    select max(llam_numero) into nrollamada from llamada where llam_anio=to_char(now(),'YY')::integer;
		    if nrollamada is null then
			nrollamada:=0;
		    end if;
		    sms:='La operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' tiene un camion pendiente de ingreso, pero el usuario directo esta inactivo';
		    nrollamada:=nrollamada+1;
		    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',18,nrollamada,to_char(now(),'YY')::integer,sms);
		    nrollamada:=nrollamada+1;
		    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',230,nrollamada,to_char(now(),'YY')::integer,sms);
		    nrollamada:=nrollamada+1;
		    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',292,nrollamada,to_char(now(),'YY')::integer,sms);
		    nrollamada:=nrollamada+1;
		    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',23,nrollamada,to_char(now(),'YY')::integer,sms);
		    nrollamada:=nrollamada+1;
		    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',239,nrollamada,to_char(now(),'YY')::integer,sms);
		    nrollamada:=nrollamada+1;
		    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',364,nrollamada,to_char(now(),'YY')::integer,sms);
		    nrollamada:=nrollamada+1;
		    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',366,nrollamada,to_char(now(),'YY')::integer,sms);
		    nrollamada:=nrollamada+1;
		    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',356,nrollamada,to_char(now(),'YY')::integer,sms);
		end if;

		--Verifico estado usuario indirecto
		select usu_codigo into contrato from usuarios where usu_codigo=r1.op_indirecto and usu_estado=1;
		if not found then
		    select max(llam_numero) into nrollamada from llamada where llam_anio=to_char(now(),'YY')::integer;
		    if nrollamada is null then
			nrollamada:=0;
		    end if;
		    sms:='La operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' tiene un camion pendiente de ingreso, pero el usuario indirecto esta inactivo';
		    nrollamada:=nrollamada+1;
		    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',18,nrollamada,to_char(now(),'YY')::integer,sms);
		    nrollamada:=nrollamada+1;
		    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',230,nrollamada,to_char(now(),'YY')::integer,sms);
		    nrollamada:=nrollamada+1;
		    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',292,nrollamada,to_char(now(),'YY')::integer,sms);
		    nrollamada:=nrollamada+1;
		    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',23,nrollamada,to_char(now(),'YY')::integer,sms);
		    nrollamada:=nrollamada+1;
		    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',239,nrollamada,to_char(now(),'YY')::integer,sms);
		    nrollamada:=nrollamada+1;
		    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',364,nrollamada,to_char(now(),'YY')::integer,sms);
		    nrollamada:=nrollamada+1;
		    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',366,nrollamada,to_char(now(),'YY')::integer,sms);
		    nrollamada:=nrollamada+1;
		    insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',356,nrollamada,to_char(now(),'YY')::integer,sms);
		end if;

		--Verifico estado Consignatario
		if r1.op_consig is not null and int4gt(r1.op_consig,1) then
		    select csg_id into contrato from consig where csg_id=r1.op_consig and csg_estado=1;
		    if not found then
			select max(llam_numero) into nrollamada from llamada where llam_anio=to_char(now(),'YY')::integer;
			if nrollamada is null then
			    nrollamada:=0;
			end if;
			sms:='La operacion '||r1.top_comprob||'-'||r1.op_nrotaldir||' Comprobante: '||r1.op_compbte||' tiene un camion pendiente de ingreso, pero el consignatario esta inactivo';
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',18,nrollamada,to_char(now(),'YY')::integer,sms);
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',230,nrollamada,to_char(now(),'YY')::integer,sms);
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',292,nrollamada,to_char(now(),'YY')::integer,sms);
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',23,nrollamada,to_char(now(),'YY')::integer,sms);
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',239,nrollamada,to_char(now(),'YY')::integer,sms);
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',364,nrollamada,to_char(now(),'YY')::integer,sms);
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',366,nrollamada,to_char(now(),'YY')::integer,sms);
			nrollamada:=nrollamada+1;
			insert into llamada (llam_llamante,llam_llamado,llam_numero,llam_anio,llam_motivo) values ('Mensaje del Sistema',356,nrollamada,to_char(now(),'YY')::integer,sms);
		    end if;
		end if;

	    end loop;
	end loop;


    RETURN retval;
    END;$$;


ALTER FUNCTION public.controlo_pendientes() OWNER TO zona;

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

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

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

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

--
-- Name: ctacte_ok(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION ctacte_ok(integer) RETURNS boolean
    LANGUAGE sql
    AS $_$select (case when usu_estado=1 then 't'::boolean else 'f'::boolean end) from usuarios where usu_codigo= $1 ;$_$;


ALTER FUNCTION public.ctacte_ok(integer) OWNER TO zona;

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

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

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

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

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

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

--
-- Name: cualdepo(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cualdepo(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select unif_codigo from unifun where unif_estado in (1,100,200) and unif_usuario = $1 limit 1;$_$;


ALTER FUNCTION public.cualdepo(integer) OWNER TO zona;

--
-- Name: cuantdepo(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cuantdepo(integer) RETURNS bigint
    LANGUAGE sql
    AS $_$select count(*) from unifun where unif_estado in (1,100,200) and unif_usuario = $1;$_$;


ALTER FUNCTION public.cuantdepo(integer) OWNER TO zona;

--
-- 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: zona
--

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

--
-- Name: cuitconsig(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cuitconsig(integer) RETURNS character
    LANGUAGE sql
    AS $_$select csg_nrocuit from consig where csg_id = $1;$_$;


ALTER FUNCTION public.cuitconsig(integer) OWNER TO zona;

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

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

--
-- Name: cuitusu(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION cuitusu(integer) RETURNS character
    LANGUAGE sql
    AS $_$select usu_nrocuit from usuarios where usu_codigo = $1;$_$;


ALTER FUNCTION public.cuitusu(integer) OWNER TO zona;

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

CREATE FUNCTION depodecompbte(character varying) RETURNS smallint
    LANGUAGE sql
    AS $_$select op_deposito from operaciones where bpchareq(op_compbte,$1) order by op_id limit 1;$_$;


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

--
-- Name: depositem(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION depositem(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select sitem_deposito from subitem where sitem_id= $1 ;$_$;


ALTER FUNCTION public.depositem(integer) OWNER TO zona;

--
-- Name: depositop(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION depositop(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select op_deposito from operaciones where op_id= $1 ;$_$;


ALTER FUNCTION public.depositop(integer) OWNER TO zona;

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

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


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

--
-- Name: descauto(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION descauto(integer) RETURNS character
    LANGUAGE sql
    AS $_$select mar_nombre||'  - Modelo:  '|| mod_nombre from marauto a,modauto b where a.mar_codigo=b.mod_marca  and mod_id = $1 ;$_$;


ALTER FUNCTION public.descauto(integer) OWNER TO zona;

--
-- Name: descautoinout(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION descautoinout(integer) RETURNS character
    LANGUAGE sql
    AS $_$select descauto(lv_modelo) from ingxl,inoutliv,livianos where lv_id=iol_liviano and igxl_iol=iol_id and igxl_io= $1 ;$_$;


ALTER FUNCTION public.descautoinout(integer) OWNER TO zona;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

--
-- Name: descdirdesitem(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION descdirdesitem(integer) RETURNS character
    LANGUAGE sql
    AS $_$select a.usu_codigo||' - '||a.usu_nombre from usuarios a,subitem b where a.usu_codigo=b.sitem_directo and b.sitem_id= $1 ;$_$;


ALTER FUNCTION public.descdirdesitem(integer) OWNER TO zona;

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

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

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

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

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

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

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

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


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

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

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


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

--
-- Name: descgente(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION descgente(integer) RETURNS character
    LANGUAGE sql
    AS $_$select gte_nombre||'  - Docum.:  '|| gte_tdoc ||'  Nro  '||gte_nrodoc from gente where gte_id= $1 ;$_$;


ALTER FUNCTION public.descgente(integer) OWNER TO zona;

--
-- Name: descgentet(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION descgentet(integer) RETURNS character
    LANGUAGE sql
    AS $_$select gte_nombre||'  - Docum.:  '|| gte_tdoc ||'  Nro  '||gte_nrodoc from gente where gte_tarjeta= $1 and gte_estado=1 order by gte_id desc limit 1;$_$;


ALTER FUNCTION public.descgentet(integer) OWNER TO zona;

--
-- Name: descgteio(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION descgteio(integer) RETURNS character
    LANGUAGE sql
    AS $_$select a.gte_nombre||'  -  '|| a.gte_tdoc ||'  -  '||a.gte_nrodoc from gente a,inout b where b.io_gente=a.gte_id and b.io_id= $1 ;$_$;


ALTER FUNCTION public.descgteio(integer) OWNER TO zona;

--
-- Name: descindirdesitem(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION descindirdesitem(integer) RETURNS character
    LANGUAGE sql
    AS $_$select a.usu_codigo||' - '||a.usu_nombre from usuarios a,subitem b where a.usu_codigo=b.sitem_indirecto and b.sitem_id= $1 ;$_$;


ALTER FUNCTION public.descindirdesitem(integer) OWNER TO zona;

--
-- Name: descliv(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION descliv(integer) RETURNS character
    LANGUAGE sql
    AS $_$select lv_patente||'   -  Marca: '|| descauto(lv_modelo) from livianos where lv_id = $1 ;$_$;


ALTER FUNCTION public.descliv(integer) OWNER TO zona;

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

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

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

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

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

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

--
-- Name: descrioper(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION descrioper(integer) RETURNS character
    LANGUAGE sql
    AS $_$select traigo_simbtipoper(op_tipoper)||'-'||op_nrotaldir from operaciones where op_id= $1 ;$_$;


ALTER FUNCTION public.descrioper(integer) OWNER TO zona;

--
-- Name: descripdeartic(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION descripdeartic(integer) RETURNS character
    LANGUAGE sql
    AS $_$select artic_descrip from articu where artic_id= $1 ;$_$;


ALTER FUNCTION public.descripdeartic(integer) OWNER TO zona;

--
-- Name: dias_mora(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION dias_mora(integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
idastoh		 alias for $1;
elcliente	 integer;
nrogpo		 integer;
singpo		 integer;
totpag		 numeric;
ret 		 integer;
registro	 record;
regi		 record;
regi2		 record;
codemp		 integer;
idpto		 integer;
tipct		 integer;
ctadxv		 integer;
ctabco		 integer;
ctachq		 integer;
ctadocu		 integer;
salgrup		 numeric;
llevo		 numeric;
primera		 integer;
interd		 numeric;
fechapago	 date;
prompago	 date;
promfact	 date;
entra		 integer;
acum1		 numeric;
acum2		 numeric;
acum3		 numeric;
acum4		 numeric;
tempor		 numeric;
valmin		 numeric;
begin

ret:=0;
llevo:=0;
acum1:=0;
acum2:=0;
acum3:=0;
acum4:=0;
tempor:=0;
primera:=1;
entra:=1;

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 astc_ctacte,astc_grupo,astc_fecval,astc_importe*-1 into elcliente,nrogpo,fechapago,totpag from astoctas where astc_codemp=codemp and astc_ctacble=ctadxv and astc_idastoh=idastoh limit 1;

select sum(astc_importe) into salgrup from astoctas where astc_codemp=codemp and astc_ctacble=ctadxv and astc_ctacte=elcliente and date_le(astc_fecval,fechapago) and astc_idastoh!=idastoh;

if salgrup is null then
    salgrup:=totpag;
end if;

if(numeric_lt(salgrup,totpag)) then
    salgrup:=totpag;
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;



if(numeric_le(salgrup,0::numeric)) then
	select (fechapago - '01-01-1900'::date) * totpag into acum4;
end if;


for registro in select 
     * from astoctas where astc_codemp=codemp and astc_ctacble=ctadxv and astc_ctacte=elcliente and astc_grupo=nrogpo and date_le(astc_fecval,fechapago) order by astc_fecval desc ,astc_idastoh desc
loop
    if(numeric_gt(salgrup,0::numeric)) then
	if(numeric_le(registro.astc_importe,salgrup) and numeric_gt(registro.astc_importe,0::numeric)) then
	    entra:=2;
	    IF(registro.astc_fecvto is null) THEN
		select (registro.astc_fecval - '01-01-1900'::date) * registro.astc_importe into acum3;
	      else
		select (registro.astc_fecvto - '01-01-1900'::date) * registro.astc_importe into acum3;
	    END IF;
	    acum4:=acum4 + acum3;
	    salgrup:= salgrup - registro.astc_importe;
	  else 
	    if(numeric_gt(registro.astc_importe,salgrup) and numeric_gt(registro.astc_importe,0::numeric)) then
		entra:=3;
		IF(registro.astc_fecvto is null) THEN
		    select (registro.astc_fecval - '01-01-1900'::date) * salgrup into acum3;
		  else
		    select (registro.astc_fecvto - '01-01-1900'::date) * salgrup into acum3;
		END IF;
		acum4:=acum4 + acum3;
		salgrup:= salgrup - registro.astc_importe;
	    end if;
	end if;
    end if;
end loop; 

    select ('01-01-1900'::date + (acum4 / totpag)::integer) into promfact;

if int4eq(entra,1) then
    ret:=0;
end if;


ret:= prompago - promfact;

if int4lt(ret,0) then
    ret:=0;
end if;

if int4eq(entra,1) then
    ret:=0;
end if;


return ret;
end;$_$;


ALTER FUNCTION public.dias_mora(integer) OWNER TO zona;

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

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

--
-- Name: diasperdidos(integer, date, date, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION diasperdidos(integer, date, date, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	empleado	ALIAS FOR $1; 
	fechad		ALIAS FOR $2; 
	fechah		ALIAS FOR $3; 
	tipo		ALIAS FOR $4; 
	registro	record;
	inicio		date;
	fin		date;
	difdias		integer;
	depto		integer;
	dias		integer;
	retval 		integer;
    BEGIN
    retval:=0;

    select e_sector into depto from empleados where e_id=empleado;
    if tipo is null then
	for registro in select * from accidentes where a_idemple=empleado and (a_fechaacc<=fechah and (a_fechaalta>=fechad or a_fechaalta is null)) 
	loop
	    if date_lt(registro.a_fechaacc,fechad) then
		inicio:=fechad;
	    else
		inicio:=registro.a_fechaacc+1;
	    end if;
	    if date_ge(registro.a_fechaalta,fechah) or registro.a_fechaalta is null then
		fin:=fechah;
	    else
		fin:=registro.a_fechaalta-1;
	    end if;

	    if date_gt(fin,inicio) then
		difdias:=fin - inicio;
	    else
		difdias:=0;
	    end if;

	    if(int4ne(depto,11)) then
		SELECT count(*) into dias FROM generate_series(0, difdias) i 
						WHERE date_part('dow', inicio::date + i) NOT IN (0,6) and 
							(((date_part('day', inicio + i),date_part('month', inicio + i)) NOT IN (select f_dia,f_mes from feriados where f_modo=1)) and 
				((date_part('day', inicio + i),date_part('month', inicio + i),date_part('year', inicio + i)) NOT IN (select f_dia,f_mes,f_anio from feriados where f_modo=2)));
	    else
		SELECT count(*) into dias FROM generate_series(0, difdias) i 
						WHERE (((date_part('day', inicio + i),date_part('month', inicio + i)) NOT IN (select f_dia,f_mes from feriados where f_modo=1)) and 
							((date_part('day', inicio + i),date_part('month', inicio + i),date_part('year', inicio + i)) NOT IN (select f_dia,f_mes,f_anio from feriados where f_modo=2)));
	    end if;
	    retval:=retval+dias;

	end loop;
    else
	for registro in select * from accidentes where a_idemple=empleado and (a_fechaacc<=fechah and (a_fechaalta>=fechad or a_fechaalta is null)) and a_tipo=tipo
	loop
	    if date_lt(registro.a_fechaacc,fechad) then
		inicio:=fechad;
	    else
		inicio:=registro.a_fechaacc+1;
	    end if;
	    if date_ge(registro.a_fechaalta,fechah) or registro.a_fechaalta is null then
		fin:=fechah;
	    else
		fin:=registro.a_fechaalta-1;
	    end if;

	    if date_gt(fin,inicio) then
		difdias:=fin - inicio;
	    else
		difdias:=0;
	    end if;

raise notice 'i %, f %, dp %',inicio,fin,difdias;


	    if(int4ne(depto,11)) then
		SELECT count(*) into dias FROM generate_series(0, difdias) i 
						WHERE date_part('dow', inicio::date + i) NOT IN (0,6) and 
							(((date_part('day', inicio + i),date_part('month', inicio + i)) NOT IN (select f_dia,f_mes from feriados where f_modo=1)) and 
				((date_part('day', inicio + i),date_part('month', inicio + i),date_part('year', inicio + i)) NOT IN (select f_dia,f_mes,f_anio from feriados where f_modo=2)));
	    else
		SELECT count(*) into dias FROM generate_series(0, difdias) i 
						WHERE (((date_part('day', inicio + i),date_part('month', inicio + i)) NOT IN (select f_dia,f_mes from feriados where f_modo=1)) and 
							((date_part('day', inicio + i),date_part('month', inicio + i),date_part('year', inicio + i)) NOT IN (select f_dia,f_mes,f_anio from feriados where f_modo=2)));
	    end if;
	    retval:=retval+dias;

	end loop;
    end if;


    RETURN retval;
    END;$_$;


ALTER FUNCTION public.diasperdidos(integer, date, date, integer) OWNER TO zona;

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

CREATE FUNCTION diasperdidos(character varying, date, date, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	empleado	ALIAS FOR $1; 
	fechad		ALIAS FOR $2; 
	fechah		ALIAS FOR $3; 
	tipo		ALIAS FOR $4; 
	registro	record;
	inicio		date;
	fin		date;
	difdias		integer;
	depto		integer;
	dias		integer;
	retval 		integer;
    BEGIN
    retval:=0;

    if tipo is null then
	for registro in select * from accidentes where a_externo=empleado and a_idemple is null and (a_fechaacc<=fechah and (a_fechaalta>=fechad or a_fechaalta is null)) 
	loop
	    if date_lt(registro.a_fechaacc,fechad) then
		inicio:=fechad;
	    else
		inicio:=registro.a_fechaacc+1;
	    end if;
	    if date_ge(registro.a_fechaalta,fechah) or registro.a_fechaalta is null then
		fin:=fechah;
	    else
		fin:=registro.a_fechaalta-1;
	    end if;

	    if date_gt(fin,inicio) then
		difdias:=fin - inicio;
	    else
		difdias:=0;
	    end if;

	    SELECT count(*) into dias FROM generate_series(0, difdias) i 
						WHERE date_part('dow', inicio::date + i) NOT IN (0,6) and 
							(((date_part('day', inicio + i),date_part('month', inicio + i)) NOT IN (select f_dia,f_mes from feriados where f_modo=1)) and 
				((date_part('day', inicio + i),date_part('month', inicio + i),date_part('year', inicio + i)) NOT IN (select f_dia,f_mes,f_anio from feriados where f_modo=2)));
	    retval:=retval+dias;

	end loop;
    else
	for registro in select * from accidentes where a_externo=empleado and a_idemple is null and (a_fechaacc<=fechah and (a_fechaalta>=fechad or a_fechaalta is null)) and a_tipo=tipo
	loop
	    if date_lt(registro.a_fechaacc,fechad) then
		inicio:=fechad;
	    else
		inicio:=registro.a_fechaacc+1;
	    end if;
	    if date_ge(registro.a_fechaalta,fechah) or registro.a_fechaalta is null then
		fin:=fechah;
	    else
		fin:=registro.a_fechaalta-1;
	    end if;

	    if date_gt(fin,inicio) then
		difdias:=fin - inicio;
	    else
		difdias:=0;
	    end if;

	    SELECT count(*) into dias FROM generate_series(0, difdias) i 
						WHERE date_part('dow', inicio::date + i) NOT IN (0,6) and 
							(((date_part('day', inicio + i),date_part('month', inicio + i)) NOT IN (select f_dia,f_mes from feriados where f_modo=1)) and 
				((date_part('day', inicio + i),date_part('month', inicio + i),date_part('year', inicio + i)) NOT IN (select f_dia,f_mes,f_anio from feriados where f_modo=2)));
	    retval:=retval+dias;

	end loop;
    end if;


    RETURN retval;
    END;$_$;


ALTER FUNCTION public.diasperdidos(character varying, date, date, integer) OWNER TO zona;

--
-- Name: direcgente(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION direcgente(integer) RETURNS character varying
    LANGUAGE sql
    AS $_$select gte_direcc||'  Localidad: '||gte_locali from gente where gte_id= $1 ;$_$;


ALTER FUNCTION public.direcgente(integer) OWNER TO zona;

--
-- Name: directodeop(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION directodeop(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select op_directo from operaciones where op_id= $1 ;$_$;


ALTER FUNCTION public.directodeop(integer) OWNER TO zona;

--
-- Name: directodewop(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION directodewop(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select wop_directo from woperaciones where wop_id= $1 ;$_$;


ALTER FUNCTION public.directodewop(integer) OWNER TO zona;

--
-- Name: directodewret2(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION directodewret2(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select a.wsitem_directo from wsubitem a, wret2 b where a.wsitem_id=b.wret2_idsitem and b.wret2_id= $1 ;$_$;


ALTER FUNCTION public.directodewret2(integer) OWNER TO zona;

--
-- Name: directodewsitem(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION directodewsitem(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select wsitem_directo from wsubitem where wsitem_id= $1 ;$_$;


ALTER FUNCTION public.directodewsitem(integer) OWNER TO zona;

--
-- Name: docgente(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION docgente(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select gte_nrodoc from gente where gte_id= $1 ;$_$;


ALTER FUNCTION public.docgente(integer) OWNER TO zona;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

--
-- Name: estadocontr(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION estadocontr(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select contr_estado from contratos where contr_id= $1;$_$;


ALTER FUNCTION public.estadocontr(integer) OWNER TO zona;

--
-- Name: estadoocb(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION estadoocb(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select ocb_estado from ocb where ocb_id = $1;$_$;


ALTER FUNCTION public.estadoocb(integer) OWNER TO zona;

--
-- Name: estadooch(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION estadooch(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select och_estado from och where och_id = $1;$_$;


ALTER FUNCTION public.estadooch(integer) OWNER TO zona;

--
-- Name: estadop(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION estadop(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select op_estado from operaciones where op_id= $1 ;$_$;


ALTER FUNCTION public.estadop(integer) OWNER TO zona;

--
-- Name: estadopv(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION estadopv(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select opv_est_camion from opervehi where opv_id= $1 ;$_$;


ALTER FUNCTION public.estadopv(integer) OWNER TO zona;

--
-- Name: estadunif(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION estadunif(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select unif_estado from unifun where unif_codigo= $1 ;$_$;


ALTER FUNCTION public.estadunif(integer) OWNER TO zona;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

CREATE FUNCTION f_ai_clientes() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    BEGIN
	insert into ctes (cte_nombre,cte_codemp,cte_codigo,cte_tipcta) values (NEW.cli_nombre,NEW.cli_codemp,NEW.cli_codigo,31);
	insert into sucursal (sucu_cliente,sucu_nombre) values (NEW.cli_id,NEW.cli_nombre);
    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_ai_clientes() OWNER TO zona;

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

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

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

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

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

CREATE FUNCTION f_ai_hijcble() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    BEGIN
    update padcble set pc_estado=999 where pc_idcble=NEW.hc_idcble and pc_reg=NEW.hc_reg;
    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_ai_hijcble() OWNER TO zona;

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

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

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

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,vol_canting) values (NEW.op_id,NEW.op_directo,NEW.op_indirecto,idcli(NEW.op_directo,NEW.op_indirecto),NEW.op_compbte,NEW.op_comptrans,NEW.op_volumen);
	end if;
    end if;
    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_ai_operaciones() OWNER TO zona;

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

CREATE FUNCTION f_ai_prove() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    BEGIN
	insert into ctes (cte_nombre,cte_codemp,cte_codigo,cte_tipcta) values (NEW.prov_nombre,NEW.prov_codemp,NEW.prov_id,eval_funcion(valvaramb(NEW.prov_codemp,ptovdefault(NEW.prov_codemp),'TIPCTADXC')));

    if int4eq(NEW.prov_critico,1::int4) THEN 
	insert into criticprov (cp_idprov,cp_valact) values (NEW.prov_id,NEW.prov_critico);
    END IF;

    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_ai_prove() OWNER TO zona;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    if bpcharne(NEW.cli_nombre,OLD.cli_nombre) THEN 
	update ctes set cte_nombre=NEW.cli_nombre where cte_codigo=OLD.cli_id and cte_codemp=OLD.cli_codemp and cte_tipcta=eval_funcion(valvaramb(NEW.cli_codemp,ptovdefault(NEW.cli_codemp),'TIPCTADXV'));
	update sucursal 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 zona;

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

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

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

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

    if(date_ne(OLD.csg_fecvto,NEW.csg_fecvto)) then 
	update csgxuf set cxu_fecvto=NEW.csg_fecvto where cxu_idcsg=NEW.csg_id;
    END IF;

    if(int4ne(OLD.csg_estado,NEW.csg_estado)) then 
	update csgxuf set cxu_estado=NEW.csg_estado where cxu_idcsg=NEW.csg_id;
    END IF;


    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_au_consig() OWNER TO zona;

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

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

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

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_nrocuit=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 zona;

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

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

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

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

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

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

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

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

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

CREATE FUNCTION f_au_och() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
	registro	record;
BEGIN

    if int4eq(NEW.och_estado,999) and int4ne(OLD.och_estado,999) THEN 
	if (int4ge(OLD.och_estado,10) and int4lt(OLD.och_estado,999)) then
	    for registro in select * from rxoc where rxoc_idoch=OLD.och_id loop
		update requeb set rb_cantir=rb_cantir-registro.rxoc_cantas,rb_estado=2 where rb_id=registro.rxoc_idrb;
	    end loop;
	end if;
	delete from recepcionoch where rch_idrxoc in (select rxoc_id from rxoc where rxoc_idoch=OLD.och_id);
	update rxoc set rxoc_estado=999 where rxoc_idoch=OLD.och_id;
	update ocb set ocb_estado=NEW.och_estado where ocb_idoch=OLD.och_id;
    END IF;

    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_au_och() OWNER TO zona;

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

CREATE FUNCTION f_au_operaciones() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
aux_texto 	text;
mal		int2;
trans 		boolean;
notid		int4;
existe		int4;
reg		record;
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,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,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,vol_fechain=NEW.op_fechain,vol_ultfac=NEW.op_fechain 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,vol_fechain=NEW.op_fechain,vol_ultfac=NEW.op_fechain 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: '||NEW.op_operador||' 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 / trae_cotiza(NEW.op_moneda,NEW.op_fechain) where op_id=NEW.op_id;
    update subitem set sitem_imp_dolar=sitem_importe / trae_cotiza(NEW.op_moneda,NEW.op_fechain) 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;

if(int2eq(NEW.op_estado,999::int2) and int2gt(OLD.op_estado,100::int2)) 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;
    update subitem set sitem_estado=999 where sitem_idoper=NEW.op_id+1;
    for reg in select * from retiros where ret_idopera=NEW.op_id loop
	update subitem set sitem_cantret=sitem_cantret-reg.ret_cantidad,sitem_cantcomp=sitem_cantcomp+reg.ret_cantidad where sitem_id=reg.ret_idsitem;
    end loop;
    delete from retiros where ret_idopera=NEW.op_id;
    end if;
end if;

if(int2eq(NEW.op_estado,999::int2) and int4gt(NEW.op_tipoper,100)) then
    delete from controlop where ctp_idoper=NEW.op_id;
end if;

RETURN NEW;
END;$$;


ALTER FUNCTION public.f_au_operaciones() OWNER TO zona;

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

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

    if (timestamp_ne(NEW.opv_fecha_ing,OLD.opv_fecha_ing) or (OLD.opv_fecha_ing is null and NEW.opv_fecha_ing is not null)) then
	    update contene set cont_fecing=NEW.opv_fecha_ing where cont_idopv=NEW.opv_id;
        end if;

    if (timestamp_ne(NEW.opv_fecha_egr,OLD.opv_fecha_egr) or (OLD.opv_fecha_egr is null and NEW.opv_fecha_egr is not null)) then
	    update contene set cont_fecout=NEW.opv_fecha_egr where cont_idopvout=NEW.opv_id;
        end if;



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(OLD.opv_idoper is not null) 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;
END IF;


	select max(log_cont)+1 into cont from modlogs where log_tabla='opervehi' and log_idtabla=NEW.opv_id;
	if cont is null then
	    cont:=1;
	end if;

	if (numeric_ne(NEW.opv_peso_ing,OLD.opv_peso_ing)) then
	    insert into modlogs (log_tabla,log_idtabla,log_campo,log_valant,log_valpos,log_cont) values ('opervehi',NEW.opv_id,'opv_peso_ing',OLD.opv_peso_ing,NEW.opv_peso_ing,cont);
	end if;

	if (numeric_ne(NEW.opv_peso_egr,OLD.opv_peso_egr)) then
	    insert into modlogs (log_tabla,log_idtabla,log_campo,log_valant,log_valpos,log_cont) values ('opervehi',NEW.opv_id,'opv_peso_egr',OLD.opv_peso_egr,NEW.opv_peso_egr,cont);
	end if;

	if (timestamp_ne(NEW.opv_fecha_egr,OLD.opv_fecha_egr)) then
	    insert into modlogs (log_tabla,log_idtabla,log_campo,log_valant,log_valpos,log_cont) values ('opervehi',NEW.opv_id,'opv_fecha_egr',OLD.opv_fecha_egr,NEW.opv_fecha_egr,cont);
	end if;

	if (timestamp_ne(NEW.opv_fecha_ing,OLD.opv_fecha_ing)) then
	    insert into modlogs (log_tabla,log_idtabla,log_campo,log_valant,log_valpos,log_cont) values ('opervehi',NEW.opv_id,'opv_fecha_ing',OLD.opv_fecha_ing,NEW.opv_fecha_ing,cont);
	end if;

	if (timestamp_ne(NEW.opv_fecha_adu,OLD.opv_fecha_adu)) then
	    insert into modlogs (log_tabla,log_idtabla,log_campo,log_valant,log_valpos,log_cont) values ('opervehi',NEW.opv_id,'opv_fecha_adu',OLD.opv_fecha_adu,NEW.opv_fecha_adu,cont);
	end if;

	if (int4ne(NEW.opv_est_camion,OLD.opv_est_camion)) then
	    insert into modlogs (log_tabla,log_idtabla,log_campo,log_valant,log_valpos,log_cont) values ('opervehi',NEW.opv_id,'opv_est_camion',OLD.opv_est_camion,NEW.opv_est_camion,cont);
	end if;

	if (bpcharne(NEW.opv_pat_chasis,OLD.opv_pat_chasis)) then
	    insert into modlogs (log_tabla,log_idtabla,log_campo,log_valant,log_valpos,log_cont) values ('opervehi',NEW.opv_id,'opv_pat_chasis',OLD.opv_pat_chasis,NEW.opv_pat_chasis,cont);
	end if;

	if (bpcharne(NEW.opv_pat_tractor,OLD.opv_pat_tractor)) then
	    insert into modlogs (log_tabla,log_idtabla,log_campo,log_valant,log_valpos,log_cont) values ('opervehi',NEW.opv_id,'opv_pat_tractor',OLD.opv_pat_tractor,NEW.opv_pat_tractor,cont);
	end if;

	if (bpcharne(NEW.opv_chofer,OLD.opv_chofer)) then
	    insert into modlogs (log_tabla,log_idtabla,log_campo,log_valant,log_valpos,log_cont) values ('opervehi',NEW.opv_id,'opv_chofer',OLD.opv_chofer,NEW.opv_chofer,cont);
	end if;

	if(OLD.opv_fecha_ing is null and NEW.opv_fecha_ing is not null) then
	    insert into modlogs (log_tabla,log_idtabla,log_campo,log_valant,log_valpos,log_cont) values ('opervehi',NEW.opv_id,'opv_fecha_ing','null',NEW.opv_fecha_ing,cont);
	end if;
	if(OLD.opv_fecha_adu is null and NEW.opv_fecha_adu is not null) then
	    insert into modlogs (log_tabla,log_idtabla,log_campo,log_valant,log_valpos,log_cont) values ('opervehi',NEW.opv_id,'opv_fecha_adu','null',NEW.opv_fecha_adu,cont);
	end if;
	if(OLD.opv_fecha_egr is null and NEW.opv_fecha_egr is not null) then
	    insert into modlogs (log_tabla,log_idtabla,log_campo,log_valant,log_valpos,log_cont) values ('opervehi',NEW.opv_id,'opv_fecha_egr','null',NEW.opv_fecha_egr,cont);
	end if;
	if(OLD.opv_peso_ing is null and NEW.opv_peso_ing is not null) then
	    insert into modlogs (log_tabla,log_idtabla,log_campo,log_valant,log_valpos,log_cont) values ('opervehi',NEW.opv_id,'opv_peso_ing','null',NEW.opv_peso_ing,cont);
	end if;
	if(OLD.opv_peso_egr is null and NEW.opv_peso_egr is not null) then
	    insert into modlogs (log_tabla,log_idtabla,log_campo,log_valant,log_valpos,log_cont) values ('opervehi',NEW.opv_id,'opv_peso_egr','null',NEW.opv_peso_egr,cont);
	end if;



RETURN NEW;
END;$$;


ALTER FUNCTION public.f_au_opervehi() OWNER TO zona;

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

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

    if int4eq(NEW.pa_realizado,999) THEN 
	if OLD.pa_idrp is not null then
	    update proganualsh set pa_realizado=1 where pa_id=OLD.pa_idrp;
	end if;
    END IF;

    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_au_proganualsh() OWNER TO zona;

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

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;

    if int4ne(NEW.prov_critico,OLD.prov_critico) THEN 
	update criticprov set cp_estado=2 where cp_idprov=OLD.prov_id;
	insert into criticprov (cp_idprov,cp_valact) values (OLD.prov_id,NEW.prov_critico);
    END IF;

    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_au_prove() OWNER TO zona;

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

CREATE FUNCTION f_au_requeh() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
	registro	record;
BEGIN

    if int4eq(NEW.rh_estado,999) and int4ne(OLD.rh_estado,999) THEN 
	update och set och_estado=999 where och_id in (select rxoc_idoch from rxoc where rxoc_idrh=OLD.rh_id);
	update requeb set rb_estado=999 where rb_idrh=OLD.rh_id;
    end if;

    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_au_requeh() OWNER TO zona;

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

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

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

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

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

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

    if (bpcharne(NEW.suc_direccl,OLD.suc_direccl) or OLD.suc_direccl is NULL) 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) or OLD.suc_localil is NULL) 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) or OLD.suc_codposl is NULL) 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) or OLD.suc_codprovl is NULL) 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) or OLD.suc_paisl is NULL) 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) or OLD.suc_direcc is NULL) 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) or OLD.suc_locali is NULL) 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) or OLD.suc_codpos is NULL) 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) or OLD.suc_codprov is NULL) 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) or OLD.suc_pais is NULL) 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 zona;

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

CREATE FUNCTION f_au_unifun() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
BEGIN
    if(int2ne(NEW.unif_codigo,OLD.unif_codigo)) THEN 
	update wsubitem set wsitem_deposito=NEW.unif_codigo where wsitem_deposito=OLD.unif_codigo;
	update subitem set sitem_deposito=NEW.unif_codigo where sitem_deposito=OLD.unif_codigo;
	update operaciones set op_deposito=NEW.unif_codigo where op_deposito=OLD.unif_codigo;
	update woperaciones set wop_deposito=NEW.unif_codigo where wop_deposito=OLD.unif_codigo;
	update subitemd set sitemd_deposito=NEW.unif_codigo where sitemd_deposito=OLD.unif_codigo;
	update stock set stk_deposito=NEW.unif_codigo where stk_deposito=OLD.unif_codigo;
	update inhabilit set inh_deposito=NEW.unif_codigo where inh_deposito=OLD.unif_codigo;
	update intotal set int_deposito=NEW.unif_codigo where int_deposito='OLD.unif_codigo';
	update contratos set contr_unifun=NEW.unif_codigo where contr_unifun=OLD.unif_codigo;
	update seguros set seg_unifun=NEW.unif_codigo where seg_unifun=OLD.unif_codigo;
    END IF;
RETURN NEW;
END;$$;


ALTER FUNCTION public.f_au_unifun() OWNER TO zona;

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

CREATE FUNCTION f_au_usuarios() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
id		integer;
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;

    if(int2eq(OLD.usu_tipusu,2::int2) and (int2eq(NEW.usu_tipusu,3::int2) or int2eq(NEW.usu_tipusu,1::int2))) then
	select cli_id into id from clientes where cli_codigo=NEW.usu_codigo;
	if id is null 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;
    end if;


    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_au_usuarios() OWNER TO zona;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    delete from juzgprov where jp_ideval=OLD.evxp_id;

RETURN OLD;
END;$$;


ALTER FUNCTION public.f_bd_evxprov() OWNER TO zona;

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

CREATE FUNCTION f_bd_hijcble() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
    BEGIN
    update padcble set pc_estado=1 where pc_idcble=OLD.hc_idcble and pc_reg=OLD.hc_reg;
    RETURN OLD;
    END;$$;


ALTER FUNCTION public.f_bd_hijcble() OWNER TO zona;

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

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

    delete from evaluacion where eval_idjuzg=OLD.jp_id;

RETURN OLD;
END;$$;


ALTER FUNCTION public.f_bd_juzgprov() OWNER TO zona;

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

CREATE FUNCTION f_bd_och() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
	registro	record;
BEGIN

    if (int4ge(OLD.och_estado,10) and int4lt(OLD.och_estado,999)) then
	for registro in select * from rxoc where rxoc_idoch=OLD.och_id loop
	    update requeb set rb_cantir=rb_cantir-registro.rxoc_cantas,rb_estado=2 where rb_id=registro.rxoc_idrb;
	end loop;
    end if;
    delete from pagooc where po_idoch=OLD.och_id;
    delete from recepcionoch where rch_idrxoc in (select rxoc_id from rxoc where rxoc_idoch=OLD.och_id);
    delete from rxoc where rxoc_idoch=OLD.och_id;
    delete from ocb where ocb_idoch=OLD.och_id;

    RETURN OLD;
    END;$$;


ALTER FUNCTION public.f_bd_och() OWNER TO zona;

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

CREATE FUNCTION f_bd_requeh() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
	registro	record;
BEGIN

    delete from och where och_id in (select distinct rxoc_idoch from rxoc where rxoc_idrh=OLD.rh_id);
    delete from requeb where rb_idrh=OLD.rh_id;

    RETURN OLD;
    END;$$;


ALTER FUNCTION public.f_bd_requeh() OWNER TO zona;

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

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

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

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

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

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

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

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

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

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

--
