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

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


ALTER FUNCTION public.f_bi_puertos() OWNER TO zona;

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

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


ALTER FUNCTION public.f_bi_retiros() OWNER TO zona;

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

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

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

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

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

RETURN NEW;
END;$$;


ALTER FUNCTION public.f_bi_subitem() OWNER TO zona;

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

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


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


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

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

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



END IF;
    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_bu_astoh() OWNER TO zona;

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

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

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

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


ALTER FUNCTION public.f_bu_caratula() OWNER TO zona;

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

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


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


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

END IF;
    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_bu_cheques() OWNER TO zona;

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

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

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

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

RETURN NEW;
END;$$;


ALTER FUNCTION public.f_bu_operaciones() OWNER TO zona;

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

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

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


ALTER FUNCTION public.f_bu_retiros() OWNER TO zona;

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

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

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

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

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

    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_bu_seguros() OWNER TO zona;

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

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

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

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

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

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

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

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


ALTER FUNCTION public.f_bu_subitem() OWNER TO zona;

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

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


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

RETURN NEW;
END;$$;


ALTER FUNCTION public.f_bu_volegr() OWNER TO zona;

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

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


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

RETURN NEW;
END;$$;


ALTER FUNCTION public.f_bu_voling() OWNER TO zona;

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

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

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


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


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


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


RETURN retval;
END;$_$;


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

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

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


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

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

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


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

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

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


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

	      else

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

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


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

	      else

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


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

    retval:=yapase;

RETURN retval;
END;$_$;


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

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

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


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

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

CREATE FUNCTION fecegre_almacen(integer) RETURNS date
    LANGUAGE sql
    AS $_$select alm_retiro from almacen where alm_id= $1;$_$;


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

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

CREATE FUNCTION fecegre_de_almacen(character varying) RETURNS date
    LANGUAGE sql
    AS $_$select alm_retiro from almacen where trim(alm_leyenda)= $1 limit 1;$_$;


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

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

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


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

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

CREATE FUNCTION fechaevento(integer, integer) RETURNS date
    LANGUAGE sql
    AS $_$select fechac_fecha from feccontra where fechac_idcontra= $1 and fechac_codevent= $2;$_$;


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

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

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


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

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

CREATE FUNCTION fechainretsitem(integer) RETURNS date
    LANGUAGE sql
    AS $_$select op_fechain from operaciones a,retiros b where a.op_id=b.ret_idopera and a.op_estado>100 and b.ret_idsitem= $1 order by ret_id desc limit 1;$_$;


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

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

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


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

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

CREATE FUNCTION fechanec(integer) RETURNS date
    LANGUAGE sql
    AS $_$select rh_fecnec from requeh where rh_id = $1;$_$;


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

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

CREATE FUNCTION fechaopvegr(integer) RETURNS timestamp without time zone
    LANGUAGE sql
    AS $_$select opv_fecha_egr from opervehi where opv_id= $1 ;$_$;


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

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

CREATE FUNCTION fechaopving(integer) RETURNS timestamp without time zone
    LANGUAGE sql
    AS $_$select opv_fecha_ing from opervehi where opv_id= $1 ;$_$;


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

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

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


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

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

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


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

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

CREATE FUNCTION fecvtoconsig(integer) RETURNS date
    LANGUAGE sql
    AS $_$select csg_fecvto from consig where csg_id= $1 ;$_$;


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

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

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

retval:=0;

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

		retval:=retval+registror.sitem_imp_dolar;

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


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

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

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

		end if;

		end loop; 

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

RETURN retval;
END;$_$;


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

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

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

retval:=0;

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

	retval:=retval+registro.sitem_imp_dolar;

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


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

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

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

	end if;

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

RETURN retval;
END;$_$;


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

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

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

retval:=0;

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

		retval:=retval+registror.sitem_imp_dolar;

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


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

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

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

		end if;

		end loop; 

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

RETURN retval;
END;$_$;


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

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

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

retval:=0;

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

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

RETURN retval;
END;$_$;


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

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

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

retval:=0;

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

		retval:=retval+registror.sitem_imp_dolar;

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


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

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

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

		end if;

		end loop; 

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

RETURN retval;
END;$_$;


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

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

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

retval:=0;

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

		retval:=retval+registror.sitem_imp_dolar;

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


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

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

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

		end if;

		end loop; 

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

RETURN retval;
END;$_$;


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

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

CREATE FUNCTION fob_hijos1(integer, smallint) RETURNS numeric
    LANGUAGE sql
    AS $_$select (case when $2 =1 then sum(sitem_importe) else sum(sitem_imp_dolar) end) from subitem where sitem_idoper= $1 ;$_$;


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

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

CREATE FUNCTION fob_hijos2(integer, smallint) RETURNS numeric
    LANGUAGE sql
    AS $_$select (case when $2 =1 then sum(ret_cantidad*sitem_importe/sitem_canting) else sum(ret_cantidad*sitem_imp_dolar/sitem_canting) end) from retiros,subitem where sitem_id=ret_idsitem and ret_idopera= $1 ;$_$;


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

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

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

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

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


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

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

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

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

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


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

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

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

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


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

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

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

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

select ash_codemp,ash_idptov into codemp,idpto from astoh where ash_id=idastoh;
select idcbl(codemp,valvaramb(codemp,0,'DEUDXV')::integer) into ctadxv;   
select idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer) into ctachq;   
select idcbl(codemp,valvaramb(codemp,0,'BANCO')::integer) into ctabco;   
select idcbl(codemp,valvaramb(codemp,0,'DOCUM')::integer) into ctadocu;   
select sum(astc_importe) into salgrup from astoctas where astc_codemp=codemp and astc_ctacble=ctadxv and astc_ctacte=elcliente and astc_grupo=nrogpo and astc_idastoh!=idastoh 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;


idpto:=6;

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

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

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


primera:=1;
for registro in select 
     * from astoctas where astc_codemp=codemp and astc_ctacble=ctadxv and astc_ctacte=elcliente and astc_grupo=nrogpo 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
	    llevo:= llevo + (registro.astc_importe * (prompago - registro.astc_fecvto) * interd / 100 / 30);
	    salgrup:= salgrup - registro.astc_importe;
	  else 
	    if(numeric_gt(registro.astc_importe,salgrup) and numeric_gt(registro.astc_importe,0::numeric)) then
		llevo:=llevo + (salgrup * (prompago - registro.astc_fecvto) * interd  / 100 / 30);
		salgrup:= salgrup - registro.astc_importe;
	    else
		if (numeric_lt(registro.astc_importe,0::numeric)) then
		    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;
		end if;
	    end if;
	end if;
    end if;
end loop; 



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


return ret;
end;$_$;


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

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

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

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

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


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



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

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


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


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

ret:=salgrup;


return ret;
end;$_$;


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

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

CREATE FUNCTION genernd2(integer, integer, integer, numeric) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
declare
idastoh		 alias for $1;
elcliente	 alias for $2;
nrogpo		 alias for $3;
totpag		 alias for $4;
ret 		 numeric;
registro	 record;
regi		 record;
regi2		 record;
codemp		 integer;
idpto		 integer;
tipct		 integer;
ctadxv		 integer;
ctabco		 integer;
ctachq		 integer;
ctadocu		 integer;
salgrup		 numeric;
llevo		 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 and contr_estado=1 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;

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
			    llevo:= llevo + (regi2.chq_importe * (regi2.chq_fecheq - maxvto) * interd / 30 / 100);
			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);
			    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);
			end if;
		    end if;
		end if;
	    end if;
	end if;
    end loop; 

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

return ret;
end;$_$;


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

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

CREATE FUNCTION gente_adentro(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select io_gente from inout where io_estado=1 and io_gente= $1 ;$_$;


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

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

CREATE FUNCTION gentedeusu(integer, integer) RETURNS integer
    LANGUAGE sql
    AS $_$select gte_id from gente where gte_usu= $1 and gte_id= $2 ;$_$;


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

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

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


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

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

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

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


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

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


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


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

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

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

select cdp_dias into dias from conpag,emiti where emi_conpag=cdp_codigo and emi_id=idastoh;
select (fecval::date + dias)::date into fecvto;

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

update emiti set emi_total=total where emi_idastoh=idastoh;

retval:=signo;

RETURN retval;
END;$_$;


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

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

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

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


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

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


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


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

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

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

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

update emiti set emi_total=total where emi_idastoh=idastoh;

retval:=signo;

RETURN retval;
END;$_$;


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

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

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

begin

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

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

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


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

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

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

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


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

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

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

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

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

return ret;
end;$_$;


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

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

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

begin

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

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

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


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

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

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

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


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

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

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

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

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

return ret;
end;$_$;


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

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

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

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

end if;

RETURN retval;
END;$_$;


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

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

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

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


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

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

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

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


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

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

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


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

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

return ret;
END;$_$;


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

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

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

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

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

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

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

	select op_tipoper into tipoper from operaciones where op_id=opid;


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

return ret;
end;$_$;


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

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

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

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

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

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

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

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

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

return ret;
end;$_$;


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

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

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

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

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

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

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

	select op_tipoper into tipoper from operaciones where op_id=opid;


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

return ret;
end;$_$;


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

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

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

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

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

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

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

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

return ret;
end;$_$;


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

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

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

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

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

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

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


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

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

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

    RETURN retval;
    END;$_$;


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

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

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

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

    RETURN retval;
    END;$_$;


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

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

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

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

    RETURN retval;
    END;$_$;


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

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

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

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

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

    end if;

  else

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

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

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

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

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


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

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

CREATE FUNCTION hubovisita(integer) RETURNS bigint
    LANGUAGE sql
    AS $_$select count(*) from visita where vt_inout= $1 ;$_$;


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

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

CREATE FUNCTION idartdetipp(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select tip_imo from tipprod where tip_codigo= $1 ;$_$;


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

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

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


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

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

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


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

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

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


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

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

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


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

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

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


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

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

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


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

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

CREATE FUNCTION iddearticud(integer, character varying) RETURNS integer
    LANGUAGE sql
    AS $_$select articd_id from articud where articd_indirecto = $1 and articd_codigo=trim($2);$_$;


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

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

CREATE FUNCTION iddearticudm(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select articd_id from articud a,articu b where a.articd_indirecto=b.artic_indirecto  and a.articd_codigo=b.artic_codigo and b.artic_id= $1;$_$;


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

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

CREATE FUNCTION idopleyrexp(character varying, smallint) RETURNS integer
    LANGUAGE sql
    AS $_$select leyr_idoper from leyenrexp where leyr_nro= $2 and leyr_leyenda like '%$1%' ;$_$;


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

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

CREATE FUNCTION idopleyrexp2(character varying) RETURNS integer
    LANGUAGE sql
    AS $_$select leyr_idoper from leyenrexp where leyr_leyenda like '%$1%' ;$_$;


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

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

CREATE FUNCTION idpadcble(integer, integer) RETURNS integer
    LANGUAGE sql
    AS $_$select pc_id from padcble where pc_idcble= $1 and pc_estado=1 and pc_reg= $2 ;$_$;


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

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

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


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

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

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


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

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

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


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

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

CREATE FUNCTION idwopdewret2(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select wret2_idopera from wret2 where wret2_id= $1 ;$_$;


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

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

CREATE FUNCTION importe_fe(numeric) RETURNS text
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	imp		ALIAS FOR $1;
	retval		text;
    BEGIN
	select lpad((imp::numeric(15,2)*100)::numeric(15,0)::text,15,'0') into retval;
	RETURN retval;
    END;$_$;


ALTER FUNCTION public.importe_fe(numeric) OWNER TO zona;

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

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

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

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

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

	select trim(despacho) into despachos from caratula where car_id=caratul;

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

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

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

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

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

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


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

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

	    end loop;

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



	retval:='t';

    RETURN retval;
    END;$_$;


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

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

CREATE FUNCTION imprim_fact_deta(character varying, integer, smallint, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	impresora	ALIAS FOR $1; 
	reporte		ALIAS FOR $2; 
	mes		ALIAS FOR $3; 
	anio		ALIAS FOR $4; 
	ret 		boolean;
	operacion	int4;
	registro 	RECORD;
    BEGIN
    ret:='f';

    for registro in select cfc_usuario as x, count(*) as y
    	    from confactur where cfc_anio=anio and cfc_mes=mes and cfc_ptov=2 group by cfc_usuario order by 1
		loop
		    operacion:=genimpre(impresora,reporte,registro.x);
		    ret:='t';
		end loop; 
return ret;
	
    END;$_$;


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

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

CREATE FUNCTION imprim_fact_deta_alm(character varying, integer, smallint, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	impresora	ALIAS FOR $1; 
	reporte		ALIAS FOR $2; 
	mes		ALIAS FOR $3; 
	anio		ALIAS FOR $4; 
	ret 		boolean;
	operacion	int4;
	registro 	RECORD;
    BEGIN
    ret:='f';

    for registro in select cfc_usuario as x, count(*) as y
    	    from confactur where cfc_anio=anio and cfc_mes=mes and cfc_ptov=2 and cfc_idart in (5,7,11) group by 1 order by 1
		loop
		    operacion:=genimpre(impresora,reporte,registro.x);
		    ret:='t';
		end loop; 
return ret;
	
    END;$_$;


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

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

CREATE FUNCTION imprim_fact_deta_almxc(character varying, integer, smallint, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	impresora	ALIAS FOR $1; 
	reporte		ALIAS FOR $2; 
	mes		ALIAS FOR $3; 
	anio		ALIAS FOR $4; 
	ret 		boolean;
	operacion	int4;
	registro 	RECORD;
    BEGIN
    ret:='f';

    for registro in select cfc_usuario as x, count(*) as y
    	    from confactur where cfc_mes=mes and cfc_anio=anio and cfc_ptov=2 and cfc_idart in (5,7,11) and cfc_usuario in (258,284,325,377,520,522,568,893,983,1004,1365,1757,1823,4069,4116,4117,4344,4862,5140) group by cfc_usuario
		loop
		    operacion:=genimpre(impresora,reporte,registro.x);
		    ret:='t';
		end loop; 
return ret;
	
    END;$_$;


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

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

CREATE FUNCTION imprim_fact_detaxc(character varying, integer, smallint, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	impresora	ALIAS FOR $1; 
	reporte		ALIAS FOR $2; 
	mes		ALIAS FOR $3; 
	anio		ALIAS FOR $4; 
	ret 		boolean;
	operacion	int4;
	registro 	RECORD;
    BEGIN
    ret:='f';

    for registro in select cfc_usuario as x, count(*) as y
    	    from confactur where cfc_mes=mes and cfc_anio=anio and cfc_ptov=2 and cfc_usuario in (258,284,325,377,520,522,568,893,983,1004,1365,1757,1823,4069,4116,4117,4344,4862,5140)  group by cfc_usuario
		loop
		    operacion:=genimpre(impresora,reporte,registro.x);
		    ret:='t';
		end loop; 
return ret;
	
    END;$_$;


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

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

CREATE FUNCTION imprim_fact_detaxc(character varying, integer, integer, smallint, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	impresora	ALIAS FOR $1; 
	reporte		ALIAS FOR $2; 
	mes		ALIAS FOR $3; 
	anio		ALIAS FOR $4; 
	usuario		ALIAS FOR $5; 
	ret 		boolean;
	operacion	int4;
	registro 	RECORD;
    BEGIN
    ret:='f';

    for registro in select cfc_usuario as x
    	    from confactur where cfc_mes=11 and cfc_anio=2004 and cfc_ptov=2 and cfc_usuario=usuario group by cfc_usuario
		loop
		    operacion:=genimpre('lexmark',501,registro.x);
		    ret:='t';
		end loop; 
return ret;
	
    END;$_$;


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

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

CREATE FUNCTION imprim_fact_detaxc(character varying, integer, smallint, smallint, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	impresora	ALIAS FOR $1; 
	reporte		ALIAS FOR $2; 
	mes		ALIAS FOR $3; 
	anio		ALIAS FOR $4; 
	usuario		ALIAS FOR $5; 
	ret 		boolean;
	operacion	int4;
	registro 	RECORD;
    BEGIN
    ret:='f';

    for registro in select cfc_usuario as x, count(*) as y
    	    from confactur where cfc_anio=anio and cfc_mes=mes and cfc_ptov=2 and cfc_usuario=usuario group by cfc_usuario
		loop
		    operacion:=genimpre(impresora,reporte,registro.x);
		    ret:='t';
		end loop; 
return ret;
	
    END;$_$;


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

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

CREATE FUNCTION indiconcontr(integer, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
locador		 alias for $1;
locatario	 alias for $2;
temporal	 integer;
ret 		 boolean;
begin
ret:='f';

select contr_locatario into temporal from contratos where contr_locador=locador and contr_locatario =locatario and contr_estado=1 and contr_idsubt in (7,8,9) limit 1;

if found then
    ret:='t';
end if;

return ret;

end;$_$;


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

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

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


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

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

CREATE FUNCTION indirectodeusu(integer, integer) RETURNS boolean
    LANGUAGE sql
    AS $_$select true from operaciones where op_directo= $1 and op_indirecto= $2 limit 1;$_$;


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

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

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


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

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

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


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

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

CREATE FUNCTION itemdeitem(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select item_item from item where item_id= $1 ;$_$;


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

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

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


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

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

CREATE FUNCTION itemitemdesitem(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select item_item from subitem a, item b where a.sitem_iditem=b.item_id and a.sitem_id= $1 ;$_$;


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

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

CREATE FUNCTION length(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select length($1::text);$_$;


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

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

CREATE FUNCTION leyrexp(integer, smallint) RETURNS character
    LANGUAGE sql
    AS $_$select leyr_leyenda from leyenrexp where leyr_nro= $2 and leyr_idoper= $1 ;$_$;


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

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

CREATE FUNCTION llevastock(integer) RETURNS boolean
    LANGUAGE sql
    AS $_$select true from varambi where vari_codemp= $1 and vari_codigo='STOCK' and vari_valor='1' limit 1;$_$;


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

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

CREATE FUNCTION lpad(integer, integer, integer) RETURNS text
    LANGUAGE sql
    AS $_$select lpad($1::text,$2,$3::text);$_$;


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

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

CREATE FUNCTION ltrim(integer) RETURNS text
    LANGUAGE sql
    AS $_$select ltrim($1::text);$_$;


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

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

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


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

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

CREATE FUNCTION marcasitem(integer) RETURNS character
    LANGUAGE sql
    AS $_$select artic_marca from articu a,subitem b where a.artic_id=b.sitem_artic and b.sitem_id= $1 ;$_$;


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

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

CREATE FUNCTION marcontdeopv(integer) RETURNS character
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	idopv		ALIAS FOR $1;  
	codmarcont	int4;
	indi		int4;
	regi		RECORD;
	trans		varchar;
	trans1		varchar;
	retval		varchar;
    BEGIN

    indi=1;
    for regi in select * from contene where cont_idopv= $1 
    loop
    select marc_descrip into trans from marcont where marc_codigo=regi.cont_marcont;
	trans1:= trans||'-'||regi.cont_nrocont;

	if indi>1 then
		retval:= trans1||' / '||trans||'-'||regi.cont_nrocont;
	    else
		retval:= trans1;
	end if;
	indi:=indi+1;
    end loop;
    
    RETURN retval;
    END;$_$;


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

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

CREATE FUNCTION maxfecopv(integer) RETURNS date
    LANGUAGE sql
    AS $_$select date(max(opv_fecha_egr)) from opervehi where opv_idoper = $1 and opv_est_camion=50;$_$;


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

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

CREATE FUNCTION meapeso(smallint, date) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	moneda		ALIAS FOR $1; 
	fecha		ALIAS FOR $2; 
	cotipes		numeric;
	retval 		numeric;
    BEGIN

    select cotpeso(fecha) into cotipes;
    select (cot_cotiz * cotipes) into retval from cotiza WHERE int2eq(moneda,cot_moneda) and  date_le(cot_fecha,fecha) order by cot_fecha desc limit 1;

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


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

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

CREATE FUNCTION medcontene(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select clac_medida from clacont where clac_codigo = $1 ;$_$;


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

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

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


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

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

CREATE FUNCTION migracion() RETURNS integer
    LANGUAGE plpgsql
    AS $$
declare
regi 		RECORD;
ret		int4;
operid		int4;
itemid		int4;
rowintotal 	int4;
ruflo 	int4;
ruflo1 	int4;
ruflo2 	int4;
begin
ret:=0;

for regi in select * from intotal order by int_directo,int_indirecto,int_tipoper,int_numero,int_articod,int_lotenum
	loop
	rowintotal:=regi.int_id;
	operid:=cidop(regi.int_directo::int4,regi.int_indirecto::int4,regi.int_tipoper::int4,	regi.int_numero::int4);	

	if(regi.int_id<270554) then
		ruflo1:=regi.int_idret::int4;
	    else
		ruflo1:=cidart(regi.int_indirecto::int4,regi.int_articod::varchar);
	end if;


	
	if regi.int_lotenum::int2 < 1  then
		insert into item (
    		item_idoper,item_existe_sitem,item_moneda,item_tipprod,item_unimed) 
		values	(operid,0,regi.int_moneda::int2,trim(regi.int_tiprod)::int4,regi.int_unimed::int2);
		select max(item_id) into ruflo from item; 
	end if;
	

	insert into subitem (sitem_iditem,sitem_idoper,sitem_codigo,
			sitem_artic,sitem_canting,sitem_cantret,
			sitem_cantcomp,sitem_importe,sitem_tipemb,
			sitem_deposito,sitem_directo,sitem_indirecto,sitem_compbte)
		values
(ruflo,operid,regi.int_lotenum,ruflo1,	
    regi.int_canting::numeric,regi.int_cantret::numeric,regi.int_cantcomp::numeric,
    regi.int_valori::numeric,regi.int_embalaje::int2,regi.int_deposito::int2,
    regi.int_directo::int4,regi.int_indirecto::int4,regi.int_compbte);

    end loop; 
return ret;
end;$$;


ALTER FUNCTION public.migracion() OWNER TO zona;

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

CREATE FUNCTION migracion1() RETURNS integer
    LANGUAGE plpgsql
    AS $$
declare
regi 		RECORD;
ret		int4;
operid		int4;
itemid		int4;
rowintotal 	int4;
ruflo 	int4;
ruflo2 	int4;
begin
ret:=0;

for regi in select distinct on (int_directo,int_indirecto,int_tipoper,int_numero) * from intotal
	loop
	insert into operaciones (op_tipoper,op_directo,op_indirecto,op_compbte,op_nrotalzon,op_nrotaldir,op_estado,op_consig,op_fechain,op_deposito,op_conocim,op_peso,op_bultos,op_moneda,op_importe,op_impdolar,op_tipo_cambio,op_embalaje) 
	values
	(regi.int_tipoper::int4,regi.int_directo::int4,regi.int_indirecto::int4,regi.int_compbte::varchar,val_talon(regi.int_tipoper::int4,1),regi.int_numero::int4,regi.int_estado::int2,regi.int_consig::int4,regi.int_fecha::date,regi.int_deposito::int2,regi.int_conocim::varchar,regi.int_peso::numeric,regi.int_bultos::int4,regi.int_moneda::int2,regi.int_fobt::numeric,regi.int_valcte::numeric,regi.int_tipcbo::numeric,regi.int_embalaje::int2);
--	ret:=ret+1;		
        end loop; 

return ret;
end;$$;


ALTER FUNCTION public.migracion1() OWNER TO zona;

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

CREATE FUNCTION migracion2() RETURNS integer
    LANGUAGE plpgsql
    AS $$
declare
regi 		RECORD;
ret		int4;
operid		int4;
itemid		int4;
rowintotal 	int4;
ruflo 	int4;
ruflo2 	int4;
begin
ret:=0;


for regi in select distinct on (int_articod,int_directo,int_indirecto) * from intotal
	loop
	select artic_id into ruflo from articu where artic_indirecto=regi.int_indirecto::int4 and artic_codigo=regi.int_articod::varchar;

	if not found then
	insert into articu (artic_indirecto,artic_codigo,artic_descrip,artic_tiprod,artic_unimed) 
	values
	(regi.int_indirecto::int4,regi.int_articod::varchar,regi.int_artidesc::varchar,trim(regi.int_tiprod)::int4,regi.int_unimed::int2);
ret:=ret+1;
	end if;
        end loop; 

return ret;
end;$$;


ALTER FUNCTION public.migracion2() OWNER TO zona;

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

CREATE FUNCTION migracion_e() RETURNS integer
    LANGUAGE plpgsql
    AS $$
declare
regi 		RECORD;
ret		int4;
operid		int4;
artic_id		int4;
rowintotal 	int4;
ruflo 	int4;
ruflo2 	int4;
begin
ret:=0;
for regi in select distinct on (egt_directo,egt_indirecto,egt_tipoper,egt_numero) * from egretot
	loop
	insert into operaciones (op_tipoper,op_directo,op_indirecto,op_compbte,
	op_nrotalzon,op_nrotaldir,op_estado,op_consig,op_fechain,
	op_comptrans,op_peso,op_bultos,op_moneda,op_importe,
	op_impdolar,op_embalaje) 
	values
	(regi.egt_tipoper::int4,regi.egt_directo::int4,regi.egt_indirecto::int4,
	regi.egt_compbte,val_talon(regi.egt_tipoper::int4,1),regi.egt_numero::int4,
	101::int2,regi.egt_consig::int4,regi.egt_fecha::date,
	regi.egt_combteeg::char,regi.egt_peso::numeric,regi.egt_bultos::int4,
	regi.egt_moneda::int2,regi.egt_fobt::numeric,regi.egt_valcte::numeric,
	regi.egt_embalaje::int2	);
	ret:=ret+1;		
        end loop; 

for regi in select * from egretot 
	loop
	operid:=cidop(regi.egt_directo::int4,regi.egt_indirecto::int4,regi.egt_tipoper::int4,	regi.egt_numero::int4);	
	artic_id:=cidart(regi.egt_indirecto::int4,regi.egt_articod::varchar);
	
	insert into retiros (ret_idopera,ret_idsitem,ret_item,ret_sitem,ret_cantidad)
		values	(operid,cidsitem(operid,regi.egt_lotenum::int2,regi.egt_compbte::varchar,artic_id),1::int2,0::int2,regi.egt_cantret::numeric);

--	ret:=ret+1;		

    end loop; 

return ret;
end;$$;


ALTER FUNCTION public.migracion_e() OWNER TO zona;

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

CREATE FUNCTION migracion_e1(integer, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
desde	 	alias for $1;
hasta		alias for $2;
regi 		RECORD;
ret		int4;
operid		int4;
operidi		int4;
artic_id		int4;
rowintotal 	int4;
ruflo 	int4;
ruflo2 	int4;
begin
ret:=0;

for regi in select * from egretot where egt_id between desde and hasta
    loop
    operid:=cidop(regi.egt_directo::int4,regi.egt_indirecto::int4,regi.egt_tipoper::int4,regi.egt_numero::int4);
    operidi:=cidop(regi.egt_directo::int4,regi.egt_indirecto::int4,regi.egt_tipoperin::int4,regi.egt_numeroin::int4);
    artic_id:=cidart(regi.egt_indirecto::int4,trim(regi.egt_articod)::varchar);
    ruflo2=cidsitem(operidi::int4,regi.egt_lotenum::int2,trim(regi.egt_compbte)::varchar,artic_id::int4);
    if ruflo2 is null then ruflo2=0; end if;
	insert into retiros (ret_idopera,ret_idsitem,ret_item,ret_sitem,ret_cantidad)
		values	(operid,ruflo2,1::int2,0::int2,regi.egt_cantret::numeric);

ret:=1;
    end loop; 


return ret;
end;$_$;


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

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

CREATE FUNCTION migracion_ep() RETURNS integer
    LANGUAGE plpgsql
    AS $$
declare
regi 		RECORD;
ret		int4;
operid		int4;
artic_id		int4;
rowintotal 	int4;
ruflo 	int4;
ruflo2 	int4;
begin
ret:=0;
for regi in select distinct on (trim(egt_directo),trim(egt_indirecto),trim(egt_tipoper),trim(egt_numero)) * from egretot where egt_id>6499
	loop
	insert into operaciones (op_tipoper,op_directo,op_indirecto,op_compbte,
	op_nrotalzon,op_nrotaldir,op_estado,op_consig,op_fechain,
	op_comptrans,op_peso,op_bultos,op_moneda,op_importe,
	op_impdolar,op_embalaje) 
	values
	(trim(regi.egt_tipoper)::int4,trim(regi.egt_directo)::int4,trim(regi.egt_indirecto)::int4,
	trim(regi.egt_compbte)::varchar,val_talon(trim(regi.egt_tipoper)::int4,1),trim(regi.egt_numero)::int4,
	trim(regi.egt_esta)::int2,trim(regi.egt_consig)::int4,trim(regi.egt_fecha)::date,
	trim(regi.egt_combteeg)::varchar,trim(regi.egt_peso)::numeric,trim(regi.egt_bultos)::int4,
	trim(regi.egt_moneda)::int2,trim(regi.egt_fobt)::numeric,trim(regi.egt_valcte)::numeric,
	trim(regi.egt_embalaje)::int2	);
	ret:=ret+1;		
        end loop; 

return ret;
end;$$;


ALTER FUNCTION public.migracion_ep() OWNER TO zona;

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

CREATE FUNCTION migracion_ep1() RETURNS integer
    LANGUAGE plpgsql
    AS $$
declare
regi 		RECORD;
ret		int4;
operid		int4;
operidi		int4;
artic_id		int4;
rowintotal 	int4;
ruflo 	int4;
ruflo2 	int4;
begin
ret:=0;

for regi in select * from egretot 
    loop
    operid:=cidop(regi.egt_directo::int4,regi.egt_indirecto::int4,regi.egt_tipoper::int4,regi.egt_numero::int4);

    operidi:=cidop(regi.egt_directo::int4,regi.egt_indirecto::int4,regi.egt_tipoperin::int4,regi.egt_numeroin::int4);
    artic_id:=cidart(regi.egt_indirecto::int4,trim(regi.egt_articod)::varchar);
    ruflo2=cidsitem(operidi::int4,regi.egt_lotenum::int2,trim(regi.egt_compbte)::varchar,artic_id::int4);
    if ruflo2 is null then ruflo2=0; end if;
	
	insert into retiros (ret_idopera,ret_idsitem,ret_item,ret_sitem,ret_cantidad)
		values	(operid,ruflo2,1::int2,0::int2,regi.egt_cantret::numeric);
    end loop; 

return ret;
end;$$;


ALTER FUNCTION public.migracion_ep1() OWNER TO zona;

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

CREATE FUNCTION mismo_consig(integer, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	op_ing		ALIAS FOR $1; -- id  Op.ING.
	op_egr		ALIAS FOR $2; -- id  Op.EGR.
	retval 		boolean;
    BEGIN
    retval:='f';
    if  int4eq((select op_consig from operaciones where op_id=op_ing),(select op_consig from operaciones where op_id=op_egr)) 
        then retval:='t';
    end if;		

    RETURN retval;
    END;$_$;


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

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

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


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

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

CREATE FUNCTION modoalm(smallint) RETURNS character
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	modo		ALIAS FOR $1; 
	retval 		varchar;
    BEGIN

    if int2eq(modo,1::int2) then retval:='VOLUMEN';   end if;
    if int2eq(modo,2::int2) then retval:='CANTIDAD';   end if;
    if int2eq(modo,3::int2) then retval:='PESO';   end if;



    RETURN retval;
    END;$_$;


ALTER FUNCTION public.modoalm(smallint) OWNER TO zona;

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

CREATE FUNCTION moncteopera(integer) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
declare
operacion	alias for $1; 	--operacion
registro	RECORD;
ret 		numeric;
begin


for registro in select 
    op_impdolar as impdolar, 
    op_importe as importe 
     from operaciones where op_id=operacion
	loop

	if(registro.impdolar is null or numeric_eq(registro.impdolar,0::numeric) or registro.importe is null or numeric_eq(registro.importe,0::numeric)) then   
	    registro.importe=1; registro.impdolar=1;
	end if;

	ret:=registro.impdolar / registro.importe;

	end loop; 

return ret;
END;$_$;


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

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

CREATE FUNCTION monctesitem(integer) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
declare
sitem		alias for $1; 	--Id del Subitem
registro	RECORD;
operacion	int4;
ret 		numeric;
begin

select sitem_idoper into operacion from subitem where sitem_id=sitem;

for registro in select 
    op_impdolar as impdolar, 
    op_importe as importe 
     from operaciones where op_id=operacion
	loop

	if(registro.impdolar is null or numeric_eq(registro.impdolar,0::numeric) or registro.importe is null or numeric_eq(registro.importe,0::numeric)) then   
	    registro.importe=1; registro.impdolar=1;
	end if;

	ret:=registro.impdolar / registro.importe;

	end loop; 

return ret;
END;$_$;


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

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

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


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

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

CREATE FUNCTION monedadeitem(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select item_moneda from item where item_id= $1 ;$_$;


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

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

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


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

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

CREATE FUNCTION monedasitem(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select item_moneda from subitem a, item b where a.sitem_iditem=b.item_id and a.sitem_id= $1 ;$_$;


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

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

CREATE FUNCTION monedasitret(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select monedadeop(sitem_idoper) from subitem,retiros where ret_idsitem=sitem_id and ret_idopera= $1 order by 1 desc limit 1;$_$;


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

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

CREATE FUNCTION monedeempre(integer, integer) RETURNS boolean
    LANGUAGE sql
    AS $_$select true from monex a, astoctas b where a.mne_id= $2 and a.mne_idastoc=b.astc_id and b.astc_codemp= $1 ;$_$;


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

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

CREATE FUNCTION monopinter(integer, integer) RETURNS smallint
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	idop		ALIAS FOR $1;  
	idnop		ALIAS FOR $2;  
	regi		RECORD;
	primera		integer;
	impo		numeric;
	impod		numeric;
	impo20		numeric;
	impod20		numeric;
	tamomal		integer;
	monedar		smallint;
	retval		smallint;
    BEGIN

    primera:=1;
    tamomal:=0;
    for regi in select monedasitem(ret_idsitem) as cualmone from retiros where ret_idopera= $1 
    loop
	if int4eq(primera,1) then
	    primera:=2;
	    monedar=regi.cualmone;
	  else
	    if int2ne(monedar,regi.cualmone) then
		tamomal:=1;
	    end if;
	end if;
    end loop;

    
    if tamomal then
	monedar=2;
    end if;

    update operaciones set op_moneda=monedar where op_id in (idop,idnop);

    select fob_hijos2(idop,2::int2)::numeric(15,2) into impod;
    select fob_hijos2(idop,1::int2)::numeric(15,2) into impo;

    select fob_hijos1(idnop,2::int2)::numeric(15,2) into impod20;
    select fob_hijos1(idnop,1::int2)::numeric(15,2) into impo20;

    update operaciones set op_impdolar=impod ,op_importe=impo where op_id in (idop,idnop) and op_tipoper!=20;
    update operaciones set op_impdolar=impod20 ,op_importe=impo20 where op_id in (idop,idnop) and op_tipoper=20;
    retval:=monedar;
    
    RETURN retval;
    END;$_$;


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

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

CREATE FUNCTION newunif(integer) RETURNS character varying
    LANGUAGE sql
    AS $_$select unif_newcod from unifun where unif_codigo = $1;$_$;


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

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

CREATE FUNCTION nom_tipprod(integer) RETURNS character varying
    LANGUAGE sql
    AS $_$select tip_descrip from tipprod where tip_codigo = $1;$_$;


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

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

CREATE FUNCTION nomartic(integer) RETURNS character
    LANGUAGE sql
    AS $_$select art_nombre from articvta where art_id= $1 ;$_$;


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

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

CREATE FUNCTION nomarticusitem(integer) RETURNS character
    LANGUAGE sql
    AS $_$select articu.artic_descrip from articu,subitem where subitem.sitem_artic=artic_id and sitem_id= $1 ;$_$;


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

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

CREATE FUNCTION nombreciaseg(integer) RETURNS character varying
    LANGUAGE sql
    AS $_$select cs_nombre from ciaseg where cs_id= $1 ;$_$;


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

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

CREATE FUNCTION nombredepo(text) RETURNS character
    LANGUAGE sql
    AS $_$select unif_nombre from unifun where unif_codmaria=trim($1)::int2;$_$;


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

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

CREATE FUNCTION nombredepo1(integer) RETURNS character
    LANGUAGE sql
    AS $_$select unif_nombre from unifun where unif_codigo=$1;$_$;


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

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

CREATE FUNCTION nombretgt(integer) RETURNS character varying
    LANGUAGE sql
    AS $_$select tgte_nombre from tipgente where tgte_id= $1 ;$_$;


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

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

CREATE FUNCTION nombunifsitem(integer) RETURNS character
    LANGUAGE sql
    AS $_$select unif_nombre from unifun a, subitem b where b.sitem_id= $1 and b.sitem_deposito=a.unif_codigo ;$_$;


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

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

CREATE FUNCTION nomcble(integer) RETURNS character
    LANGUAGE sql
    AS $_$select cbl_nombre from ctacble where cbl_id= $1 ;$_$;


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

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

CREATE FUNCTION nomciaseggte(integer) RETURNS character varying
    LANGUAGE sql
    AS $_$select nombreciaseg(as_ciaseg) from artseg where as_estado=1 and as_idorig= $1 ;$_$;


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

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

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


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

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

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


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

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

CREATE FUNCTION nomconpag(integer) RETURNS character
    LANGUAGE sql
    AS $_$select cdp_nombre from conpag where cdp_codigo= $1 ;$_$;


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

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

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


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

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

CREATE FUNCTION nomdespach(integer) RETURNS character
    LANGUAGE sql
    AS $_$select desp_nombre from despach where desp_id= $1 ;$_$;


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

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

CREATE FUNCTION nomemp(integer) RETURNS character
    LANGUAGE sql
    AS $_$select emp_nombre from empresa where emp_codigo= $1 ;$_$;


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

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

CREATE FUNCTION nomemple(integer) RETURNS character
    LANGUAGE sql
    AS $_$select e_nombre from empleados where e_id= $1 ;$_$;


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

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

CREATE FUNCTION nomestadodeop(integer) RETURNS character
    LANGUAGE sql
    AS $_$select eto_nombre from estoper where eto_codigo=estadop($1);$_$;


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

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

CREATE FUNCTION nomestusu(smallint) RETURNS character
    LANGUAGE sql
    AS $_$select esc_nombre from estusu where esc_codigo= $1 ;$_$;


ALTER FUNCTION public.nomestusu(smallint) OWNER TO zona;

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

CREATE FUNCTION nomgente(integer) RETURNS character
    LANGUAGE sql
    AS $_$select gte_nombre from gente where gte_id= $1 ;$_$;


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

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

CREATE FUNCTION nomiva(integer) RETURNS character
    LANGUAGE sql
    AS $_$select iva_nombre from coniva where iva_codigo= $1 ;$_$;


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

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

CREATE FUNCTION nomivacli(integer) RETURNS character
    LANGUAGE sql
    AS $_$select iva_nombre from coniva,clientes where iva_codigo=cli_coniva and cli_id= $1 ;$_$;


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

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

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


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

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

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


ALTER FUNCTION public.nommoneda(smallint) OWNER TO zona;

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

CREATE FUNCTION nomopera(integer) RETURNS character
    LANGUAGE sql
    AS $_$select operad_nombre from operadores where operad_id= $1 ;$_$;


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

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

CREATE FUNCTION nompais(smallint) RETURNS character
    LANGUAGE sql
    AS $_$select pai_nombre from pais where pai_codigo= $1 ;$_$;


ALTER FUNCTION public.nompais(smallint) OWNER TO zona;

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

CREATE FUNCTION nompaiscli(integer) RETURNS character
    LANGUAGE sql
    AS $_$select pai_nombre from pais,sucursal where pai_codigo=sucu_pais and sucu_cliente= $1 ;$_$;


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

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

CREATE FUNCTION nomposa(character varying) RETURNS character
    LANGUAGE sql
    AS $_$select posa_nombre from posaran where posa_codigo= $1;$_$;


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

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

CREATE FUNCTION nomprov(integer) RETURNS character
    LANGUAGE sql
    AS $_$select pro_nombre from provin where pro_codigo= $1 ;$_$;


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

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

CREATE FUNCTION nomprovcli(integer) RETURNS character
    LANGUAGE sql
    AS $_$select pro_nombre from provin,sucursal where pro_codigo=sucu_provin and sucu_cliente= $1 ;$_$;


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

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

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


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

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

CREATE FUNCTION nomptv(integer) RETURNS character
    LANGUAGE sql
    AS $_$select ptv_nombre from ptovta where ptv_id= $1 ;$_$;


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

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

CREATE FUNCTION nomrubpersonal(integer) RETURNS character
    LANGUAGE sql
    AS $_$select rp_nombre from rubpersonal where rp_id= $1 ;$_$;


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

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

CREATE FUNCTION nomsrubp(integer) RETURNS character
    LANGUAGE sql
    AS $_$select srp_nombre from srubpersonal where srp_id= $1 ;$_$;


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

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

CREATE FUNCTION nomsubtc(integer) RETURNS character
    LANGUAGE sql
    AS $_$select subt_descrip from subtcontrat where subt_id= $1 ;$_$;


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

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

CREATE FUNCTION nomtipc(integer) RETURNS character
    LANGUAGE sql
    AS $_$select tipc_descrip from tipcontrat where tipc_codigo = $1;$_$;


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

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

CREATE FUNCTION nomtipcta(integer) RETURNS character
    LANGUAGE sql
    AS $_$select tct_nombre from tipcta where tct_codigo = $1;$_$;


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

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

CREATE FUNCTION nomtiproditem(integer) RETURNS character
    LANGUAGE sql
    AS $_$select tip_descrip from tipprod a, item b where a.tip_codigo=b.item_tipprod and b.item_id= $1 ;$_$;


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

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

CREATE FUNCTION nomtiprodsitem(integer) RETURNS character
    LANGUAGE sql
    AS $_$select tip_descrip from tipprod a, item b,subitem c where a.tip_codigo=b.item_tipprod and b.item_id=c.sitem_iditem and c.sitem_id= $1 ;$_$;


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

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

CREATE FUNCTION nomtipusu(smallint) RETURNS character
    LANGUAGE sql
    AS $_$select tpu_nombre from tipusu where tpu_codigo= $1 ;$_$;


ALTER FUNCTION public.nomtipusu(smallint) OWNER TO zona;

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

CREATE FUNCTION nomunifsitem(integer) RETURNS character
    LANGUAGE sql
    AS $_$select trim(unif_newcod)||'  -  '||trim(substring(unif_nombre from 1 for position(' -' in unif_nombre))) from unifun a,subitem b where a.unif_codigo=b.sitem_deposito and b.sitem_id= $1 ;$_$;


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

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

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


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

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

CREATE FUNCTION nomusuvta(integer) RETURNS character
    LANGUAGE sql
    AS $_$select nomusu(vt_usuario) from visita where vt_inout= $1 limit 1;$_$;


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

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

CREATE FUNCTION nomvend(integer) RETURNS character
    LANGUAGE sql
    AS $_$select ven_nombre from vendedor where ven_id= $1 ;$_$;


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

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

CREATE FUNCTION nomzona(integer) RETURNS character
    LANGUAGE sql
    AS $_$select zon_nombre from zona where zon_codigo= $1 ;$_$;


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

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

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


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

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

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


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

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

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


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

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

CREATE FUNCTION numero_letras(numeric) RETURNS text
    LANGUAGE plpgsql
    AS $_$
DECLARE
     numero	ALIAS FOR $1;
     lnEntero INTEGER;
     lcRetorno TEXT;
     lnTerna INTEGER;
     lcMiles TEXT;
     lcCadena TEXT;
     lnUnidades INTEGER;
     lnDecenas INTEGER;
     lnCentenas INTEGER;
     lnFraccion INTEGER;
     lnSw INTEGER;
BEGIN
     lnEntero := FLOOR(numero)::INTEGER;--Obtenemos la parte Entera
     lnFraccion := FLOOR(((numero - lnEntero) * 100))::INTEGER;--Obtenemos la Fraccion del Monto
     lcRetorno := '';
     lnTerna := 1;
     IF lnEntero > 0 THEN
     lnSw := LENGTH(lnEntero);
     WHILE lnTerna <= lnSw LOOP
        -- Recorro terna por terna
        lcCadena = '';
        lnUnidades = lnEntero % 10;
        lnEntero = CAST(lnEntero/10 AS INTEGER);
        lnDecenas = lnEntero % 10;
        lnEntero = CAST(lnEntero/10 AS INTEGER);
        lnCentenas = lnEntero % 10;
        lnEntero = CAST(lnEntero/10 AS INTEGER);
    -- Analizo las unidades
       SELECT
         CASE /* UNIDADES */
           WHEN lnUnidades = 1 AND lnTerna = 1 THEN 'UNO ' || lcCadena
           WHEN lnUnidades = 1 AND lnTerna <> 1 THEN 'UN ' || lcCadena
           WHEN lnUnidades = 2 THEN 'DOS ' || lcCadena
           WHEN lnUnidades = 3 THEN 'TRES ' || lcCadena
           WHEN lnUnidades = 4 THEN 'CUATRO ' || lcCadena
           WHEN lnUnidades = 5 THEN 'CINCO ' || lcCadena
           WHEN lnUnidades = 6 THEN 'SEIS ' || lcCadena
           WHEN lnUnidades = 7 THEN 'SIETE ' || lcCadena
           WHEN lnUnidades = 8 THEN 'OCHO ' || lcCadena
           WHEN lnUnidades = 9 THEN 'NUEVE ' || lcCadena
           ELSE lcCadena
          END INTO lcCadena;
          /* UNIDADES */
    -- Analizo las decenas
    SELECT
    CASE /* DECENAS */
      WHEN lnDecenas = 1 THEN
        CASE lnUnidades
          WHEN 0 THEN 'DIEZ '
          WHEN 1 THEN 'ONCE '
          WHEN 2 THEN 'DOCE '
          WHEN 3 THEN 'TRECE '
          WHEN 4 THEN 'CATORCE '
          WHEN 5 THEN 'QUINCE '
          ELSE 'DIECI' || lcCadena
        END
      WHEN lnDecenas = 2 AND lnUnidades = 0 THEN 'VEINTE ' || lcCadena
      WHEN lnDecenas = 2 AND lnUnidades <> 0 THEN 'VEINTI' || lcCadena
      WHEN lnDecenas = 3 AND lnUnidades = 0 THEN 'TREINTA ' || lcCadena
      WHEN lnDecenas = 3 AND lnUnidades <> 0 THEN 'TREINTA Y ' || lcCadena
      WHEN lnDecenas = 4 AND lnUnidades = 0 THEN 'CUARENTA ' || lcCadena
      WHEN lnDecenas = 4 AND lnUnidades <> 0 THEN 'CUARENTA Y ' || lcCadena
      WHEN lnDecenas = 5 AND lnUnidades = 0 THEN 'CINCUENTA ' || lcCadena
      WHEN lnDecenas = 5 AND lnUnidades <> 0 THEN 'CINCUENTA Y ' || lcCadena
      WHEN lnDecenas = 6 AND lnUnidades = 0 THEN 'SESENTA ' || lcCadena
      WHEN lnDecenas = 6 AND lnUnidades <> 0 THEN 'SESENTA Y ' || lcCadena
      WHEN lnDecenas = 7 AND lnUnidades = 0 THEN 'SETENTA ' || lcCadena
      WHEN lnDecenas = 7 AND lnUnidades <> 0 THEN 'SETENTA Y ' || lcCadena
      WHEN lnDecenas = 8 AND lnUnidades = 0 THEN 'OCHENTA ' || lcCadena
      WHEN lnDecenas = 8 AND lnUnidades <> 0 THEN 'OCHENTA Y ' || lcCadena
      WHEN lnDecenas = 9 AND lnUnidades = 0 THEN 'NOVENTA ' || lcCadena
      WHEN lnDecenas = 9 AND lnUnidades <> 0 THEN 'NOVENTA Y ' || lcCadena
      ELSE lcCadena
    END INTO lcCadena; /* DECENAS */
    -- Analizo las centenas
    SELECT
    CASE /* CENTENAS */
      WHEN lnCentenas = 1 AND lnUnidades = 0 AND lnDecenas = 0 THEN 'CIEN ' || lcCadena
      WHEN lnCentenas = 1 AND NOT(lnUnidades = 0 AND lnDecenas = 0) THEN 'CIENTO ' || lcCadena
      WHEN lnCentenas = 2 THEN 'DOSCIENTOS ' || lcCadena
      WHEN lnCentenas = 3 THEN 'TRESCIENTOS ' || lcCadena
      WHEN lnCentenas = 4 THEN 'CUATROCIENTOS ' || lcCadena
      WHEN lnCentenas = 5 THEN 'QUINIENTOS ' || lcCadena
      WHEN lnCentenas = 6 THEN 'SEISCIENTOS ' || lcCadena
      WHEN lnCentenas = 7 THEN 'SETECIENTOS ' || lcCadena
      WHEN lnCentenas = 8 THEN 'OCHOCIENTOS ' || lcCadena
      WHEN lnCentenas = 9 THEN 'NOVECIENTOS ' || lcCadena
      ELSE lcCadena
    END INTO lcCadena;/* CENTENAS */
    -- Analizo la terna
    SELECT
    CASE /* TERNA */
      WHEN lnTerna = 1 THEN lcCadena
      WHEN lnTerna = 2 AND (lnUnidades + lnDecenas + lnCentenas <> 0) THEN lcCadena || ' MIL '
      WHEN lnTerna = 3 AND (lnUnidades + lnDecenas + lnCentenas <> 0) AND
        lnUnidades = 1 AND lnDecenas = 0 AND lnCentenas = 0 THEN lcCadena || ' MILLON '
      WHEN lnTerna = 3 AND (lnUnidades + lnDecenas + lnCentenas <> 0) AND
        NOT (lnUnidades = 1 AND lnDecenas = 0 AND lnCentenas = 0) THEN lcCadena || ' MILLONES '
      WHEN lnTerna = 4 AND (lnUnidades + lnDecenas + lnCentenas <> 0) THEN lcCadena || ' MIL MILLONES '
      ELSE ''
    END INTO lcCadena;/* TERNA */
 
    --Retornamos los Valores Obtenidos
    lcRetorno = lcCadena  || lcRetorno;
    lnTerna = lnTerna + 1;
    END LOOP;
  END IF;
  IF lnTerna = 1 THEN
    lcRetorno := 'CERO';
  END IF;

  
  IF lnFraccion!= 0  THEN
	lcRetorno :=' PESOS ' || RTRIM(lcRetorno) || ' CON ' || LTRIM(lnFraccion) || '/100 CENTAVOS ------';
    else
	lcRetorno :=' PESOS ' || RTRIM(lcRetorno) || ' ------';
  END IF;

RETURN lcRetorno;
end;$_$;


ALTER FUNCTION public.numero_letras(numeric) OWNER TO zona;

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

CREATE FUNCTION numtalon(integer, integer, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	ptovta		ALIAS FOR $1; 
	comproba	ALIAS FOR $2; 
	modo		ALIAS FOR $3; -- 1:graba  2:consulta
	otro 		integer;
	talonario	integer;
	retval 		integer;
    BEGIN

    select comp_talon into talonario from
    	 comprob where int4eq(comproba,comp_id);

    select tal_valor into retval from
    	 talon where int4eq(talonario,tal_id);

    if found then
	if int4eq(modo,1) then
	    update talon set tal_valor=tal_valor+1 where int4eq(talonario,tal_id);
	end if;		
    end if;
    RETURN retval;
    END;$_$;


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

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

CREATE FUNCTION numtalonf(integer, integer, date) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	ptovta		ALIAS FOR $1; 
	comprob		ALIAS FOR $2; 
	fecha		ALIAS FOR $3;
	otro 		integer;
	anter		date;
	retval 		integer;
    BEGIN

    select tal_fecha into anter from
    	 talon where int4eq(ptovta,tal_idptov) and int4eq(comprob,tal_comprob);

    if(date_le(anter,fecha)) then
	select tal_valor into retval from
    	    talon where int4eq(ptovta,tal_idptov) and int4eq(comprob,tal_comprob);
	if not found then
		otro:=0;
		select tal_valor into retval from talon where int4eq(otro,tal_idptov) and int4eq(comprob,tal_comprob);
		update talon set tal_valor=tal_valor+1,tal_fecha=fecha where int4eq(otro,tal_idptov) and int4eq(comprob,tal_comprob);
	     else
		update talon set tal_valor=tal_valor+1,tal_fecha=fecha where int4eq(ptovta,tal_idptov) and int4eq(comprob,tal_comprob);
	end if;
      else
        retval:=-1;
    end if;

    RETURN retval;
    END;$_$;


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

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

CREATE FUNCTION opera_de_dir_ind(integer, integer, integer, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	directo		ALIAS FOR $1; 
	indirecto	ALIAS FOR $2; 
	tipoper		ALIAS FOR $3; 
	operacion	ALIAS FOR $4; 
	esta 		int4;
	retval 		boolean;
    BEGIN
    retval:='t';

    select op_id into esta from operaciones where
	op_directo=directo and 
	op_indirecto=indirecto and 
	op_tipoper=tipoper and 
	op_id=operacion ;

    if not found  
        then retval:='f';
    end if;		

    RETURN retval;
    END;$_$;


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

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

CREATE FUNCTION opera_publicada(integer) RETURNS boolean
    LANGUAGE sql
    AS $_$select int2eq(b.op_estado,101::int2) from subitem a,operaciones b where a.sitem_idoper=b.op_id and a.sitem_id = $1;$_$;


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

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

CREATE FUNCTION operadrh(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select rh_operadal from requeh where rh_id = $1;$_$;


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

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

CREATE FUNCTION opimpdolar(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sum(sitem_imp_dolar) from subitem where sitem_idoper= $1 ;$_$;


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

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

CREATE FUNCTION opverif(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select auxo_verif from auxoper where auxo_idoper= $1 ;$_$;


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

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

CREATE FUNCTION orden_tarifa(integer, integer) RETURNS smallint
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	usuario		ALIAS FOR $1;  
	articulo	ALIAS FOR $2; 
	orden		int2;
	retval		int2;
    BEGIN

    retval:=1;
    SELECT  max(tari_orden) INTO orden
	    FROM tarifas   WHERE int4eq(tari_idart,articulo) and int4eq(tari_usuario,usuario);

    if int2gt(orden,0::int2) then
	    retval:= orden + 1;
    end if;

    RETURN retval;
    END;$_$;


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

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

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

ret:='f';

if(int4eq(usuario,0::int4)) then
	delete from confactur where cfc_idart=articulo and cfc_anio=anio and cfc_mes=mes;
	for registro in select 
	    * from tarifas where tari_idart=articulo
		and estadocontr(tari_idcontr)=1 and date_ge(tari_fhasta,fecha) and date_le(tari_fdesde,fecha)
	loop
	    ret:='t';
--	    insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_estado,cfc_anio,cfc_mes) values (registro.tari_usuario,fecha,articulo::int4,1::numeric,registro.tari_importe::numeric,registro.tari_importe::numeric,1::int2,anio,mes);
	    insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_estado,cfc_anio,cfc_mes) values (registro.tari_usuario,fecha,articulo::int4,1::numeric,valtarico(registro.tari_usuario,articulo,0::numeric,0::int2,fecha::date,registro.tari_idcontr,registro.tari_orden),valtarico(registro.tari_usuario,articulo,0::numeric,0::int2,fecha::date,registro.tari_idcontr,registro.tari_orden),1::int2,anio,mes);
	end loop; 

    else

	delete from confactur where cfc_anio=anio and cfc_mes=mes and cfc_usuario=usuario and cfc_idart=articulo;
--	select tari_importe into importe from tarifas where tari_idart=articulo and tari_usuario=usuario and estadocontr(tari_idcontr)=1 and date_ge(tari_fhasta,fecha) and date_le(tari_fdesde,fecha);
	select valtarico(usuario,articulo,0::numeric,0::int2,fecha::date,tari_idcontr,tari_orden) into importe from tarifas where  estadocontr(tari_idcontr)=1 ;
	insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_estado,cfc_anio,cfc_mes) values (usuario,fecha,articulo::int4,1::numeric,importe::numeric,importe::numeric,1::int2,anio,mes);
end if;

return ret;
end;$_$;


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

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

CREATE FUNCTION pagfac1(integer) RETURNS character
    LANGUAGE plpgsql
    AS $_$
declare
idastoh		 alias for $1;
ret 		 varchar;
aux1 		 varchar;
aux2 		 varchar;
codemp	 	 integer;
cuantchq 	 integer;
pago	 	 numeric;
eneft	 	 numeric;
enchq	 	 numeric;
enotr	 	 numeric;
begin
codemp:=1;

    select sum(astc_importe) into pago from astoctas where astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'DEUDXV')::integer) and astc_importe<0 and codcomp(astc_comprob) not in ('CA','CB');

    if pago is not null then
	ret:='Forma de Pago:';
	select sum(astc_importe) into eneft from astoctas where astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'CAJA')::integer) and astc_importe>0;
	select sum(astc_importe) into enchq from astoctas where astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer) and astc_importe>0;
	select sum(astc_importe) into enotr from astoctas where astc_idastoh=idastoh and astc_ctacble not in (idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer),idcbl(codemp,valvaramb(codemp,0,'CAJA')::integer),idcbl(codemp,valvaramb(codemp,0,'DEUDXV')::integer)) and astc_importe>0;
	if eneft is not null then
	    ret:= ret || '  Efectivo                                                      $'|| eneft ;
	  else	    
	    if enchq is not null then
		select count(*) into cuantchq from cheques, astoctas where chq_idastoc=astc_id and astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer) and astc_importe>0;
		if (cuantchq>2) then
		    ret:= ret || '  Cheques segun detalle al dorso                                 $'|| enchq ;
		    end if;
		if (cuantchq<3) then
		    select descchqf(chq_id) into aux1 from cheques, astoctas where chq_idastoc=astc_id and astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer) and astc_importe>0 order by chq_id asc limit 1;
		    ret:= ret ||' Cheque '|| aux1;
		    end if;
	      else	    
		if enotr is not null then
		    select desccble(astc_ctacble) into aux2 from astoctas where astc_idastoh=idastoh and astc_ctacble not in (idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer),idcbl(codemp,valvaramb(codemp,0,'CAJA')::integer),idcbl(codemp,valvaramb(codemp,0,'DEUDXV')::integer)) and astc_importe>0;
		    ret:= ret ||'  '|| aux2 ||'                 $'||  enotr;
		    end if;
		end if;
	    end if;
	end if;

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

return ret;
end;$_$;


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

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

CREATE FUNCTION pagfac2(integer) RETURNS character
    LANGUAGE plpgsql
    AS $_$
declare
idastoh		 alias for $1;
ret 		 varchar;
aux1 		 varchar;
aux2 		 varchar;
codemp	 	 integer;
cuantchq 	 integer;
pago	 	 numeric;
eneft	 	 numeric;
enchq	 	 numeric;
enotr	 	 numeric;
begin
codemp:=1;

    select sum(astc_importe) into pago from astoctas where astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'DEUDXV')::integer) and astc_importe<0 and codcomp(astc_comprob) not in ('CA','CB');

    if pago is not null then
	select sum(astc_importe) into eneft from astoctas where astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'CAJA')::integer) and astc_importe>0;
	select sum(astc_importe) into enchq from astoctas where astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer) and astc_importe>0;
	select sum(astc_importe) into enotr from astoctas where astc_idastoh=idastoh and astc_ctacble not in (idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer),idcbl(codemp,valvaramb(codemp,0,'CAJA')::integer),idcbl(codemp,valvaramb(codemp,0,'DEUDXV')::integer)) and astc_importe>0;
	if eneft is not null then
	    if enchq is not null then
		select descchqf(chq_id) into aux1 from cheques, astoctas where chq_idastoc=astc_id and astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer) and astc_importe>0 limit 1;
		ret:= ret ||' Cheque '|| aux1;
	      else	    
		if enotr is not null then
		    select desccble(astc_ctacble) into aux2 from astoctas where astc_idastoh=idastoh and astc_ctacble not in (idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer),idcbl(codemp,valvaramb(codemp,0,'CAJA')::integer),idcbl(codemp,valvaramb(codemp,0,'DEUDXV')::integer)) and astc_importe>0;
		    ret:= ret ||'  '|| aux2 ||'                 $'||  enotr;
		    end if;
		end if;

	  else    

	    if enchq is not null then
		select count(*) into cuantchq from cheques, astoctas where chq_idastoc=astc_id and astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer) and astc_importe>0;
		if int4eq(cuantchq,2) then
		    select descchqf(chq_id) into aux1 from cheques, astoctas where chq_idastoc=astc_id and astc_idastoh=idastoh and astc_ctacble=idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer) and astc_importe>0 order by chq_id desc limit 1;
		    ret:= ret ||' Cheque '|| aux1;
	    	  else	    
		    if enotr is not null then
			select desccble(astc_ctacble) into aux2 from astoctas where astc_idastoh=idastoh and astc_ctacble not in (idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer),idcbl(codemp,valvaramb(codemp,0,'CAJA')::integer),idcbl(codemp,valvaramb(codemp,0,'DEUDXV')::integer)) and astc_importe>0;
			ret:= ret ||'  '|| aux2 ||'                 $'||  enotr;
			end if;
		    end if;

	      else	    

		if enotr is not null then
		    select desccble(astc_ctacble) into aux2 from astoctas where astc_idastoh=idastoh and astc_ctacble not in (idcbl(codemp,valvaramb(codemp,0,'CHEQUE')::integer),idcbl(codemp,valvaramb(codemp,0,'CAJA')::integer),idcbl(codemp,valvaramb(codemp,0,'DEUDXV')::integer)) and astc_importe>0;
		    ret:= ret ||'  '|| aux2 ||'                 $'||  enotr;
		    end if;
		end if;
	    end if;
	end if;

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

return ret;
end;$_$;


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

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

CREATE FUNCTION pagosdeashid(integer) RETURNS character varying
    LANGUAGE plpgsql
    AS $_$
declare
idastoh		 alias for $1;
ret 		 character varying;
registro	 record;
regist		 record;
ctacte		 integer;
grupo		 integer;
idastoc		 integer;
begin

for registro in select 
     * from astoctas where astc_idastoh=idastoh
    loop
	if registro.astc_ctacble=134 then
	    ctacte:=registro.astc_ctacte;
	    grupo:=registro.astc_grupo;
	    idastoc:=registro.astc_id;
ret:='';
	    for regist in select 
    		 * from astoctas where astc_ctacte=ctacte and astc_grupo=grupo and astc_id!=idastoc and astc_importe>0
    		loop
		ret:= ret || ' / '||codcompastc(regist.astc_id)||' - '||regist.astc_numero::character||' - '||regist.astc_fecval;
	    end loop; 
	end if;
    end loop; 
return ret;

end;$_$;


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

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

CREATE FUNCTION paisorideitem(integer) RETURNS character
    LANGUAGE sql
    AS $_$select a.pai_nombre  from pais a, item b where a.pai_codigo=b.item_paisorigen and b.item_id= $1 ;$_$;


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

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

CREATE FUNCTION patentede(integer) RETURNS character
    LANGUAGE sql
    AS $_$select lv_patente from livianos where lv_id= $1;$_$;


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

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

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


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

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

CREATE FUNCTION patoper(integer) RETURNS character
    LANGUAGE plpgsql
    AS $_$
declare
idoper		 alias for $1;
ret 		 varchar;
auxot		 varchar;
begin

    select opv_pat_tractor into ret from opervehi where opv_idoper = idoper limit 1;

    if ret is null then 
	ret:='A/CARGAR';
    end if;

return ret;
end;$_$;


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

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

CREATE FUNCTION polizagte(integer) RETURNS character varying
    LANGUAGE sql
    AS $_$select as_poliza from artseg where as_idorig= $1 ;$_$;


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

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

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


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

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

CREATE FUNCTION posadeitem(integer) RETURNS character
    LANGUAGE sql
    AS $_$select item_posa from item where  item_id= $1 ;$_$;


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

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

CREATE FUNCTION precio_unitario(integer) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	item		ALIAS FOR $1; -- id del Sub Item.
	retval 		numeric;
	importe		numeric;
	cantidad	numeric;
    BEGIN
    retval:=0;
    SELECT   sitem_importe,sitem_canting INTO importe,cantidad
	    FROM subitem   WHERE int4eq(sitem_id,item);
    if(importe!=0 and cantidad!=0) then
	retval:= importe / cantidad::numeric;
    end if;	    
	    
    RETURN retval;
    END;$_$;


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

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

CREATE FUNCTION precio_unitariod(integer) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	item		ALIAS FOR $1; -- id del Sub Item.
	retval 		numeric;
	importe		numeric;
	cantidad	numeric;
    BEGIN
    retval:=0;
    SELECT   sitem_imp_dolar,sitem_canting INTO importe,cantidad
	    FROM subitem   WHERE int4eq(sitem_id,item);

    if(importe!=0 and cantidad!=0) then
	retval:= importe / cantidad::numeric;
    end if;	    

    RETURN retval;
    END;$_$;


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

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

CREATE FUNCTION preciodesitem(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sitem_importe/sitem_canting from subitem where sitem_importe!=0 and sitem_id= $1 ;$_$;


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

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

CREATE FUNCTION preciodoldesitem(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sitem_imp_dolar/sitem_canting from subitem where sitem_imp_dolar!=0 and sitem_id= $1 ;$_$;


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

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

CREATE FUNCTION presintdeopv(integer) RETURNS character
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	idopv		ALIAS FOR $1;  
	codmarcont	int4;
	indi		int4;
	regi		RECORD;
	trans		varchar;
	trans1		varchar;
	retval		varchar;
    BEGIN

    indi=1;
    for regi in select * from contene where cont_idopv= $1 
    loop
	trans1:= regi.cont_preori||'-'||regi.cont_preana;

	if indi>1 then
		retval:= trans1||' / '||regi.cont_preori||'-'||regi.cont_preana;
	    else
		retval:= trans1;
	end if;
	indi:=indi+1;
    end loop;
    
    RETURN retval;
    END;$_$;


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

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

CREATE FUNCTION presintdeopv1(integer) RETURNS character
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	idopv		ALIAS FOR $1;  
	codmarcont	int4;
	indi		int4;
	pase		int4;
	regi		RECORD;
	trans		varchar;
	trans1		varchar;
	trans2		varchar;
	res		varchar;
	retval		varchar;
    BEGIN

    indi=1;
    for regi in select * from contene where cont_idopv= $1 
    loop
	res:='';
	trans:= regi.cont_preori;
	trans1:= regi.cont_preana;
	trans2:= regi.cont_presatel;

	pase:=1;
	if(trans is not null) then
	    res:=trans;
	    pase:=2;
	end if;

	if(trans1 is not null) then
	    if(int4eq(pase,2)) then
		res:=res||'-';
	    end if;
	    res:=res||trans1;
	    pase:=2;
	end if;

	if(trans2 is not null) then
	    if(int4eq(pase,2)) then
		res:=res||'-';
	    end if;
	    res:=res||trans2;
	    pase:=2;
	end if;

	if(int4eq(pase,1)) then
	    res:=' ';
	end if;

	if indi>1 then
		retval:= retval||' / '||res;
	    else
		retval:= res;
	end if;
	indi:=indi+1;
    end loop;
    
    RETURN retval;
    END;$_$;


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

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

CREATE FUNCTION procdif(integer, integer, date, date) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	idptov		ALIAS FOR $1; 
	ctacble		ALIAS FOR $2;
	fechad		ALIAS FOR $3;
	fechah		ALIAS FOR $4;
	codemp		integer;
	saldo 		numeric;
	coef		numeric;
	coefref		numeric;
	coefaa		numeric;
	coefrel		numeric;
	auximp		numeric;
	mesd		integer;
	aniod		integer;
	mesh		integer;
	anioh		integer;
	mesa		integer;
	anioa		integer;
	tipcta		integer;
	registro	record;
    BEGIN

    select ptv_codemp into codemp from ptovta where ptv_id=idptov;

    select date_part('month',fechad)::integer,date_part('year',fechad)::integer into mesd,aniod;
    select date_part('month',fechah)::integer,date_part('year',fechah)::integer into mesh,anioh;

    mesa:=mesd;
    anioa:=aniod;

    if int4eq(mesd,1) then
	mesa:=12;
	anioa:=anioa-1;
    else
	mesa:=mesa-1;
    end if;

    select inf_coef into coefaa from inflacion where inf_mes=mesa and inf_anio=anioa;
    if coefaa is null then
	coefaa:=1;
    end if;

    RAISE NOTICE 'COEFAA %, PERIODO %-%',coefaa,mesa,anioa;

    mesa:=mesd;
    anioa:=aniod;


    select inf_coef into coefref from inflacion where inf_mes=mesh and inf_anio=anioh;
    if coefref is null then
	coefref:=1;
    end if;


    coefaa:=coefref/coefaa;
    RAISE NOTICE 'COEFAA %',coefaa;
    coefaa:=coefaa-1;
    RAISE NOTICE 'COEFAA %',coefaa;

    if int4lt(mesh,12) then
	mesh:=mesh+1;
    else
	mesh:=1;
	anioh:=anioh+1;
    end if;

    while int4ne(mesa,mesh) or int4ne(anioa,anioh) loop

	RAISE NOTICE 'PERIODO AVANZO %-%, HASTA %-%',mesa,anioa,mesh,anioh;

	select inf_coef into coef from inflacion where inf_mes=mesa and inf_anio=anioa;
	if coef is null then
	    coef:=1;
	end if;

	saldo:=0;

	RAISE NOTICE 'SALDO % ',saldo;

	delete from difcta where dc_mes=mesa and dc_anio=anioa and dc_ctacble=ctacble and dc_codemp=codemp and dc_idptov=idptov;

	if int4eq(mesa,mesd) and int4eq(anioa,aniod) then
	    RAISE NOTICE 'PERIODO AVANZO %-%, DESDE %-%',mesa,anioa,mesd,aniod;
	    if int4gt(idptov,0) then
		select astc_importe into saldo from astoctas where codcomp(astc_comprob)='AA' and astc_idptov=idptov and astc_estado=2 and astc_ctacble=ctacble and date_part('month',astc_fecval)::integer=mesd and date_part('year',astc_fecval)::integer=aniod;
		if saldo is not null then
		    saldo:=saldo*coefaa;
		end if;
	    else
		select astc_importe into saldo from astoctas where codcomp(astc_comprob)='AA' and astc_estado=2 and astc_ctacble=ctacble and date_part('month',astc_fecval)::integer=mesd and date_part('year',astc_fecval)::integer=aniod;
		if saldo is not null then
		    saldo:=saldo*coefaa;
		end if;
	    end if;
	end if;

	coefrel:=coefref/coef;
	coefrel:=coefrel-1;

	if int4gt(idptov,0) then
	    for registro in select * from astoctas where codcomp(astc_comprob) not in ('AA') and astc_idptov=idptov and astc_estado=2 and astc_ctacble=ctacble and date_part('month',astc_fecval)::integer=mesa and date_part('year',astc_fecval)::integer=anioa order by 1 loop 
		saldo:=saldo+(registro.astc_importe*coefrel);
	    end loop;
	    insert into difcta (dc_mes,dc_anio,dc_ctacble,dc_importeacum,dc_codemp,dc_idptov) values (mesa,anioa,ctacble,saldo,codemp,idptov);
	else
	    for registro in select * from astoctas where codcomp(astc_comprob) not in ('AA') and astc_estado=2 and astc_ctacble=ctacble and date_part('month',astc_fecval)::integer=mesa and date_part('year',astc_fecval)::integer=anioa order by 1 loop 
		saldo:=saldo+(registro.astc_importe*coefrel);
	    end loop;
	    insert into difcta (dc_mes,dc_anio,dc_ctacble,dc_importeacum,dc_codemp,dc_idptov) values (mesa,anioa,ctacble,saldo,codemp,idptov);
	end if;

	RAISE NOTICE 'SALDO % ',saldo;

	if int4lt(mesa,12) then
	    mesa:=mesa+1;
	else
	    mesa:=1;
	    anioa:=anioa+1;
	end if;

    end loop;

    RETURN 1;
    END;$_$;


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

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

CREATE FUNCTION provdeastc(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,'DEUDXC')::integer) limit 1;$_$;


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

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

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


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

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

CREATE FUNCTION provinclie(integer, integer) RETURNS integer
    LANGUAGE sql
    AS $_$select sucu_provin from sucursal where sucu_cliente= $1 and sucu_codigo= $2 ;$_$;


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

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

CREATE FUNCTION proxcodprov(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select max(prov_codigo)+1 from prove where prov_codemp= $1 ;$_$;


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

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

CREATE FUNCTION proxgpocli(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select max(astc_grupo)+1 from astoctas where astc_codemp=1 and astc_ctacble=18 and astc_ctacte= $1 ;$_$;


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

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

CREATE FUNCTION pruebaindi(integer, integer) RETURNS boolean
    LANGUAGE sql
    AS $_$select 't'::boolean as temporal from contratos where contr_locador = $1 and contr_locatario = $2 and contr_estado=1 and contr_idsubt in (7,8,9,11) limit 1;$_$;


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

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

CREATE FUNCTION ptovdefault(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select ptv_id from ptovta where ptv_codemp= $1 order by ptv_id limit 1;$_$;


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

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

CREATE FUNCTION ptovemp(integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	empresa		ALIAS FOR $1; 
	retval 		integer;
	cuantos		integer;
    BEGIN
    select count(*) into cuantos from
    	 ptovta where int4eq(empresa,ptv_codemp);

	 if int4eq(cuantos,1) then
		select ptv_id into retval from
    		ptovta where int4eq(empresa,ptv_codemp);
	    else
		retval:=-1;
	 end if;		
    RETURN retval;
    END;$_$;


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

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

CREATE FUNCTION publico(date) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	fecha		ALIAS FOR $1; -- fecha
	registro	RECORD;
	regi		RECORD;
	regi2		RECORD;
	primera		int4;
	estado		int2;
	operacion	int4;
	fecsal		date;
	operaciono	int4;
	fecsalo		date;
	trans		boolean;
	retval		int4;

    BEGIN

    primera:=1;
    estado:=0;

    for registro in
	select * from opervehi where opv_est_camion < 50 and opv_fecha_egr is not null order by opv_idoper
	loop
	operacion:=registro.opv_idoper;
	fecsal:=registro.opv_fecha_egr;

	if(int4eq(primera,1) or int4ne(operacion,operaciono)) then
		primera:=0;

		if(int2eq(estado,1::int2)) then
		    insert into auxoperv (avh_idoper,avh_fecha_pub) values (operaciono,fecsalo);
		end if;
		estado:=0;

		if(int2eq(registro.opv_est_camion,2::int2) and int2ne(estado,2::int2) and date_le(date(registro.opv_fecha_egr),fecha)) then
		        estado:=1;
		    else
			estado:=2;
		end if;

	    else

		if(int2ne(estado,2::int2) and int2eq(registro.opv_est_camion,2::int2) and date_le(date(registro.opv_fecha_egr),fecha)) then
		        estado:=1;
		    else
			estado:=2;
		end if;

	end if;

	operaciono:=registro.opv_idoper;
	fecsalo:=registro.opv_fecha_egr;

	end loop;

	if(int2eq(estado,1::int2)) then
	    insert into auxoperv (avh_idoper,avh_fecha_pub) values (operaciono,fecsalo);
	    retval:=operaciono;
	end if;


    for regi2 in
	select * from opervehi where opv_est_camion < 50 and opv_fecha_egr is null order by opv_idoper
	loop
	    delete from auxoperv where avh_idoper=regi2.opv_idoper;
	end loop;


    for regi in
	select * from auxoperv  
	loop
	    if(int2lt(estado_opera(regi.avh_idoper),100::int2)) then
		trans:=cambio_estado(regi.avh_idoper,101::int2,1::int2);
		update opervehi set opv_est_camion=50 where opv_idoper=regi.avh_idoper and opv_est_camion < 50;
		if(int4lt(tipoperdeop(regi.avh_idoper),100)) then
			update operaciones set op_fechain=regi.avh_fecha_pub where op_id=regi.avh_idoper;
		    else
			update operaciones set op_fechain=regi.avh_fecha_pub, op_fecha_close=regi.avh_fecha_pub where op_id=regi.avh_idoper;
		end if;
	    end if;
	end loop;


    delete from auxoperv;


    RETURN retval;
    END;$_$;


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

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

CREATE FUNCTION reenumero(integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
opid		 alias for $1;
registro	 record;
cantidad	 integer;
ret		 boolean;

begin
cantidad:=1;
ret:='f';
for registro in select 
    * from retiros where ret_idopera=opid order by 1
    loop
	update retiros set ret_item=cantidad where ret_id=registro.ret_id;
	cantidad:=cantidad+1;
	ret:='t';
end loop; 

return ret;
end;$_$;


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

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

CREATE FUNCTION reparoweb(integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
modo		 alias for $1;
ret 		 boolean;
registro	 record;
aux_texto	 text;
indirecto	 integer;
operacion	 integer;

begin


lock wret2 in access exclusive mode;

drop trigger au_wret2 ON wret2;


for registro in select 
     * from temporalweb
loop


    if(registro.wtmp_valor>0) then
	    update wret2 set wret2_cantidad=registro.wtmp_valor where wret2_id=registro.wtmp_idret;
--	    update wsubitem set wsitem_cantcompw=wsitem_cantcompw-registro.wtmp_compweb+registro.wtmp_valor where wsitem_id=idsitemdewret2(registro.wtmp_idret);
	    update wsubitem set wsitem_cantcompw=wsitem_cantcompw+registro.wtmp_valor where wsitem_id=idsitemdewret2(registro.wtmp_idret);
	    aux_texto:='SE LE COMUNICA QUE SE HA MODIFICADO LA REEXPEDICION NUMERO:  <b>'||idwopdewret2(registro.wtmp_idret)||'</b> QUE USTED HA CARGADO EN ESTE SISTEMA OPORTUNAMENTE RELACIONADA AL USUARIO INDIRECTO <b>'||nomusu(indirectodewret2(registro.wtmp_idret)) ||'</b>.  EL MOTIVO DE ESTA MODIFICACION RESPONDE AL PROCESAMIENTO POR PARTE DE OPERADORES DE LA CONCESIONARIA DE REEXPEDICIONES QUE AFECTAN AL ARTICULO:  <b>'||articulodewret2(registro.wtmp_idret)||'</b> QUE TAMBIEN FUERA COMPROMETIDO POR USTED.  VERIQUE LA CANTIDAD A RETIRAR DE ESE ARTICULO Y FINALIZE NUEVAMENTE LA OPERACION !!!!!!!';
	    ret:=grabonotiweb(directodewret2(registro.wtmp_idret),5,10,'ARTICULOS PARCIALMENTE COMPROMETIDOS',aux_texto);
	    update woperaciones set wop_estado=11 where wop_id=idwopdewret2(registro.wtmp_idret);

	else
	    aux_texto:='SE LE COMUNICA QUE SE HA ELIMINADO DE LA REEXPEDICION NUMERO:  <b>'||idwopdewret2(registro.wtmp_idret)||'</b> QUE USTED HA CARGADO EN ESTE SISTEMA OPORTUNAMENTE RELACIONADA AL USUARIO INDIRECTO <b>'||nomusu(indirectodewret2(registro.wtmp_idret)) ||'</b>.   EL ARTICULO:  <b>'||articulodewret2(registro.wtmp_idret)||' </b> QUE TAMBIEN FUERA COMPROMETIDO POR USTED.  EL MOTIVO RESPONDE AL PROCESAMIENTO POR PARTE DE OPERADORES DE LA CONCESIONARIA DE REEXPEDICIONES QUE AFECTAN DICHO ARTICULO VERIFIQUE NUEVAMENTE LA OPERACION !!!!!!!';
	    ret:=grabonotiweb(directodewret2(registro.wtmp_idret),5,10,'ITEMS DE REEXPEDICIONES ELIMINADOS',aux_texto);
--	    update wsubitem set wsitem_cantcompw=wsitem_cantcompw-registro.wtmp_compweb where wsitem_id=idsitemdewret2(registro.wtmp_idret);
	    delete from wret2 where wret2_id=registro.wtmp_idret;
	    update woperaciones set wop_estado=11 where wop_id=idwopdewret2(registro.wtmp_idret);

    end if;
end loop; 

CREATE TRIGGER au_wret2 AFTER UPDATE ON wret2 FOR EACH ROW EXECUTE PROCEDURE f_au_wret2();
			
 delete from temporalweb;
ret:='t';
return ret;
end;$_$;


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

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

CREATE FUNCTION retenig(integer, numeric, date) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	provd		ALIAS FOR $1; 
	imppago		ALIAS FOR $2;
	fecha		ALIAS FOR $3;
	codemp		integer;
	ptov		integer;
	tipct		integer;
	retsn		integer;
	idastoh		integer;
	deudxc		integer;
	ctaretig	integer;
	compnk		integer;
	registro	record;
	totpagt		numeric;
	totrett		numeric;
	totpag 		numeric;
	totret 		numeric;
	mnoi 		numeric;
	tasa 		numeric;
	retval 		numeric;
    BEGIN
    select prov_codemp into codemp from prove where prov_id=provd;
    select prov_idptov into ptov from prove where prov_id=provd;
    select valvaramb(codemp,ptov,'TIPCTADXC') into tipct;	
    select idcbl(codemp,valvaramb(codemp,ptov,'DEUDXC')::int4) into deudxc;
    select idcbl(codemp,valvaramb(codemp,ptov,'CTARETIG')::int4) into ctaretig;
    select valvaramb(codemp,ptov,'MNIRETIG') into mnoi;
    select valvaramb(codemp,ptov,'TASARIG') into tasa;
    select prov_retig into retsn from prove where prov_id=provd;
    select idcomp('NK',1) into compnk;

    totrett:=0;
    totpagt:=0;
    totret:=0;
    totpag:=0;
    retval:=0;


    if int4eq(retsn,1) then

	for registro in select 
         * from astoctas where astc_estado=2 and astc_ctacble=deudxc and astc_tipcta=tipct and astc_ctacte=provd and date_part('year',astc_fecval)=date_part('year',fecha::date) and date_part('month',astc_fecval)=date_part('month',fecha::date) and astc_importe>0 and astc_comprob!=compnk  
	    loop 
	    select sum(astc_importe*-1) into totrett from astoctas where astc_idastoh=registro.astc_idastoh and astc_ctacble=ctaretig and astc_importe<0; 
	    select sum(astc_importe*-1) into totpagt from astoctas where astc_idastoh=registro.astc_idastoh and astc_importe<0; 
	
	    if totpagt is null then
		totpagt:=0;
	    end if;

	    if totrett is null then
		totrett:=0;
	    end if;

	    totpag:= totpag + totpagt;
	    totret:= totret + totrett;
	    
	    end loop;

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

	if totret is null then
	    totret:=0;
	end if;

	totpag:= ((totpag + imppago)/1.21) - mnoi;


	if(totpag > 0 ) then
	    retval:= ( totpag * tasa / 100) - totret;
	end if;

	if(retval < 0 ) then
	end if;

    end if;

    RETURN retval;
    END;$_$;


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

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

CREATE FUNCTION reti_a_fecha(integer, date) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
DECLARE
idsitem		ALIAS FOR $1; 	-- id del subitem
fecha		ALIAS FOR $2;	-- fecha hasta
difer1 		numeric;
difer2 		numeric;
retval 		numeric;
BEGIN

retval:=0;

select sum(ret_cantidad) into retval from
    retiros where ret_idsitem=idsitem and date_le(fechainop(ret_idopera),fecha) and estadop(ret_idopera)=101;


if retval is null then
    retval:=0;
end if;


select sum(ret_cantidad) into difer1 from
    retiros where ret_idsitem=idsitem and estadop(ret_idopera)=101;

if difer1 is null then
    difer1:=0;
end if;


select sitem_cantret into difer2 from
    subitem where sitem_id=idsitem;

if difer2 is null then
    difer2:=0;
end if;


if numeric_ne(difer2,difer1) then

retval:=retval + difer2 - difer1;
end if;


RETURN retval;
END;$_$;


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

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

CREATE FUNCTION reti_a_fechap(integer, date) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
DECLARE
idsitem		ALIAS FOR $1; 	-- id del subitem
fecha		ALIAS FOR $2;	-- fecha hasta
retval 		numeric;
BEGIN

retval:=0;

select sum(ret_cantidad) into retval from
    retiros where ret_idsitem=idsitem and date_le(fechainop(ret_idopera),fecha) and estadop(ret_idopera)=101;


if retval is null then
    retval:=0;
end if;


RETURN retval;
END;$_$;


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

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

CREATE FUNCTION retirosafecha(integer, date) RETURNS numeric
    LANGUAGE sql
    AS $_$select sum(ret_cantidad) from retiros where ret_idsitem= $1 and date_le(fechainop(ret_idopera), $2) and estadop(ret_idopera)=101;$_$;


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

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

CREATE FUNCTION rexpconfactur(date, date, smallint, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
desde		 alias for $1;
hasta		 alias for $2;
anio 		 alias for $3;
mes 		 alias for $4;
ret 		 boolean;
registro	 record;
directo		 int4;
indirecto	 int4;
tipoper		 int4;
hay	 	 int4;
auxot		 varchar;
begin

ret:='t';
for registro in select 
    * from operaciones where op_estado=101 and date_ge(op_fechain,desde) and date_le(op_fechain,hasta) and op_tipoper in (101,105) 
	loop

	ret:='f';
	select cfc_id into hay from confactur where cfc_idoper=registro.op_id and cfc_idart=35 and cfc_fecha=registro.op_fechain;
	if not found then
	    auxot:=substr(nomusu(registro.op_indirecto),1,25) || ' / ' || substr(traigo_simbtipoper(registro.op_tipoper),1,3) || '-'|| registro.op_nrotaldir;
--	    insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_idoper,cfc_leyen,cfc_estado,cfc_anio,cfc_mes,cfc_indirecto) values (registro.op_directo,registro.op_fechain,35::int4,1::numeric,20::numeric,20::numeric,registro.op_id,auxot,1::int2,anio,mes,registro.op_indirecto);
	    insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_idoper,cfc_leyen,cfc_estado,cfc_anio,cfc_mes,cfc_indirecto) values (registro.op_directo,registro.op_fechain,35::int4,1::numeric,valtari(registro.op_directo,35,0::numeric,0::int2,registro.op_fechain::date),valtari(registro.op_directo,35,0::numeric,0::int2,registro.op_fechain::date),registro.op_id,auxot,1::int2,anio,mes,registro.op_indirecto);
	end if;

end loop; 

return ret;
end;$_$;


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

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

CREATE FUNCTION rexpconfacturd(date, date, smallint, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
desde		 alias for $1;
hasta		 alias for $2;
anio 		 alias for $3;
mes 		 alias for $4;
ret 		 boolean;
registro	 record;
directo		 int4;
indirecto	 int4;
tipoper		 int4;
hay	 	 int4;
auxot		 varchar;
begin

ret:='t';
for registro in select 
    * from operaciones where op_estado=101 and date_ge(op_fechain,desde) and date_le(op_fechain,hasta) and op_tipoper in (101,105) 
	loop

	ret:='f';
	select cfc_id into hay from confactur where cfc_idoper=registro.op_id and cfc_idart=35;
	if not found then
	    auxot:=substr(nomusu(registro.op_indirecto),1,25) || ' / ' || substr(traigo_simbtipoper(registro.op_tipoper),1,3) || '-'|| registro.op_nrotaldir;
--	    insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_idoper,cfc_leyen,cfc_estado,cfc_anio,cfc_mes,cfc_indirecto) values (registro.op_directo,registro.op_fechain,35::int4,1::numeric,20::numeric,20::numeric,registro.op_id,auxot,1::int2,anio,mes,registro.op_indirecto);
	    insert into confactur (cfc_usuario,cfc_fecha,cfc_idart,cfc_canti,cfc_precio,cfc_importe,cfc_idoper,cfc_leyen,cfc_estado,cfc_anio,cfc_mes,cfc_indirecto) values (registro.op_directo,registro.op_fechain,35::int4,1::numeric,valtari(registro.op_directo,35,0::numeric,0::int2,registro.op_fechain::date),valtari(registro.op_directo,35,0::numeric,0::int2,registro.op_fechain::date),registro.op_id,auxot,1::int2,anio,mes,registro.op_indirecto);
	end if;
end loop; 

return ret;
end;$_$;


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

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

CREATE FUNCTION rezagoconfactur(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;
auxot		 varchar;
begin
ret:='t';

for registro in select 
    * from opervehi,rezago where 
	    opv_idrezago is not null 
	    and opv_idoper in (NULL,2) 
	    and opv_pat_tractor is not NULL 
	    and opv_idrezago=rz_id 
	    and rz_estado!=999 
	    and opv_est_camion!=100 
	    and opv_tipo_camion in (1,3,4,6) 
	    and opv_peso_ing>500 
	    and rz_directo>20 
	    and date_ge(date(opv_fecha_egr),desde) 
	    and date_le(date(opv_fecha_egr),hasta) order by rz_directo
	loop
	ret:='f';

	if(int4eq(registro.opv_tipo_camion,1::int4)) then
	    auxot:='CAMION DE REZAGO';
	end if;

	if(int4eq(registro.opv_tipo_camion,6::int4)) then
	    auxot:='CAMION DE PROVEEDORES';
	end if;

	if(int4eq(registro.opv_tipo_camion,3::int4)) then
	    auxot:='CAMION PARA MOVIMIENTOS INTERNOS';
	end if;

	if(int4eq(registro.opv_tipo_camion,4::int4)) then
	    auxot:='CAMION PARA RETIRO DE CONTENEDORES';
	end if;


	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 (registro.rz_directo,registro.opv_fecha_ing,40::int4,1::numeric,valtari(registro.rz_directo,40,0::numeric,0::int2,registro.opv_fecha_egr::date),valtari(registro.rz_directo,40,0::numeric,0::int2,registro.opv_fecha_egr::date),registro.rz_id*-1,auxot,1::int2,NULL,anio,mes,NULL);
end loop; 

return ret;
end;$_$;


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

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

CREATE FUNCTION rubdearticc(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select artc_rubcomp from articc where artc_id = $1;$_$;


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

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

CREATE FUNCTION rubpdesrubp(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select srp_idrubp from srubpersonal where srp_id= $1 ;$_$;


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

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

CREATE FUNCTION sacoauto(integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
idiol		alias for $1;
ret 		boolean;
idio 		int4;
existe 		int4;
existeo		int4;
fecout		timestamp without time zone;
begin

    existeo:=2;
    select ogxl_io into idio from outgxl where ogxl_iol=idiol limit 1;

    if not found then
	select igxl_io into idio from ingxl where igxl_iol=idiol limit 1;
	if not found then
	    ret:='f';
	  else
	    existe:=1;
	    ret:='t';
	end if;
      else
	existeo:=1;
	existe:=1;
	ret:='t';
    end if;

    if int4eq(existe,1::int4) then
	select io_fecout into fecout from inout where io_id=idio;
	if found then
	    update inoutliv set iol_estado=101, iol_fecout=fecout where iol_id=idiol;	    
	    if int4eq(existeo,2::int4) then
		insert into outgxl values(idiol,idio,101);
	    end if;
	end if;
    end if;




return ret;
end;$_$;


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

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

CREATE FUNCTION saldoal(integer, integer, integer, integer, date) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	codemp		ALIAS FOR $1; 
	ptovta		ALIAS FOR $2; 
	tipcta		ALIAS FOR $3; 
	ctacte		ALIAS FOR $4;
	fechad		ALIAS FOR $5;
	salant 		numeric;
	retval 		numeric;
    BEGIN
    select sum(astc_importe) into retval from astoctas 
	where astc_codemp=codemp and astc_idptov=ptovta and astc_tipcta=tipcta 
	and astc_ctacte=ctacte and astc_fecval< fechad and astc_cierra= 1
	and astc_estado=2;

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


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

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

CREATE FUNCTION saldocbl(integer, integer, integer, date) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	codemp		ALIAS FOR $1; 
	ptovta		ALIAS FOR $2; 
	cuenta		ALIAS FOR $3; 
	fechad		ALIAS FOR $4;
	retval 		numeric;
    BEGIN
    if int4eq(codemp,-1) then
	    select sum(astc_importe) into retval from astoctas 
		where astc_ctacble=cuenta and astc_fecval< fechad and astc_estado=2 and codcomp(astc_comprob)!='AR' ;
        else
	    if int4eq(ptovta,0) then
		    select sum(astc_importe) into retval from astoctas 
			where astc_codemp=codemp and astc_ctacble=cuenta 
			    and astc_estado=2 and astc_comprob not in (6,7,147,157) and astc_fecval< fechad;
    		else
		    select sum(astc_importe) into retval from astoctas 
			where astc_codemp=codemp and astc_idptov=ptovta  
			    and astc_ctacble=cuenta and astc_estado=2 and astc_comprob not in (6,7,147,157) 
			    and astc_fecval< fechad ;
	    end if;
    end if;

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


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

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

CREATE FUNCTION salgrup(integer, integer, integer, integer) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	codemp		ALIAS FOR $1; 
	tipcta		ALIAS FOR $2;
	ctacte		ALIAS FOR $3;
	grupo		ALIAS FOR $4;
	esisti		integer;
	retval 		numeric;
    BEGIN
    if int4eq(grupo,0) then
	    select sum(astc_importe) into retval from astoctas
		where astc_codemp=codemp and astc_estado=2 and astc_tipcta=tipcta
		    and astc_ctacte=ctacte and astc_grupo is null;
	else
	    select sum(astc_importe) into retval from astoctas
		where astc_codemp=codemp and astc_estado=2 and astc_tipcta=tipcta
		    and astc_ctacte=ctacte and astc_grupo=grupo;
    end if;

    if not found then
	retval:=0;
    end if;
    RETURN retval;
    END;$_$;


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

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

CREATE FUNCTION salioel(integer) RETURNS date
    LANGUAGE sql
    AS $_$select fechainop(ret_idopera) from retiros where ret_idsitem = $1 limit 1;$_$;


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

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

CREATE FUNCTION seg_disponible(smallint, numeric, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	cod_unifun	ALIAS FOR $1; -- id dela unifun
	valorfob	ALIAS FOR $2; -- Valor Fob
	caso		ALIAS FOR $3; -- Caso 
	
		    --  0=compara parametro contra monto UNIFUN
		    --  1=compara contra la oper (INSERTO DE OP FUTURO)
 
	compara 	numeric;
	aux_seg 	varchar;
	retval 		boolean;
    BEGIN
	if caso=0 then
		SELECT  unif_seguro - unif_valormerca INTO compara FROM unifun   
		    WHERE cod_unifun = unif_codigo;
			retval:=numeric_le(valorfob,compara); 
	    elsif	
	    caso=1 then
		 SELECT  var_valor  INTO     aux_seg 	-- Controla seguro??
		    FROM varamb    WHERE var_codigo like 'SEGURO%';
	    
		 if bpchareq(aux_seg,'NO') then
			return true;
	        else
	    	SELECT  unif_seguro - unif_valormerca INTO compara FROM unifun   
			WHERE cod_unifun = unif_codigo;
	    	retval:=numeric_le(valorfob,compara); 
	        end if;	
	    
	    end if;


    RETURN retval;
    END;$_$;


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

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

CREATE FUNCTION seg_ok(integer, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	cod_operacion	ALIAS FOR $1; -- id dela operacion
	cod_modo	ALIAS FOR $2; -- modo de operacion
-- modo =	1 valido para notificar y devuelvo true
--		2 valido pulenta (notifico y devuelvo true/false segun)
	compara 	numeric;
	registro 	RECORD;
	retval 		boolean;
	trans 		boolean;
	aux_seg 	varchar;
	aux_texto 	text;
    BEGIN
    retval:='t';		
    SELECT  var_valor  INTO     aux_seg 	-- Controla seguro??
	    FROM varamb    WHERE var_codigo like 'SEGURO%';
	
    if bpchareq(aux_seg,'NO') 
	then return true;
    end if;

    for registro in select sitem_deposito as x,sum(sitem_imp_dolar) as y
     from subitem where sitem_idoper=cod_operacion group by sitem_deposito
	loop
	trans:=seg_disponible(registro.x,registro.y,0::int2);

	if booleq(trans,'f') then 
		retval:=trans;	
		aux_texto:='Con la unifun '||registro.x ||' existen problemas de seguro por '||registro.y ||' !!!!!!!!!!';
		insert into noticias(not_tipo,not_numero,not_texto)values(1,cod_operacion,aux_texto);
	    end if;
	end loop; 

	if  bpchareq(aux_seg,'NI') or (int2eq(cod_modo,1::int2)) then
--	if  bpchareq(aux_seg,'NI') then
--	if   (int2eq(cod_modo,1::int2)) then
	    retval:='t';		
	end if;
    RETURN retval;
    END;$_$;


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

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

CREATE FUNCTION segunifun(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sum(seg_impmoncte) from seguros where seg_estado=1 and seg_importei>0 and seg_unifun= $1 ;$_$;


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

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

CREATE FUNCTION sepuedeimportar(integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
wopid		 alias for $1;
ret 		 boolean;
registro	 record;
begin

ret:='t';

for registro in select 
    cantidisponib(wret2_idsitem) as x, wret2_cantidad as y
    from wret2 where wret2_idopera=wopid 
    loop
	if(booleq(ret,'t')) then
	    if(registro.x < registro.y) then
		ret:='f';
	    end if;
	end if;
    end loop; 

return ret;
end;$_$;


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

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

CREATE FUNCTION sibunimedsitem(integer) RETURNS character
    LANGUAGE sql
    AS $_$select uni_simbolo from unimed a, item b where a.uni_codigo=b.item_unimed and b.item_id= $1 ;$_$;


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

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

CREATE FUNCTION simbmoneda(smallint) RETURNS character
    LANGUAGE sql
    AS $_$select mon_simbol from moneda where mon_codigo= $1 ;$_$;


ALTER FUNCTION public.simbmoneda(smallint) OWNER TO zona;

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

CREATE FUNCTION simbunimeditem(integer) RETURNS character
    LANGUAGE sql
    AS $_$select a.uni_simbolo from unimed a, item b where int2eq(a.uni_codigo,b.item_unimed) and b.item_id= $1 ;$_$;


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

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

CREATE FUNCTION simbunimedsitem(integer) RETURNS character
    LANGUAGE sql
    AS $_$select a.uni_simbolo from unimed a, item b ,subitem c where int2eq(a.uni_codigo,b.item_unimed) and b.item_id=c.sitem_iditem and c.sitem_id= $1 ;$_$;


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

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

CREATE FUNCTION simbunimedwsitem(integer) RETURNS character
    LANGUAGE sql
    AS $_$select uni_simbolo from unimed where uni_codigo= $1 ;$_$;


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

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

CREATE FUNCTION simbunimedwsitem2(integer) RETURNS character
    LANGUAGE sql
    AS $_$select a.uni_simbolo from unimed a,wsubitem b where a.uni_codigo=b.wsitem_unimed and b.wsitem_id= $1 ;$_$;


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

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

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


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

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

CREATE FUNCTION sitemid_alm(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select al_idsitem from almacenaje where al_id= $1 ;$_$;


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

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

CREATE FUNCTION sitemid_almacen(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select alm_idsitem from almacen where alm_id= $1 ;$_$;


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

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

CREATE FUNCTION sitemid_almacenaje(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select al_idsitem from almacenaje where al_id= $1 ;$_$;


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

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

CREATE FUNCTION sitemid_de_almacen(character varying) RETURNS integer
    LANGUAGE sql
    AS $_$select alm_idsitem from almacen where trim(alm_leyenda)= $1 order by alm_id desc limit 1;$_$;


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

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

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


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

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

CREATE FUNCTION stasaconiva(smallint) RETURNS numeric
    LANGUAGE sql
    AS $_$select iva_stasa from coniva where iva_codigo= $1;$_$;


ALTER FUNCTION public.stasaconiva(smallint) OWNER TO zona;

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

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


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

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

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


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

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

CREATE FUNCTION substr(integer, integer, integer) RETURNS text
    LANGUAGE sql
    AS $_$select substr($1::text,$2,$3);$_$;


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

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

CREATE FUNCTION substr(date, integer, integer) RETURNS text
    LANGUAGE sql
    AS $_$select substr($1::text,$2,$3);$_$;


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

--
-- Name: substr(double precision, integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION substr(double precision, integer, integer) RETURNS text
    LANGUAGE sql
    AS $_$select substr($1::text,$2,$3);$_$;


ALTER FUNCTION public.substr(double precision, integer, integer) OWNER TO zona;

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

CREATE FUNCTION subtotf(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sum(movs_importe) from movsto where movs_idastoh= $1 ;$_$;


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

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

CREATE FUNCTION tarjehabilit(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select gte_tarjeta from gente where gte_estado=1 and gte_tarjeta= $1 ;$_$;


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

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

CREATE FUNCTION tasaartic(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select art_tasa from articvta where art_id= $1 ;$_$;


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

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

CREATE FUNCTION tasaconiva(smallint) RETURNS numeric
    LANGUAGE sql
    AS $_$select iva_tasa from coniva where iva_codigo= $1;$_$;


ALTER FUNCTION public.tasaconiva(smallint) OWNER TO zona;

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

CREATE FUNCTION tasaiva_fe(numeric) RETURNS text
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	imp		ALIAS FOR $1;
	inte		integer;
	retval		text;
    BEGIN
	if (numeric_eq(imp,0)) then
	    inte:=3;
	else
	    if (numeric_eq(imp,10.5)) then
		inte:=4;
	    else
		if (numeric_eq(imp,21)) then
		    inte:=5;
		else
		    if (numeric_eq(imp,27)) then
			inte:=6;
		    else
			if (numeric_eq(imp,5)) then
			    inte:=8;
			else
			    if (numeric_eq(imp,2.5)) then
				inte:=9;
			    end if;
			end if;
		    end if;
		end if;
	    end if;
	end if;
	select lpad(inte::text,4,'0') into retval;
	RETURN retval;
    END;$_$;


ALTER FUNCTION public.tasaiva_fe(numeric) OWNER TO zona;

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

CREATE FUNCTION tdocgente(integer) RETURNS character
    LANGUAGE sql
    AS $_$select gte_tdoc from gente where gte_id= $1 ;$_$;


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

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

CREATE FUNCTION tdocngente(integer) RETURNS character
    LANGUAGE sql
    AS $_$select gte_tdoc ||'  -  '||gte_nrodoc from gente where gte_id= $1 ;$_$;


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

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

CREATE FUNCTION tgtegte(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select tgte_tipo from tipgente where tgte_id= $1 ;$_$;


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

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

CREATE FUNCTION tiene_funcion(integer, integer, integer, integer) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	idreg		ALIAS FOR $1;  -- id del registro
	idartic		ALIAS FOR $2;  -- id del articulo 
	idoper		ALIAS FOR $3; 
	tabla		ALIAS FOR $4;  -- 1=voling   y   2=volegr 
	modo		int4;
	pase		int4;
	sinfun		int4;
	registro	record;
	valorfob	text;
	funcion		text;
	funcion2	text;
	funcion3	text;
	cotiz		text;
	peso		text;
	volumen		numeric;
	cantidad	numeric;
	preciopul	numeric;
	precio		numeric;
	retval		numeric;
    BEGIN
    retval:=0;
    pase:=0;
    sinfun:=1;

	select cfac_funcion into funcion from complfac where cfac_id=idreg;
	if not found then
	    select art_funcion into funcion from articvta where art_id=idartic;
	    if not found then
		sinfun:=0;
	    end if;
	end if;


	select cfac_precio into preciopul from complfac where cfac_id=idreg;
	if not found then
	    select art_precio into precio from articvta where art_id=idartic;
	end if;

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


RETURN retval;
END;$_$;


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

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

CREATE FUNCTION tiene_vol(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sum(vol_canting-vol_cantret) from voling where vol_estado=101 and vol_cliente= $1 ;$_$;


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

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

CREATE FUNCTION tienestock(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select sitem_id from subitem where sitem_estado=1 and sitem_canting>sitem_cantret and (sitem_directo=$1 or sitem_indirecto=$1) limit 1;$_$;


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

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

CREATE FUNCTION tipctacbl(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select cbl_tipcta from ctacble where cbl_id= $1 ;$_$;


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

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

CREATE FUNCTION tipgentedeusu(integer, integer) RETURNS integer
    LANGUAGE sql
    AS $_$select gte_id from gente where gte_tipo= $1 and gte_id= $2 ;$_$;


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

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

CREATE FUNCTION tipo_de_contrato(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select subt_idtipc from subtcontrat where subt_id= $1 ;$_$;


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

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

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


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

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

CREATE FUNCTION tipprod_item(integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	itemc	ALIAS FOR $1; -- id del Item
	tipo	int4;
    BEGIN
    SELECT item_tipprod into tipo
	FROM item WHERE item_id = itemc;
    RETURN tipo;
    END;$_$;


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

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

CREATE FUNCTION tipprod_ok(integer, smallint, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	operacion	ALIAS FOR $1; -- id dela operacion
	unifun		ALIAS FOR $2; -- id unifun
	modo		ALIAS FOR $3; -- modo
-- modo =	1 valido para notificar y devuelvo true
--		2 valido pulenta (notifico y devuelvo true/false segun)
	compara 	numeric;
	registro 	RECORD;
	retval 		boolean;
	trans 		boolean;
	aux_seg 	varchar;
	aux_texto 	text;
    BEGIN
    retval:='t';		
    SELECT  var_valor  INTO     aux_seg 	-- Controla tipo de merca?
	    FROM varamb    WHERE var_codigo like 'VALID_TIPMERC%';
	
    if bpchareq(aux_seg,'NO') 
	then return true;
    end if;

    for registro in select sitem_iditem as x,sitem_deposito as y,count(*) as z
     from subitem where sitem_idoper=operacion  group by x,y
	loop
	trans:=tipprod_posible(registro.y::int2,tipprod_item(registro.x));

	if booleq(trans,'f') then 
		retval:=trans;	
		aux_texto:='La unidad funcional '||registro.y||'  ('||traigo_nomunifun(registro.y) ||')  no tolera el ingreso de mercaderia del tipo '||tipprod_item(registro.x) ||' debera cambiar de ubicacion la misma. Notifique al usuario ';
		insert into noticias(not_tipo,not_numero,not_texto)values(1,operacion,aux_texto);
	    end if;
	end loop; 

	if  bpchareq(aux_seg,'NI') or (int2eq(modo,1::int2)) then
	    retval:='t';		
	end if;

    RETURN retval;
    END;$_$;


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

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

CREATE FUNCTION tipprod_posible(smallint, integer) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
    DECLARE
	unifun		ALIAS FOR $1; -- id de Unifun.
	tipmerc		ALIAS FOR $2; -- tipo de Mercaderia
	compara 	numeric;
	registro 	RECORD;
	kk 		int2;
	retval 		boolean;
	trans 		boolean;
	aux_seg 	varchar;
    BEGIN
    retval:='t';		
    SELECT  var_valor  INTO     aux_seg 	-- Controla Tipo de Merca??
	    FROM varamb    WHERE var_codigo like 'VALID_TIPMERC%';
	
    if bpchareq(aux_seg,'NO') 
	then return true;
    end if;


    select txu_codtipp into kk from tippxunif where 
	    int4eq(txu_codtipp,tipmerc) and 
		int2eq(txu_codunif,unifun);
    if not found then 
	return false;
    end if;


    if bpchareq(aux_seg,'NI')  then
	    retval:='t';		
	end if;
    RETURN retval;
    END;$_$;


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

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

CREATE FUNCTION tipproditem(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select item_tipprod from item where item_id = $1;$_$;


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

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

CREATE FUNCTION tipprodsitem(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select i.item_tipprod from item i, subitem s where i.item_id=s.sitem_iditem and sitem_id = $1;$_$;


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

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

CREATE FUNCTION tipprodunifun(integer) RETURNS character varying
    LANGUAGE plpgsql
    AS $_$
declare
unifunc		ALIAS FOR $1; 
regi 		RECORD;
ret		character varying;
begin
ret:='Habilitada para';
for regi in select txu_codtipp,trim(tip_descrip) as ladescrip from tippxunif,tipprod where tip_codigo=txu_codtipp and txu_codunif=unifunc
	loop
	ret:=ret||' / '||regi.ladescrip;		
        end loop; 

return ret;
end;$_$;


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

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

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


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

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

CREATE FUNCTION tiprodsitem(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select item_tipprod from item b, subitem c where  b.item_id=c.sitem_iditem and c.sitem_id= $1 ;$_$;


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

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

CREATE FUNCTION titastoh(integer) RETURNS character
    LANGUAGE sql
    AS $_$select ash_titulo from astoh where ash_id= $1 ;$_$;


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

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

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


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

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

CREATE FUNCTION totchqastc(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sum(chq_importe) from cheques where chq_idastoc= $1;$_$;


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

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

CREATE FUNCTION totchqastce(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sum(chq_importe) from cheques where chq_idastoce= $1;$_$;


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

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

CREATE FUNCTION totdescto(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sum(astc_importe) from astoctas where astc_idastoh= $1 and astc_ctacble=idcbl(astc_codemp,valvaramb(astc_codemp,astc_idptov,'CTADESCTO')::integer);$_$;


ALTER FUNCTION public.totdescto(integer) OWNER TO zona;

--
-- Name: totfactu(integer, smallint, smallint, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION totfactu(integer, smallint, smallint, integer) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
declare
usuario		 alias for $1;
anio		 alias for $2;
mes		 alias for $3;
articulo	 alias for $4;
ret 		 numeric;

begin

if int4eq(articulo,0) then 
    select sum(cfc_importe) into ret from confactur where cfc_usuario=usuario and cfc_anio=anio and cfc_mes=mes;
  else
    select sum(cfc_importe) into ret from confactur where cfc_usuario=usuario and cfc_anio=anio and cfc_mes=mes and cfc_idart=articulo;
end if;

return ret;
end;$_$;


ALTER FUNCTION public.totfactu(integer, smallint, smallint, integer) OWNER TO zona;

--
-- Name: totimpastc(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION totimpastc(integer, integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select astc_importe from astoctas where astc_ctacble= $1 and astc_idastoh= $2 ;$_$;


ALTER FUNCTION public.totimpastc(integer, integer) OWNER TO zona;

--
-- Name: totiva21(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION totiva21(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sum(astc_importe) from astoctas where astc_idastoh= $1 and astc_ctacble=idcbl(astc_codemp,valvaramb(astc_codemp,astc_idptov,'CTAIVA')::integer);$_$;


ALTER FUNCTION public.totiva21(integer) OWNER TO zona;

--
-- Name: totivast(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION totivast(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sum(astc_importe) from astoctas where astc_idastoh= $1 and astc_ctacble=idcbl(astc_codemp,valvaramb(astc_codemp,astc_idptov,'CTAIVAST')::integer);$_$;


ALTER FUNCTION public.totivast(integer) OWNER TO zona;

--
-- Name: totretirado(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION totretirado(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sum(r.ret_cantidad * (s.sitem_imp_dolar / s.sitem_canting)) from retiros r, subitem s where r.ret_idopera= $1 and r.ret_idsitem=s.sitem_id;$_$;


ALTER FUNCTION public.totretirado(integer) OWNER TO zona;

--
-- Name: tposastc(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION tposastc(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sum(astc_importe) from astoctas where astc_idastoh= $1 and astc_importe>0 ;$_$;


ALTER FUNCTION public.tposastc(integer) OWNER TO zona;

--
-- Name: trae_cotiza(smallint, date); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION trae_cotiza(smallint, date) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
declare
moneda		 alias for $1;
fecha		 alias for $2;
ret 		 numeric;
begin
     SELECT  cot_cotiz  INTO     ret 
	    FROM cotiza    
		WHERE int2eq(moneda,cot_moneda) and  
		    date_le(cot_fecha,fecha) 
	    order by cot_fecha desc limit 1;
return ret;
END;$_$;


ALTER FUNCTION public.trae_cotiza(smallint, date) OWNER TO zona;

--
-- Name: traigo_codarticu(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION traigo_codarticu(integer) RETURNS character
    LANGUAGE sql
    AS $_$select artic_codigo from articu a,subitem b where a.artic_id=b.sitem_artic and b.sitem_id= $1 ;$_$;


ALTER FUNCTION public.traigo_codarticu(integer) OWNER TO zona;

--
-- Name: traigo_compbte(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION traigo_compbte(integer) RETURNS character
    LANGUAGE sql
    AS $_$select op_compbte from operaciones a, subitem b where b.sitem_id= $1 and b.sitem_idoper=a.op_id ;$_$;


ALTER FUNCTION public.traigo_compbte(integer) OWNER TO zona;

--
-- Name: traigo_dirunifun(smallint); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION traigo_dirunifun(smallint) RETURNS character
    LANGUAGE sql
    AS $_$select unif_direc from unifun where unif_codigo= $1 ;$_$;


ALTER FUNCTION public.traigo_dirunifun(smallint) OWNER TO zona;

--
-- Name: traigo_moneda(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION traigo_moneda(integer) RETURNS character
    LANGUAGE sql
    AS $_$select mon_simbol from moneda a, item b where a.mon_codigo=b.item_moneda and b.item_id= $1 ;$_$;


ALTER FUNCTION public.traigo_moneda(integer) OWNER TO zona;

--
-- Name: traigo_nomarticu(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION traigo_nomarticu(integer) RETURNS character
    LANGUAGE sql
    AS $_$select artic_descrip from articu where artic_id= $1 ;$_$;


ALTER FUNCTION public.traigo_nomarticu(integer) OWNER TO zona;

--
-- Name: traigo_nomtipoper(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION traigo_nomtipoper(integer) RETURNS character
    LANGUAGE sql
    AS $_$select top_nombre from tipoper where top_codigo= $1 ;$_$;


ALTER FUNCTION public.traigo_nomtipoper(integer) OWNER TO zona;

--
-- Name: traigo_nomunifun(smallint); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION traigo_nomunifun(smallint) RETURNS character
    LANGUAGE sql
    AS $_$select unif_nombre from unifun where unif_codigo= $1 ;$_$;


ALTER FUNCTION public.traigo_nomunifun(smallint) OWNER TO zona;

--
-- Name: traigo_simbtipoper(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION traigo_simbtipoper(integer) RETURNS character
    LANGUAGE sql
    AS $_$select top_comprob from tipoper where top_codigo= $1 ;$_$;


ALTER FUNCTION public.traigo_simbtipoper(integer) OWNER TO zona;

--
-- Name: transfieroweb(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION transfieroweb(integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
wopid		 alias for $1;
ret 		 boolean;
registro	 record;
regist		 record;
registleye	 record;
registwr	 record;
registw2	 record;
disponible	 numeric;
dispon		 numeric;
compromweb	 numeric;
llevo		 numeric;
elultimo	 numeric;
idop		 integer;
primera		 integer;
elestado	 smallint;
begin

ret:='t';
idop:=0;

select wop_estado into elestado from woperaciones where wop_id=wopid;

if found then
    if int2eq(elestado,1::int2) then

	for registro in select 
	    cantidisponib(wret2_idsitem) as x, wret2_cantidad as y
	    from wret2 where wret2_idopera=wopid 
	    loop
		if(booleq(ret,'t')) then
		    if(registro.x < registro.y) then
			ret:='f';
		    end if;
		end if;
	    end loop; 


	if(booleq(ret,'t')) then

		insert into operaciones(op_directo,op_indirecto,op_tipoper,op_idopw,op_operador,op_nrotalzon,op_nrotaldir) select wop_directo,wop_indirecto,wop_tipoper,wop_id,wop_operador,val_talon(wop_tipoper,1),val_talon(wop_tipoper,wop_directo) from woperaciones where wop_id = wopid;

		select op_id into idop from operaciones where op_idopw=wopid;

		for regist in select 
		    * from wret2 where wret2_idopera=wopid
		loop
		    insert into retiros (ret_idopera,ret_idsitem,ret_item,ret_sitem,ret_cantidad) values (idop,regist.wret2_idsitem,regist.wret2_item,regist.wret2_sitem,regist.wret2_cantidad);
		    update wsubitem set wsitem_cantcomp=wsitem_cantcomp+regist.wret2_cantidad, wsitem_cantcompw=wsitem_cantcompw-regist.wret2_cantidad where wsitem_id=regist.wret2_idsitem;
		end loop; 

		for registleye in select 
		    * from wleyenrexp where wleyr_idoper=wopid
		loop
		    insert into leyenrexp (leyr_idoper,leyr_nro,leyr_leyenda) values (idop,registleye.wleyr_nro,registleye.wleyr_leyenda);
		end loop; 

		update woperaciones set wop_estado=50 where wop_id=wopid;

		for registwr in select 
		    * from retiros where ret_idopera=idop
		loop
		    insert into wretiros (wret_id,wret_idopera,wret_idsitem,wret_item,wret_sitem,wret_cantidad,wret_idsitemc,wret_compbte,wret_tipoper,wret_nrotaldir,wret_estado) 
			values (registwr.ret_id,registwr.ret_idopera,registwr.ret_idsitem,registwr.ret_item,registwr.ret_sitem,registwr.ret_cantidad,registwr.ret_idsitemc,compbteoper(registwr.ret_idopera),tipoperdeop(registwr.ret_idopera),nrotaldiroper(registwr.ret_idopera),1::int2);
		end loop; 


	    else


		for registw2 in select 
		    * from wret2 where wret2_idopera=wopid 
	        loop

		primera:=0;
		elultimo:=0;
		dispon:=0;
		dispon:=cantidisponib(registw2.wret2_idsitem);
		elultimo:=registw2.wret2_cantidad;

		if(elultimo<=dispon) then
			if(int4eq(primera,0)) then
			    insert into operaciones(op_directo,op_indirecto,op_tipoper,op_idopw,op_operador,op_nrotalzon,op_nrotaldir) select wop_directo,wop_indirecto,wop_tipoper,wop_id,wop_operador,val_talon(wop_tipoper,1),val_talon(wop_tipoper,wop_directo) from woperaciones where wop_id = wopid;
			    select op_id into idop from operaciones where op_idopw=wopid;
			    for registleye in select 
				* from wleyenrexp where wleyr_idoper=wopid
			    loop
				insert into leyenrexp (leyr_idoper,leyr_nro,leyr_leyenda) values (idop,registleye.wleyr_nro,registleye.wleyr_leyenda);
			    end loop; 
			    primera:=1;
			end if;

			update wsubitem set wsitem_cantcompw=wsitem_cantcompw + registw2.wret2_cantidad where wsitem_id=registw2.wret2_idsitem;

		    else
			if(dispon <= 0) then
				insert into temporalweb (wtmp_idsitem,wtmp_disponib,wtmp_compweb,wtmp_idret,wtmp_valor) values (registw2.wret2_idsitem,dispon,elultimo,registw2.wret2_id,-1);
    			    else
				insert into temporalweb (wtmp_idsitem,wtmp_disponib,wtmp_compweb,wtmp_idret,wtmp_valor) values (registw2.wret2_idsitem,dispon,elultimo,registw2.wret2_id,dispon);
			end if;
		end if;
		end loop; 

		ret:=reparoweb(1);
	end if;
    end if;
end if;
return idop;
end;$_$;


ALTER FUNCTION public.transfieroweb(integer) OWNER TO zona;

--
-- Name: transfreexpdeweb(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION transfreexpdeweb(integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
wopid		 alias for $1;
ret 		 boolean;
registro	 record;
regist		 record;
registleye	 record;
registwr	 record;
registw2	 record;
disponible	 numeric;
dispon		 numeric;
compromweb	 numeric;
llevo		 numeric;
elultimo	 numeric;
idop		 integer;
primera		 integer;
entre		 integer;
elestado	 smallint;
aux_texto	 text;
aux_texto1	 text;
aux_texto2	 text;
aux_texto3	 text;
begin

ret:='t';
entre:=0;
idop:=0;

select wop_estado into elestado from woperaciones where wop_id=wopid;

if found then
    if int2eq(elestado,1::int2) then
	for registro in select 
	    cantidisponib(wret2_idsitem) as x, wret2_cantidad as y
	    from wret2 where wret2_idopera=wopid 
	    loop
		entre:=1;
		if(booleq(ret,'t')) then
		    if(registro.x < registro.y) then
			ret:='f';
		    end if;
		end if;
	    end loop; 


    if int4eq(entre,0) then
	ret:='f';
    end if;


	if(booleq(ret,'t')) then

		insert into operaciones(op_directo,op_indirecto,op_tipoper,op_idopw,op_operador,op_nrotalzon,op_nrotaldir,op_consig) select wop_directo,wop_indirecto,wop_tipoper,wop_id,wop_operador,val_talon(wop_tipoper,1),val_talon(wop_tipoper,wop_directo),wop_consig from woperaciones where wop_id = wopid;

		select op_id into idop from operaciones where op_idopw=wopid;

		for regist in select 
		    * from wret2 where wret2_idopera=wopid
		loop
		    insert into retiros (ret_idopera,ret_idsitem,ret_item,ret_sitem,ret_cantidad) values (idop,regist.wret2_idsitem,regist.wret2_item,regist.wret2_sitem,regist.wret2_cantidad);
		    update wsubitem set wsitem_cantcomp=wsitem_cantcomp+regist.wret2_cantidad, wsitem_cantcompw=wsitem_cantcompw-regist.wret2_cantidad where wsitem_id=regist.wret2_idsitem;
		end loop; 

		for registleye in select 
		    * from wleyenrexp where wleyr_idoper=wopid
		loop
		    insert into leyenrexp (leyr_idoper,leyr_nro,leyr_leyenda) values (idop,registleye.wleyr_nro,registleye.wleyr_leyenda);
		end loop; 

		update woperaciones set wop_estado=50 where wop_id=wopid;

		for registwr in select 
		    * from retiros where ret_idopera=idop
		loop
		    insert into wretiros (wret_id,wret_idopera,wret_idsitem,wret_item,wret_sitem,wret_cantidad,wret_idsitemc,wret_compbte,wret_tipoper,wret_nrotaldir,wret_estado) 
			values (registwr.ret_id,registwr.ret_idopera,registwr.ret_idsitem,registwr.ret_item,registwr.ret_sitem,registwr.ret_cantidad,registwr.ret_idsitemc,compbteoper(registwr.ret_idopera),tipoperdeop(registwr.ret_idopera),nrotaldiroper(registwr.ret_idopera),1::int2);
		end loop; 


	    else


		for registro in select 
		    * from wret2 where wret2_idopera=wopid 
		loop

		    delete from wretiros where wret_idsitem=registro.wret2_idsitem; 

		    for regist in select 
			* from retiros where ret_idsitem=registro.wret2_idsitem
			loop
			    insert into wretiros (wret_id,wret_idopera,wret_idsitem,wret_item,wret_sitem,wret_cantidad,wret_idsitemc,wret_compbte,wret_tipoper,wret_nrotaldir) 
				values (regist.ret_id,regist.ret_idopera,regist.ret_idsitem,regist.ret_item,regist.ret_sitem,regist.ret_cantidad,regist.ret_idsitemc,compbteoper(regist.ret_idopera),tipoperdeop(regist.ret_idopera),nrotaldiroper(regist.ret_idopera));
			end loop; 


		    if(registro.wret2_cantidad<=cantidisponib(registro.wret2_idsitem)) then

			    update wsubitem set wsitem_cantcompw=cantcompwdeidwsitem(registro.wret2_idsitem),wsitem_canting=cantingdeidsitem(registro.wret2_idsitem),wsitem_cantcomp=cantcompdeidsitem(registro.wret2_idsitem),wsitem_cantret=cantretdeidsitem(registro.wret2_idsitem),wsitem_cantmala=cantmaladeidsitem(registro.wret2_idsitem) where wsitem_id=registro.wret2_idsitem;

			else

			    aux_texto2:='<br> SE HA ELIMINADO EL ARTICULO  <B> '||codartdewret2(registro.wret2_id)||'</B> EL CUAL USTED HABIA COMPROMETIDO POR UNA CANTIDAD DE : <B>'||registro.wret2_cantidad||'</B> ';
			    insert into temporalweb (wtmp_idwop,wtmp_idsitem,wtmp_disponib,wtmp_compweb,wtmp_idret,wtmp_valor) values (wopid,registro.wret2_idsitem,cantidisponib(registro.wret2_idsitem),registro.wret2_cantidad,registro.wret2_id,-1);

		    end if;

		end loop; 

		aux_texto:='SE LE COMUNICA QUE NO SE HA PODIDO PROCESAR LA REEXPEDICION NUMERO:  <b>'||wopid||' </b>QUE USTED HA CARGADO EN ESTE SISTEMA OPORTUNAMENTE RELACIONADA AL USUARIO INDIRECTO  <b>'||nomusu(indirectodewop(wopid))||' </b>.  EL MOTIVO DE ESTA MODIFICACION RESPONDE AL PROCESAMIENTO POR PARTE DE OPERADORES DE LA CONCESIONARIA DE REEXPEDICIONES QUE AFECTAN AL/LOS SIGUIENTES ARTICULOS POR USTED COMPROMETIDOS '||aux_texto2||'<BR>   VERIQUE NUEVAMENTE LA OPERACION Y FINALICELA !!!!!!! ';
		ret:=grabonotiweb(directodewop(wopid),5,10,'ERROR EN LA IMPORTACION DE REEXPEDICIONES',aux_texto);
		update woperaciones set wop_estado=11 where wop_id=wopid;



		for registro in select 
    		    * from temporalweb where wtmp_idwop=wopid
		    loop
			update wsubitem set wsitem_canting=cantingdeidsitem(registro.wtmp_idsitem),wsitem_cantcomp=cantcompdeidsitem(registro.wtmp_idsitem),wsitem_cantret=cantretdeidsitem(registro.wtmp_idsitem),wsitem_cantmala=cantmaladeidsitem(registro.wtmp_idsitem) where wsitem_id=registro.wtmp_idsitem;
			delete from wret2 where wret2_id=registro.wtmp_idret;
		    end loop; 
			
		delete from temporalweb where wtmp_idwop=wopid;

	end if;
    end if;
end if;
return idop;
end;$_$;


ALTER FUNCTION public.transfreexpdeweb(integer) OWNER TO zona;

--
-- Name: transitodeop(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION transitodeop(integer) RETURNS character
    LANGUAGE sql
    AS $_$select op_comptrans from operaciones where op_id= $1 ;$_$;


ALTER FUNCTION public.transitodeop(integer) OWNER TO zona;

--
-- Name: transitositem(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION transitositem(integer) RETURNS character
    LANGUAGE sql
    AS $_$select op_comptrans from operaciones a, subitem b where b.sitem_id= $1 and b.sitem_idoper=a.op_id ;$_$;


ALTER FUNCTION public.transitositem(integer) OWNER TO zona;

--
-- Name: trato(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION trato(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select tgte_trato from tipgente where tgte_id= $1;$_$;


ALTER FUNCTION public.trato(integer) OWNER TO zona;

--
-- Name: tratodegente(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION tratodegente(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select tgte_trato from gente,tipgente where tgte_id= gte_tipo and gte_id= $1;$_$;


ALTER FUNCTION public.tratodegente(integer) OWNER TO zona;

--
-- Name: ult_auto(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION ult_auto(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select iol_liviano from inoutliv where iol_estado=101 and iol_barreo= $1 order by iol_fecout desc limit 1;$_$;


ALTER FUNCTION public.ult_auto(integer) OWNER TO zona;

--
-- Name: ult_autoi(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION ult_autoi(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select iol_liviano from inoutliv where iol_estado=1 and iol_barrei= $1 order by iol_fecin desc limit 1;$_$;


ALTER FUNCTION public.ult_autoi(integer) OWNER TO zona;

--
-- Name: ult_cotiz(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION ult_cotiz(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select cot_cotiz  from cotiza where cot_moneda = $1  order by cot_fecha desc limit 1;$_$;


ALTER FUNCTION public.ult_cotiz(integer) OWNER TO zona;

--
-- Name: ulticont(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION ulticont(integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
opid		 alias for $1;
ret 		 int4;
begin
select max(contr_id) into ret from contratos;
return ret;
end;$_$;


ALTER FUNCTION public.ulticont(integer) OWNER TO zona;

--
-- Name: ultiopeindi(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION ultiopeindi(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select op_id from operaciones WHERE op_estado=101 and op_tipoper in (101,105) and op_indirecto= $1 order by op_fechain desc limit 1;$_$;


ALTER FUNCTION public.ultiopeindi(integer) OWNER TO zona;

--
-- Name: ultoperind(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION ultoperind(integer) RETURNS date
    LANGUAGE sql
    AS $_$select op_fechain from operaciones where op_indirecto= $1 and op_estado=101 order by op_fechain desc limit 1;$_$;


ALTER FUNCTION public.ultoperind(integer) OWNER TO zona;

--
-- Name: unifunes(integer, integer, integer, smallint); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION unifunes(integer, integer, integer, smallint) RETURNS character varying
    LANGUAGE plpgsql
    AS $_$
declare
locador		 alias for $1;
locatario	 alias for $2;
idsubt		 alias for $3;
estado		 alias for $4;
ret		 character varying;
registro	 record;

begin

	ret='';
	for registro in select * from contratos
	      where contr_locador=locador and contr_locatario=locatario and contr_idsubt=idsubt
		and contr_estado=estado order by contr_unifun
	    loop
		if(char_length(ret)<1) then
		    ret:=registro.contr_unifun;
		  else
		    ret:=ret ||' -  '||registro.contr_unifun;
		end if;
	    end loop;


return ret;
end;$_$;


ALTER FUNCTION public.unifunes(integer, integer, integer, smallint) OWNER TO zona;

--
-- Name: unifunesnewxd(integer, integer, integer, smallint, character varying); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION unifunesnewxd(integer, integer, integer, smallint, character varying) RETURNS character varying
    LANGUAGE plpgsql
    AS $_$
declare
locador		 alias for $1;
locatario	 alias for $2;
idsubt		 alias for $3;
estado		 alias for $4;
dispos		 alias for $5;
ret		 character varying;
registro	 record;
begin

	ret='';
	if dispos is not null then
	    for registro in select * from contratos
	      where contr_locador=locador and contr_locatario=locatario and contr_idsubt=idsubt
		and contr_estado=estado and bpchareq(trim(dispos),trim(contr_dispos)) order by contr_unifun
		loop
		    if(char_length(ret)<1) then
			ret:=newunif(registro.contr_unifun);
		      else
			ret:=ret ||' -  '||newunif(registro.contr_unifun);
		    end if;
		end loop;
	  else
	    for registro in select * from contratos
	      where contr_locador=locador and contr_locatario=locatario and contr_idsubt=idsubt
		and contr_estado=estado order by contr_unifun
		loop
		    if(char_length(ret)<1) then
			ret:=newunif(registro.contr_unifun);
		      else
			ret:=ret ||' -  '||newunif(registro.contr_unifun);
		    end if;
		end loop;
	end if;


return ret;
end;$_$;


ALTER FUNCTION public.unifunesnewxd(integer, integer, integer, smallint, character varying) OWNER TO zona;

--
-- Name: unifunesxd(integer, integer, integer, smallint, character varying); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION unifunesxd(integer, integer, integer, smallint, character varying) RETURNS character varying
    LANGUAGE plpgsql
    AS $_$
declare
locador		 alias for $1;
locatario	 alias for $2;
idsubt		 alias for $3;
estado		 alias for $4;
dispos		 alias for $5;
ret		 character varying;
registro	 record;
begin

	ret='';
	if dispos is not null then
	    for registro in select * from contratos
	      where contr_locador=locador and contr_locatario=locatario and contr_idsubt=idsubt
		and contr_estado=estado and bpchareq(trim(dispos),trim(contr_dispos)) order by contr_unifun
		loop
		    if(char_length(ret)<1) then
			ret:=registro.contr_unifun;
		      else
			ret:=ret ||' -  '||registro.contr_unifun;
		    end if;
		end loop;
	  else
	    for registro in select * from contratos
	      where contr_locador=locador and contr_locatario=locatario and contr_idsubt=idsubt
		and contr_estado=estado order by contr_unifun
		loop
		    if(char_length(ret)<1) then
			ret:=registro.contr_unifun;
		      else
			ret:=ret ||' -  '||registro.contr_unifun;
		    end if;
		end loop;
	end if;


return ret;
end;$_$;


ALTER FUNCTION public.unifunesxd(integer, integer, integer, smallint, character varying) OWNER TO zona;

--
-- Name: unimeddeitem(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION unimeddeitem(integer) RETURNS smallint
    LANGUAGE sql
    AS $_$select item_unimed from item where item_id= $1 ;$_$;


ALTER FUNCTION public.unimeddeitem(integer) OWNER TO zona;

--
-- Name: usuario_inout(integer, date); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION usuario_inout(integer, date) RETURNS character
    LANGUAGE plpgsql
    AS $_$
declare
    idio		 alias for $1;
    fecha		 alias for $2;
    retval		varchar;

    begin
    retval:='TRAMITES';

    select nomusu(vt_usuario) into retval from visita where date(vt_fecin)=fecha and vt_inout=idio;
    if not found then
	select usudegte(io_gente) into retval from inout where io_id=idio;
    end if;

return retval;
END;$_$;


ALTER FUNCTION public.usuario_inout(integer, date) OWNER TO zona;

--
-- Name: usuariodepo(smallint); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION usuariodepo(smallint) RETURNS integer
    LANGUAGE sql
    AS $_$select unif_usuario from unifun where unif_codigo= $1 ::int2;$_$;


ALTER FUNCTION public.usuariodepo(smallint) OWNER TO zona;

--
-- Name: usucontrapart(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION usucontrapart(integer, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
operacion	 alias for $1;
modo		 alias for $2;
directo		 int4;
indirecto	 int4;
deposito	 int4;
ret 		 int4;
begin

 SELECT  op_directo,op_indirecto,op_deposito  INTO  directo,indirecto,deposito    
    FROM operaciones   WHERE op_id= operacion+1;

if int4eq(modo,1) then ret:=directo; end if;
if int4eq(modo,2) then ret:=indirecto; end if;
if int4eq(modo,3) then ret:=deposito; end if;

return ret;
END;$_$;


ALTER FUNCTION public.usucontrapart(integer, integer) OWNER TO zona;

--
-- Name: usudegente(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION usudegente(integer) RETURNS integer
    LANGUAGE sql
    AS $_$select gte_usu from gente where gte_id= $1 ;$_$;


ALTER FUNCTION public.usudegente(integer) OWNER TO zona;

--
-- Name: usudegente(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION usudegente(integer, integer) RETURNS integer
    LANGUAGE sql
    AS $_$select gte_usu from gente where gte_id= $1 ;$_$;


ALTER FUNCTION public.usudegente(integer, integer) OWNER TO zona;

--
-- Name: usudegte(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION usudegte(integer) RETURNS character
    LANGUAGE sql
    AS $_$select nomusu(gte_usu) from gente  where gte_id= $1 ;$_$;


ALTER FUNCTION public.usudegte(integer) OWNER TO zona;

--
-- Name: usuporcuit(text); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION usuporcuit(text) RETURNS integer
    LANGUAGE sql
    AS $_$select usu_codigo from usuarios where bpchareq(usu_nrocuit,trim($1));$_$;


ALTER FUNCTION public.usuporcuit(text) OWNER TO zona;

--
-- Name: usupordepo(text); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION usupordepo(text) RETURNS integer
    LANGUAGE sql
    AS $_$select unif_usuario from unifun where unif_codmaria=trim($1)::int2;$_$;


ALTER FUNCTION public.usupordepo(text) OWNER TO zona;

--
-- Name: usureal_confactur(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION usureal_confactur(integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
cfcid		 alias for $1;
ret 		 int4;
auxreal		 int4;
auxusu 		 int4;

begin
    select cfc_usuario,cfc_usureal into auxusu,auxreal  
     from confactur where cfc_id=cfcid;

	if auxreal is null then 
		ret:=auxusu;
	    else
		ret:= auxreal;
	end if;

return ret;
end;$_$;


ALTER FUNCTION public.usureal_confactur(integer) OWNER TO zona;

--
-- Name: usuvisita(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION usuvisita(integer, integer) RETURNS integer
    LANGUAGE sql
    AS $_$select vt_usuario from visita where vt_inout= $1 and vt_usuario= $2;$_$;


ALTER FUNCTION public.usuvisita(integer, integer) OWNER TO zona;

--
-- Name: val_talon(integer, integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION val_talon(integer, integer) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
declare
tipoper		 alias for $1;
usuario		 alias for $2;
ret 		 int4;
begin

 SELECT  talop_numero  INTO     ret 
    FROM talonop   WHERE talop_usuario=usuario and talop_tipoper=tipoper;

return ret;
END;$_$;


ALTER FUNCTION public.val_talon(integer, integer) OWNER TO zona;

--
-- Name: valfob_ahora(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION valfob_ahora(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sum((sitem_canting-sitem_cantret)*(sitem_imp_dolar/sitem_canting)) from subitem where sitem_idoper = $1;$_$;


ALTER FUNCTION public.valfob_ahora(integer) OWNER TO zona;

--
-- Name: valfob_reti(integer); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION valfob_reti(integer) RETURNS numeric
    LANGUAGE sql
    AS $_$select sum((r.ret_cantidad)*(s.sitem_imp_dolar/s.sitem_canting)) from subitem s, retiros r where r.ret_idopera = $1  and r.ret_idsitem=s.sitem_id;$_$;


ALTER FUNCTION public.valfob_reti(integer) OWNER TO zona;

--
-- Name: valmer_unifun(integer, smallint, smallint); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION valmer_unifun(integer, smallint, smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
DECLARE
operacion	ALIAS FOR $1; 	-- id de la operacion
caso		ALIAS FOR $2; 	-- Caso 
				--  1=arregla valormerca de unifun por ingreso
				--  2=arregla valormerca de unifun por egreso
modalidad	ALIAS FOR $3; 	-- Modalidad sumo o resto 
				--  1=actualizo normal
				--  2=Me arrepiento y corrijo lo ya hecho
compara 	numeric;
deposito 	int2;
registro 	RECORD;
retval 		boolean;
trans 		boolean;
aux_texto 	text;
BEGIN
retval:='t';		

if modalidad=1 then
	if caso=1 then
		for registro in select sitem_deposito as x,sum(sitem_imp_dolar) as y
    		    from subitem where sitem_idoper=operacion group by sitem_deposito
			loop
			    update unifun set unif_valormerca=unif_valormerca+registro.y
				where unif_codigo=registro.x;
			end loop; 
	    else
		for registro in select ret_idsitem as x,sum(ret_cantidad*precio_unitariod(ret_idsitem)) as y
    		    from retiros where ret_idopera=operacion group by x
			loop
			    select sitem_deposito into deposito from subitem where sitem_id=registro.x;
			    update unifun set unif_valormerca=unif_valormerca-registro.y
				where unif_codigo=deposito;
			end loop; 
	end if;

    else
	if caso=1 then
		for registro in select sitem_deposito as x,sum(sitem_imp_dolar) as y
    		    from subitem where sitem_idoper=operacion group by sitem_deposito
			loop
			    update unifun set unif_valormerca=unif_valormerca-registro.y
				where unif_codigo=registro.x;
			end loop; 
	    else
		for registro in select ret_idsitem as x,sum(ret_cantidad*precio_unitariod(ret_idsitem)) as y
    		    from retiros where ret_idopera=operacion group by x
			loop
			    select sitem_deposito into deposito from subitem where sitem_id=registro.x;
			    update unifun set unif_valormerca=unif_valormerca+registro.y
				where unif_codigo=deposito;
			end loop; 
	end if;
end if;


RETURN retval;
END;$_$;


ALTER FUNCTION public.valmer_unifun(integer, smallint, smallint) OWNER TO zona;

--
-- Name: valmerxunif(smallint); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION valmerxunif(smallint) RETURNS boolean
    LANGUAGE plpgsql
    AS $_$
declare
deposito	 alias for $1;
ret 		 boolean;
total 		 numeric;
depo 		 int2;
registro	 record;
begin

ret:='f';

if(int2eq(deposito,0::int2)) then
    for registro in select 
	sitem_deposito as depos, sum((sitem_canting-sitem_cantret)*(sitem_imp_dolar/sitem_canting)) as totals from subitem where sitem_estado=1 and estadop(sitem_idoper)=101 group by sitem_deposito
	loop
	    ret:='t';
	    update unifun set unif_valormerca=registro.totals where unif_codigo=registro.depos;
	end loop; 

else

    select sum((sitem_canting-sitem_cantret)*(sitem_imp_dolar/sitem_canting)) into total from subitem where sitem_estado=1 and sitem_deposito=deposito and estadop(sitem_idoper)=10;
    ret:='t';
    update unifun set unif_valormerca=total where unif_codigo=deposito;

end if;

return ret;
end;$_$;


ALTER FUNCTION public.valmerxunif(smallint) OWNER TO zona;

--
-- Name: valor_moncte(smallint, date, numeric, numeric); Type: FUNCTION; Schema: public; Owner: zona
--

CREATE FUNCTION valor_moncte(smallint, date, numeric, numeric) RETURNS numeric
    LANGUAGE plpgsql
    AS $_$
declare
moneda		 alias for $1;
fecha		 alias for $2;
cuanto		 alias for $3;
tipo_de_cambio	 alias for $4;
aux_mon		 int2;
cotiz		 numeric;
ret 		 numeric;
begin

 SELECT  var_valor 
 INTO     aux_mon -- Codigo Moneda Homogenea
    FROM varamb    WHERE var_codigo like 'MONH%';

if int2eq(aux_mon,moneda) then
	    ret:= cuanto;
   else
     if numeric_eq(tipo_de_cambio,0::numeric) then -- busco la cotizacion
	    cotiz:=trae_cotiza(moneda,fecha)::numeric;
	    if (cotiz is not null) then 
		    if (cotiz!=0) then 
			ret:=cuanto / cotiz;
		    end if;
		else
		    ret:=0;
	    end if;
	else

	    ret:= cuanto / tipo_de_cambio;

--	    cotiz:=trae_cotiza(1::int2,fecha)::numeric;
--	    if(cotiz) then 
--		    ret:= cuanto * (tipo_de_cambio / cotiz);
--		else
--		    ret:=0;
--	    end if;
    end if;

end if;

return ret;
END;$_$;


ALTER FUNCTION public.valor_moncte(smallint, date, numeric, numeric) OWNER TO zona;

--
