SET TERM ^ ;

CREATE OR ALTER trigger ttbpedido_b10i for tbpedido
active before insert position 0
AS
DECLARE VARIABLE STATUS_REP VARCHAR(1);
BEGIN

  IF(NEW.ECOMMERCE = 1)THEN
  BEGIN
    NEW.REPRESENTANTE_CODIGO = COALESCE((SELECT FIRST 1 P.VALOR_EXT  FROM TBCONTROLE_N P WHERE P.ID = 272),0);
    NEW.FAMILIA_CODIGO = 0;
    --NEW.STATUS_ECOMMERCE = 2;
    NEW.STATUS_PAGAMENTO = 1;
    NEW.CODIGO_RASTREIO = '';
    NEW.CTE = '';

    UPDATE OR INSERT INTO TBUPDATE_ECOMMERCE (TABELA, TABELA_ID, SUB_ID) VALUES ('TBPEDIDO', NEW.PEDIDO, 0) MATCHING (TABELA, TABELA_ID, SUB_ID);
  END

  IF(NEW.ECOMMERCE = 2 AND coalesce(NEW.REPRESENTANTE_CODIGO,0) = 0)THEN
  BEGIN
    NEW.REPRESENTANTE_CODIGO = COALESCE( FN_PARAMETRO('SISTEMA.REPRESENTANTE_LACLOFIT'),0);
    NEW.FAMILIA_CODIGO = 0;
    --NEW.STATUS_ECOMMERCE = 2;
    NEW.STATUS_PAGAMENTO = 1;
    NEW.CODIGO_RASTREIO = '';
    NEW.CTE = '';
  END

  IF(NEW.REPRESENTANTE_CODIGO = 0 OR NEW.REPRESENTANTE_CODIGO IS NULL)THEN
  BEGIN
    EXCEPTION "..."'REPRESENTANTE DO PEDIDO INVALIDO OU NAO CADASTRADO, OPERACAO CANCELADA!';
  END

  STATUS_REP = COALESCE((SELECT FIRST 1 A.STATUS FROM TBREPRESENTANTE A WHERE A.CODIGO = COALESCE(NEW.REPRESENTANTE_CODIGO, 0)),0);
  IF(COALESCE(STATUS_REP, '') = '0')THEN
  BEGIN
     EXCEPTION "..."'REPRESENTANTE DO PEDIDO INATIVO OU NAO CADASTRADO, OPERACAO CANCELADA!';
  END
END
^

SET TERM ; ^

