CREATE OR REPLACE PROCEDURE INSERE_ERROSSIMULAPLAVOO(
P_CDFILIAL IN VARCHAR2,
P_NRERROSIMULAPLAVOO IN OUT VARCHAR2,
P_CDCIA IN VARCHAR2,
P_NRVOO IN VARCHAR2,
P_CDTRECHO IN VARCHAR2,
P_DTHRPLAVOOPV IN DATE,
P_DSERRO IN VARCHAR2,
P_CDOPERADOR IN VARCHAR2,
P_NRORG IN NUMBER
)
AS
   PRAGMA AUTONOMOUS_TRANSACTION;
   V_SEQ VARCHAR2(20);
   V_MAX_SEQ NUMBER;
BEGIN
   IF P_DSERRO IS NOT NULL THEN
	   IF P_NRERROSIMULAPLAVOO IS NULL THEN
	      NOVO_CODIGO_NT('ERROSIMULAPLAVOO' || P_CDFILIAL, V_SEQ);
	      P_NRERROSIMULAPLAVOO := TO_NUMBER(V_SEQ);
	   END IF;

	   SELECT MAX(NRSEQUENCIAL)
	     INTO V_MAX_SEQ
	     FROM ERROSIMULAPLAVOO
	    WHERE CDFILIAL = P_CDFILIAL
	      AND NRERROSIMULAPLAVOO = P_NRERROSIMULAPLAVOO;
       
       V_MAX_SEQ := NVL(V_MAX_SEQ, 0) + 1;

	   INSERT INTO ERROSIMULAPLAVOO
	   (CDFILIAL, NRERROSIMULAPLAVOO, NRSEQUENCIAL, 
	   	CDCIA, NRVOO, CDTRECHO, DTHRPLAVOOPV,
	    DSERROBANCO, DSERROTRADUZIDO,
	    NRORG, NRORGINCLUSAO, NRORGULTATU,
	    CDOPERINCLUSAO, CDOPERULTATU,
	    DTINCLUSAO, DTULTATU, IDATIVO)
	   VALUES
	   (P_CDFILIAL, P_NRERROSIMULAPLAVOO, V_MAX_SEQ, 
	   	P_CDCIA, P_NRVOO, P_CDTRECHO, P_DTHRPLAVOOPV,
	    P_DSERRO, NULL,
	    P_NRORG, P_NRORG, P_NRORG,
	    P_CDOPERADOR, P_CDOPERADOR,
	    SYSDATE, SYSDATE, 'S');
   END IF;
   
   COMMIT;
END;
/