CREATE OR REPLACE FUNCTION triggered_set_date_limite_calcule()
    RETURNS TRIGGER
    language plpgsql
AS
$triggered_set_date_limite_calcule$
    BEGIN   
        -- Verifie si l'on est en incompletude
        -- Et selectionne la date_limite_calcule en fonction
        IF NEW.incompletude IS true AND NEW.incomplet_notifie IS true THEN
            NEW.date_limite_calcule = NEW.date_limite_incompletude;
        ELSE 
       		NEW.date_limite_calcule = NEW.date_limite;
        END IF;
        RETURN NEW;
    END;
$triggered_set_date_limite_calcule$;

DROP TRIGGER IF EXISTS trigg_insert_set_date_limite_calcule ON openads.dossier ;
CREATE TRIGGER trigg_insert_set_date_limite_calcule 	 
    BEFORE INSERT ON openads.dossier 	 
    FOR EACH ROW EXECUTE FUNCTION openads.triggered_set_date_limite_calcule(); 	 

DROP TRIGGER IF EXISTS trigg_update_set_date_limite_calcule ON openads.dossier ;
CREATE TRIGGER trigg_update_set_date_limite_calcule 	 
    BEFORE UPDATE OF incompletude,incomplet_notifie,date_limite,date_limite_incompletude ON openads.dossier 	 
    FOR EACH ROW EXECUTE FUNCTION openads.triggered_set_date_limite_calcule();