CREATE OR REPLACE FUNCTION f_au_astoctas() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
DECLARE
	total		numeric;
	dias		numeric;
	cuentadxv	integer;
	cuentadxc	integer;
BEGIN
    if int4ne(NEW.astc_estado,OLD.astc_estado) THEN 
	update cheques set chq_estado=NEW.astc_estado where chq_idastoc=NEW.astc_id;
	update monex set mne_estado=NEW.astc_estado where mne_idastoc=NEW.astc_id;
	update docum set doc_estado=NEW.astc_estado where doc_idastoc=NEW.astc_id;
	update compliq set clq_estado=NEW.astc_estado where clq_idastoc=NEW.astc_id;
	END IF;


    select idcbl(NEW.astc_codemp,NEW.astc_idptov,valvaramb(NEW.astc_codemp,NEW.astc_idptov,'DEUDXV')::integer) into cuentadxv;
    select idcbl(NEW.astc_codemp,NEW.astc_idptov,valvaramb(NEW.astc_codemp,NEW.astc_idptov,'DEUDXC')::integer) into cuentadxc;

    if int4ne(NEW.astc_ctacte,OLD.astc_ctacte) THEN 
	if int4eq(OLD.astc_ctacble,cuentadxv) THEN 
	    update emiti set emi_codcli=NEW.astc_ctacte where emi_idastoh=NEW.astc_idastoh;
	    update compliq set clq_idcopr=NEW.astc_ctacte where clq_idastoc=NEW.astc_id;
	END IF;
	if int4eq(OLD.astc_ctacble,cuentadxc) THEN 
		update compra set cpra_prove=NEW.astc_ctacte where cpra_idastoh=NEW.astc_idastoh;
		update gastos set gto_prove=NEW.astc_ctacte where gto_idastoh=NEW.astc_idastoh;
		update liqegr set eg_prove=NEW.astc_ctacte where eg_idastoh=NEW.astc_idastoh;
	END IF;
    END IF;

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

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

    if numeric_ne(NEW.astc_importe,OLD.astc_importe) THEN 
	if int4eq(OLD.astc_ctacble,cuentadxv) THEN 
	    update compliq set clq_importe=NEW.astc_importe where clq_idastoc=NEW.astc_id;
	END IF;
    END IF;


    RETURN NEW;
    END;$$;


ALTER FUNCTION public.f_au_astoctas() OWNER TO sanjor;





