SET TERM ^ ;

CREATE trigger ttbpdv_cfe_item_b05iu for tbpdv_cfe_item
active before insert or update position 5
AS
DECLARE VARIABLE CHECK_ACTION_PED INTEGER;
DECLARE VARIABLE CHECK_ACTION_PRE INTEGER;
DECLARE VARIABLE VENDEDOR_AUX_ID INTEGER;
BEGIN
    /* CHECAGEM PARA PREENCHIMENTO DO CAMPO VENDEDOR COM BASE NO PEDIDO */

    :CHECK_ACTION_PED = 0;

    IF(INSERTING AND NEW.PEDIDO IS NOT NULL AND NEW.PEDIDO > 0) THEN
    BEGIN
        :CHECK_ACTION_PED = 1;

    END ELSE IF(UPDATING AND (OLD.PEDIDO IS DISTINCT FROM NEW.PEDIDO) AND NEW.PEDIDO > 0) THEN
    BEGIN
        :CHECK_ACTION_PED = 1;
    END

    IF(:CHECK_ACTION_PED = 1) THEN
    BEGIN
        :VENDEDOR_AUX_ID = COALESCE((SELECT FIRST 1 COALESCE(T.VENDEDOR_ID, 0) FROM TBPEDIDO T WHERE T.PEDIDO = NEW.PEDIDO), 0);
        NEW.VENDEDOR_ID = :VENDEDOR_AUX_ID;
    END

     /* CHECAGEM PARA PREENCHIMENTO DO CAMPO VENDEDOR COM BASE NO PRE_PEDIDO */
    :CHECK_ACTION_PRE = 0;

    IF(INSERTING AND NEW.CONFERENCIA_ID IS NOT NULL AND NEW.CONFERENCIA_ID > 0) THEN
    BEGIN
        :CHECK_ACTION_PRE = 1;

    END ELSE IF(UPDATING AND (OLD.CONFERENCIA_ID IS DISTINCT FROM NEW.CONFERENCIA_ID) AND NEW.CONFERENCIA_ID > 0) THEN
    BEGIN
        :CHECK_ACTION_PRE = 1;
    END

    IF(:CHECK_ACTION_PRE = 1) THEN
    BEGIN
        :VENDEDOR_AUX_ID = COALESCE((SELECT FIRST 1 COALESCE(T.VENDEDOR_ID, 0) FROM TBPDV_CONFERENCIA T WHERE T.ID = NEW.CONFERENCIA_ID), 0);
        NEW.VENDEDOR_ID = :VENDEDOR_AUX_ID;
    END

    IF(NEW.VENDEDOR_ID = 0) THEN
    BEGIN
        NEW.VENDEDOR_ID = COALESCE((SELECT FIRST 1 COALESCE(T.VENDEDOR_ID, 0) FROM TBPDV_CFE T WHERE T.ID = NEW.PDV_CFE_ID), 0);
    END
END
^

SET TERM ; ^

COMMENT ON TRIGGER TTBPDV_CFE_ITEM_B05IU IS 'PREENCHIMENTO DO CAMPO VENDEDOR ID, COM BASE NO PEDIDO/PRE PEDIDO OU CABECALHO DO CFE';


SET TERM ^ ;

CREATE trigger ttbnfs_item_b05iu for tbnfs_item
active before insert or update position 2
AS
DECLARE VARIABLE CHECK_ACTION_PED INTEGER;
DECLARE VARIABLE CHECK_ACTION_PRE INTEGER;
DECLARE VARIABLE VENDEDOR_AUX_ID INTEGER;
BEGIN
    /* CHECAGEM PARA PREENCHIMENTO DO CAMPO VENDEDOR COM BASE NO PEDIDO */

    :CHECK_ACTION_PED = 0;
    
    IF(INSERTING AND NEW.PEDIDO IS NOT NULL AND NEW.PEDIDO > 0) THEN
    BEGIN
        :CHECK_ACTION_PED = 1;
    
    END ELSE IF(UPDATING AND (OLD.PEDIDO IS DISTINCT FROM NEW.PEDIDO) AND NEW.PEDIDO > 0) THEN
    BEGIN
        :CHECK_ACTION_PED = 1;
    END
    
    IF(:CHECK_ACTION_PED = 1) THEN
    BEGIN
        :VENDEDOR_AUX_ID = COALESCE((SELECT FIRST 1 COALESCE(T.VENDEDOR_ID, 0) FROM TBPEDIDO T WHERE T.PEDIDO = NEW.PEDIDO), 0);
        NEW.VENDEDOR_ID = :VENDEDOR_AUX_ID;
    END

    IF(NEW.VENDEDOR_ID = 0) THEN
    BEGIN
        NEW.VENDEDOR_ID = COALESCE((SELECT FIRST 1 COALESCE(T.VENDEDOR_ID, 0) FROM TBNFS T WHERE T.CONTROLE = NEW.NFS_CONTROLE), 0);
    END
END
^

SET TERM ; ^

