CREATE OR ALTER TRIGGER TTBNFE_B09UI FOR TBNFE
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
DECLARE VARIABLE OLD_DATA_COMPETENCIA DATE;
BEGIN
    IF(INSERTING)THEN
    BEGIN
        IF(NEW.DATA_COMPETENCIA IS NOT NULL)THEN
        BEGIN
           NEW.DATA_COMPETENCIA = FN_START_OF_MONTH_2(NEW.DATA_COMPETENCIA);
        END
    
        IF(NEW.DATA_COMPETENCIA IS NULL)THEN
        BEGIN
           NEW.DATA_COMPETENCIA = FN_START_OF_MONTH_2(NEW.DATA_ENTRADA);
        END
    END
    IF(UPDATING)THEN
    BEGIN
        IF(NEW.DATA_COMPETENCIA IS NOT NULL AND NEW.DATA_COMPETENCIA IS DISTINCT FROM OLD.DATA_COMPETENCIA)THEN
        BEGIN
           NEW.DATA_COMPETENCIA  = FN_START_OF_MONTH_2(NEW.DATA_COMPETENCIA);
           :OLD_DATA_COMPETENCIA = FN_START_OF_MONTH_2(OLD.DATA_COMPETENCIA);
           IF(NEW.DATA_COMPETENCIA IS DISTINCT FROM :OLD_DATA_COMPETENCIA)THEN
           BEGIN
              UPDATE TBNFE_PARCELAMENTO A SET A.DATA_COMPETENCIA = NEW.DATA_COMPETENCIA WHERE A.NFE_CONTROLE = NEW.CONTROLE;
           END
        END
    END
END;

CREATE OR ALTER TRIGGER TTBNFS_B09UI FOR TBNFS
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
DECLARE VARIABLE OLD_DATA_COMPETENCIA DATE;
BEGIN
    IF(INSERTING)THEN
    BEGIN
        IF(NEW.DATA_COMPETENCIA IS NOT NULL)THEN
        BEGIN
           NEW.DATA_COMPETENCIA = FN_START_OF_MONTH_2(NEW.DATA_COMPETENCIA);
        END
    
        IF(NEW.DATA_COMPETENCIA IS NULL)THEN
        BEGIN
           NEW.DATA_COMPETENCIA = FN_START_OF_MONTH_2(NEW.DATA_EMISSAO);
        END
    END
    IF(UPDATING)THEN
    BEGIN
        IF(NEW.DATA_COMPETENCIA IS NOT NULL AND NEW.DATA_COMPETENCIA IS DISTINCT FROM OLD.DATA_COMPETENCIA)THEN
        BEGIN
           NEW.DATA_COMPETENCIA  = FN_START_OF_MONTH_2(NEW.DATA_COMPETENCIA);
           :OLD_DATA_COMPETENCIA = FN_START_OF_MONTH_2(OLD.DATA_COMPETENCIA);
           IF(NEW.DATA_COMPETENCIA IS DISTINCT FROM :OLD_DATA_COMPETENCIA)THEN
           BEGIN
              UPDATE TBNFS_PARCELAMENTO A SET A.DATA_COMPETENCIA = NEW.DATA_COMPETENCIA WHERE A.NFS_CONTROLE = NEW.CONTROLE;
           END
        END
    END
END;