	SET TERM ^ ;

	ALTER TABLE TBPEDIDO_ITEM
	ADD ALTERANDO_CAMBIO SMALLINT
	DEFAULT 0 ^

	CREATE OR ALTER TRIGGER TBPEDIDO_ITEM_SALDO_B1U_22 FOR TBPEDIDO_ITEM_SALDO
	ACTIVE BEFORE UPDATE POSITION 0
	AS
	DECLARE VARIABLE HISTORICO VARCHAR(500);
	BEGIN
	  HISTORICO = '';
	  IF(OLD.QUANTIDADE IS DISTINCT FROM NEW.QUANTIDADE)THEN
	  BEGIN
		HISTORICO = ' SALDO: '||COALESCE(OLD.QUANTIDADE,0.00)||' -> '||COALESCE(NEW.QUANTIDADE,0.00);
	  END
	  IF(HISTORICO <> '')THEN
	  BEGIN
		HISTORICO = 'ITEM SEQ.'||COALESCE((SELECT FIRST 1 FN_LPAD(ITEM.SEQUENCIA,3,0) FROM TBPEDIDO_ITEM ITEM WHERE ITEM.PEDIDO = NEW.PEDIDO AND ITEM.CONTROLE = NEW.PEDIDO_ITEM_CONTROLE),'000')||' ALTERADO'||:HISTORICO;

		EXECUTE PROCEDURE SPI_HISTORICO('TBPEDIDO',NEW.PEDIDO,:HISTORICO);
	  END
	END
	^

	CREATE OR ALTER TRIGGER TTBPEDIDO_ITEM_A5U_01 FOR TBPEDIDO_ITEM
	ACTIVE AFTER UPDATE POSITION 5
	AS
	BEGIN

	 IF(COALESCE(NEW.ALTERANDO_CAMBIO, 0) = 0) THEN
	 BEGIN
	  IF (OLD.QUANTIDADE <> NEW.QUANTIDADE OR
		  OLD.T01 <> NEW.T01 OR OLD.T02 <> NEW.T02 OR
		  OLD.T03 <> NEW.T03 OR OLD.T04 <> NEW.T04 OR
		  OLD.T05 <> NEW.T05 OR OLD.T06 <> NEW.T06 OR
		  OLD.T07 <> NEW.T07 OR OLD.T08 <> NEW.T08 OR
		  OLD.T09 <> NEW.T09 OR OLD.T10 <> NEW.T10 OR
		  OLD.T11 <> NEW.T11 OR OLD.T12 <> NEW.T12 OR
		  OLD.T13 <> NEW.T13 OR OLD.T14 <> NEW.T14 OR
		  OLD.T15 <> NEW.T15 OR OLD.T16 <> NEW.T16 OR
		  OLD.T17 <> NEW.T17 OR OLD.T18 <> NEW.T18 OR
		  OLD.T19 <> NEW.T19 OR OLD.T20 <> NEW.T20) THEN
		  BEGIN
			DELETE FROM TBPEDIDO_ITEM_SALDO
			WHERE PEDIDO_ITEM_CONTROLE = NEW.CONTROLE
			  AND PEDIDO = NEW.PEDIDO;

			INSERT INTO TBPEDIDO_ITEM_SALDO (
			  PEDIDO_ITEM_CONTROLE, PEDIDO, QUANTIDADE,
			  T01, T02, T03, T04, T05, T06, T07, T08, T09, T10,
			  T11, T12, T13, T14, T15, T16, T17, T18, T19, T20)
			  VALUES (NEW.CONTROLE, NEW.PEDIDO, NEW.QUANTIDADE,
			  NEW.T01, NEW.T02, NEW.T03, NEW.T04, NEW.T05,
			  NEW.T06, NEW.T07, NEW.T08, NEW.T09, NEW.T10,
			  NEW.T11, NEW.T12, NEW.T13, NEW.T14, NEW.T15,
			  NEW.T16, NEW.T17, NEW.T18, NEW.T19, NEW.T20);
		  END
	  END

	--   IF (NEW.MARGEM < 0) THEN
	--       BEGIN
	--       NEW.MARGEM = 0;
	--       END
		
	END^

	SET TERM ; ^

