CREATE trigger ttbestoque_cliente_b02i for tbestoque_cliente
active before insert position 1
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN
    HISTORICO = '';

    IF ( NEW.ID > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||' REGISTRO INCLUIDO';
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBESTOQUE_CLIENTE',NEW.ID, HISTORICO);
    END
END;


CREATE trigger ttbestoque_cliente_b01d for tbestoque_cliente
active before delete position 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN
    HISTORICO = '';

    IF ( OLD.ID > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||' REGISTRO EXCLUIDO';
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBESTOQUE_CLIENTE',OLD.ID, HISTORICO);
    END
END;


CREATE trigger ttbestoque_cliente_b01u for tbestoque_cliente
active before update position 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN
    HISTORICO = '';

    IF ( NEW.EMPRESA_ID IS DISTINCT FROM OLD.EMPRESA_ID) THEN
    BEGIN
        HISTORICO = HISTORICO||' CLIENTE:'||COALESCE(OLD.EMPRESA_ID, 0)||'->'||COALESCE(NEW.EMPRESA_ID, 0);
    END

    IF ( NEW.OBSERVACAO IS DISTINCT FROM OLD.OBSERVACAO) THEN
    BEGIN
        HISTORICO = HISTORICO||' OBS:'||COALESCE(OLD.OBSERVACAO, '')||'->'||COALESCE(NEW.OBSERVACAO, '');
    END


    IF (HISTORICO <> '') THEN
    BEGIN
        HISTORICO = ' REG.ALTERADO: '||HISTORICO;
        EXECUTE PROCEDURE SPI_HISTORICO('TBESTOQUE_CLIENTE',NEW.ID, HISTORICO);
    END
END;


CREATE trigger ttbestoque_cliente_b02d for tbestoque_cliente
active before delete position 1
AS
BEGIN
   IF(OLD.ID > 0) THEN
   BEGIN
      DELETE FROM TBESTOQUE_CLIENTE_ITEM WHERE ESTOQUE_CLIENTE_ID = OLD.ID;
   END
END;


