-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-- Trigger de UPDATE: tua_sga_actas
-- AFTER UPDATE
-- Tabla: sga_actas
-- Version: 3.0.0
-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

-- DROP FUNCTION ftua_sga_actas ();
CREATE OR REPLACE FUNCTION ftua_sga_actas () RETURNS trigger AS 
$BODY$
DECLARE
   cur_folios record;
   cnt_folios smallint;

BEGIN
	 cnt_folios := 0;
	 
   -- Cuando se cierra el acta o se anula el acta, debo registrar los folios fisicos.
   IF OLD.estado <> NEW.estado AND (NEW.estado = 'C' OR NEW.estado = 'B') THEN
     FOR cur_folios IN SELECT distinct folio
                         FROM sga_actas_detalle
                         WHERE sga_actas_detalle.id_acta = NEW.id_acta
     LOOP
       cnt_folios := cnt_folios + 1;
       -- Inserto el Folio
       INSERT INTO sga_actas_folios (id_acta, folio) VALUES (NEW.id_acta, cur_folios.folio);

     END LOOP;
     
     -- Si no hay alumnos en el detalle del acta, inserto igualmente un folio al acta.
     IF cnt_folios = 0 THEN
       INSERT INTO sga_actas_folios (id_acta, folio) VALUES (NEW.id_acta, 1);
     END IF;
     
   END IF;
   
   RETURN NEW;
END;
$BODY$
LANGUAGE 'plpgsql';


-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-- Trigger de UPDATE sobre sga_actas
-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-- DROP TRIGGER tua_sga_actas ON sga_actas RESTRICT;
CREATE TRIGGER tua_sga_actas
       AFTER UPDATE ON sga_actas
       FOR EACH ROW EXECUTE PROCEDURE ftua_sga_actas();

