SET TERM ^ ;

CREATE OR ALTER trigger ttbpdv_conferencia_item_b99iud for tbpdv_conferencia_item
active after insert or update or delete position 99
AS
DECLARE VARIABLE STATUS_ITEM INTEGER;
DECLARE VARIABLE HISTORICO VARCHAR(500);
DECLARE VARIABLE SITUACAO_HISTORICO VARCHAR(500);
BEGIN
  IF(DELETING) THEN
  BEGIN
     STATUS_ITEM = COALESCE((SELECT MAX(X.SITUACAO) FROM TBPDV_CONFERENCIA_ITEM X WHERE X.PDV_CONFERENCIA_ID = OLD.PDV_CONFERENCIA_ID AND X.ID <> OLD.ID), 0);

     UPDATE TBPDV_CONFERENCIA T SET T.STATUS_ITENS = :STATUS_ITEM WHERE T.ID = OLD.PDV_CONFERENCIA_ID;
  END 

  
  IF(UPDATING OR INSERTING) THEN
  BEGIN
     STATUS_ITEM = COALESCE((SELECT MAX(X.SITUACAO) FROM TBPDV_CONFERENCIA_ITEM X WHERE X.PDV_CONFERENCIA_ID = NEW.PDV_CONFERENCIA_ID), 0);

     STATUS_ITEM = IIF(:STATUS_ITEM > NEW.SITUACAO, :STATUS_ITEM, NEW.SITUACAO);
     UPDATE TBPDV_CONFERENCIA T SET T.STATUS_ITENS = :STATUS_ITEM WHERE T.ID = NEW.PDV_CONFERENCIA_ID;

  END 

  IF(HISTORICO <> '') THEN
  BEGIN
      HISTORICO = 'ITEM '||NEW.SEQUENCIA||' ALTERADO '||HISTORICO;
      EXECUTE PROCEDURE SPI_HISTORICO('TBPDV_CONFERENCIA', NEW.PDV_CONFERENCIA_ID, HISTORICO);
  END
END
^

SET TERM ; ^

